/**
 * Student Resources — PR 3 §6.3
 *
 * Read-only mirror of the teacher Resources hub. Students browse their enrolled
 * subjects (the controller scopes /api/subjects by enrollment for `student` and
 * `parent` roles), then drill into tabs of syllabus / test papers / homework
 * sheets / past exam papers — each tab is just a filtered AttachmentList.
 * No upload UI here; that's the teacher's job in teacher/Resources.tsx.
 */

import { useEffect, useState } from 'react';
import {
  BookOpen, ChevronLeft, Search, BookMarked,
  FileText, FileSpreadsheet, Presentation, FileArchive
} from 'lucide-react';
import api from '../../store/api';
import { AttachmentList } from '../../components/AttachmentList';
import { useEducationTerms } from '../../utils/educationTerms';

interface Subject {
  id: number;
  uid: string;
  name: string;
  code: string;
  class_id?: number;
  class_name?: string;
}

type TabId = 'syllabus' | 'test_paper' | 'homework_sheet' | 'past_exam';

const TAB_META: Record<TabId, { label: string; Icon: typeof FileText }> = {
  syllabus: { label: 'Curriculum & Syllabus', Icon: FileText },
  test_paper: { label: 'Test Papers', Icon: FileSpreadsheet },
  homework_sheet: { label: 'Homework Sheets', Icon: FileText },
  past_exam: { label: 'Past Exam Papers', Icon: Presentation },
};

export default function StudentResources() {
  const terms = useEducationTerms();
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [selectedSubject, setSelectedSubject] = useState<Subject | null>(null);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [activeSubTab, setActiveSubTab] = useState<TabId>('syllabus');

  useEffect(() => {
    setLoading(true);
    api.get('/subjects')
      .then(res => setSubjects(Array.isArray(res.data) ? res.data : []))
      .catch(err => console.error('Failed to load subjects:', err))
      .finally(() => setLoading(false));
  }, []);

  const filteredSubjects = subjects.filter(s =>
    s.name.toLowerCase().includes(search.toLowerCase()) ||
    s.code?.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="p-4 sm:p-8 space-y-6 max-w-7xl mx-auto">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-border pb-6">
        <div>
          <div className="flex items-center gap-2">
            <BookMarked className="text-primary" size={24} />
            <h1 className="text-2xl font-black text-text tracking-tight uppercase">{terms.subjects} Resources</h1>
          </div>
          <p className="text-xs text-text-muted mt-1 uppercase font-bold tracking-widest">
            {selectedSubject ? `${selectedSubject.name} (${selectedSubject.code})` : `Browse your enrolled ${terms.subjects}`}
          </p>
        </div>
        {selectedSubject && (
          <button
            onClick={() => setSelectedSubject(null)}
            className="flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card hover:bg-muted text-text-muted hover:text-text transition-all text-xs font-black uppercase tracking-widest shadow-sm"
          >
            <ChevronLeft size={16} /> Back to {terms.subjects}
          </button>
        )}
      </div>

      {!selectedSubject ? (
        <div className="space-y-6">
          <div className="flex max-w-md bg-card border border-border rounded-2xl px-4 py-3 items-center gap-3">
            <Search className="text-text-muted/40 shrink-0" size={18} />
            <input
              type="text"
              placeholder={`Search your ${terms.subjects}...`}
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="w-full bg-transparent border-none outline-none text-sm font-semibold placeholder:text-text-muted/40 text-text"
            />
          </div>

          {loading ? (
            <div className="py-20 text-center">
              <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
              <p className="text-xs font-black uppercase tracking-widest text-text-muted">Loading subjects…</p>
            </div>
          ) : filteredSubjects.length === 0 ? (
            <div className="py-20 text-center bg-card border border-border rounded-3xl">
              <BookOpen size={48} className="mx-auto text-text-muted/20 mb-4" />
              <p className="text-xs font-black uppercase tracking-widest text-text-muted">
                {subjects.length === 0
                  ? `No enrolled ${terms.subjects} yet`
                  : `No ${terms.subjects.toLowerCase()} match your search`}
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredSubjects.map(s => (
                <div
                  key={s.id}
                  onClick={() => setSelectedSubject(s)}
                  className="bg-card border border-border rounded-3xl p-6 hover:shadow-xl hover:shadow-primary/5 hover:border-primary/20 transition-all cursor-pointer group flex flex-col justify-between min-h-[160px]"
                >
                  <div>
                    <span className="text-[0.6rem] font-black uppercase tracking-widest px-2 py-1 rounded-md bg-primary/10 text-primary border border-primary/10">
                      {s.code || 'SUBJ'}
                    </span>
                    <h3 className="text-lg font-bold text-text mt-3 group-hover:text-primary transition-colors leading-snug">
                      {s.name}
                    </h3>
                  </div>
                  <div className="flex justify-between items-center border-t border-border/50 pt-4 mt-4">
                    <span className="text-[0.65rem] font-bold text-text-muted uppercase">
                      {s.class_name || `General ${terms.subject}`}
                    </span>
                    <div className="text-primary group-hover:translate-x-1 transition-transform">
                      <ChevronLeft size={16} className="rotate-180" />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          <div className="lg:col-span-3 flex flex-row lg:flex-col overflow-x-auto lg:overflow-x-visible gap-2 bg-card border border-border p-2 rounded-2xl lg:rounded-3xl shrink-0">
            {(Object.keys(TAB_META) as TabId[]).map(tabId => {
              const meta = TAB_META[tabId];
              const isSelected = activeSubTab === tabId;
              return (
                <button
                  key={tabId}
                  onClick={() => setActiveSubTab(tabId)}
                  className={`flex items-center gap-2 px-4 py-3 rounded-xl text-xs font-black uppercase tracking-wider text-left transition-all flex-1 lg:flex-initial whitespace-nowrap ${
                    isSelected
                      ? 'bg-primary text-white shadow-md'
                      : 'hover:bg-muted text-text-muted hover:text-text'
                  }`}
                >
                  <meta.Icon size={14} />
                  {meta.label}
                </button>
              );
            })}
          </div>

          <div className="lg:col-span-9 space-y-6">
            <div className="bg-card border border-border rounded-3xl p-6 sm:p-8 space-y-6 text-left">
              <div>
                <h2 className="text-lg font-black text-text uppercase tracking-tight">
                  {TAB_META[activeSubTab].label}
                </h2>
                <p className="text-xs text-text-muted uppercase tracking-widest mt-1 font-bold">
                  Files uploaded by your teacher for {selectedSubject.name}
                </p>
              </div>

              <AttachmentList
                parent_kind="subject"
                parent_id={selectedSubject.id}
                emptyMessage={`No ${TAB_META[activeSubTab].label.toLowerCase()} uploaded yet for this ${terms.subject}.`}
                captionPrefix={activeSubTab}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}