/**
 * Parent Resources — PR 3 §7.2
 *
 * Per-child subject resources viewer. Mirrors the student Resources surface
 * (subject cards → tabs of syllabus / test papers / homework sheets / past
 * exam papers, all backed by AttachmentList) but with a child switcher at the
 * top. The /api/subjects endpoint is auto-scoped to "subjects for any class
 * one of the parent's children is enrolled in" when the caller is a parent
 * (see PR 3 server-side change in subjects.controller.js).
 */

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

interface Child {
  id: number;
  first_name: string;
  last_name: string;
  class_name?: string;
  grade?: string;
}

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 ParentResources() {
  const terms = useEducationTerms();
  const [children, setChildren] = useState<Child[]>([]);
  const [selectedChild, setSelectedChild] = useState<Child | null>(null);
  const [showChildPicker, setShowChildPicker] = useState(false);

  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [selectedSubject, setSelectedSubject] = useState<Subject | null>(null);
  const [loadingSubjects, setLoadingSubjects] = useState(false);

  const [activeSubTab, setActiveSubTab] = useState<TabId>('syllabus');
  const [search, setSearch] = useState('');

  // Load the parent's children once on mount.
  useEffect(() => {
    api.get('/users/children')
      .then(res => {
        const list: Child[] = Array.isArray(res.data) ? res.data : [];
        setChildren(list);
        if (list.length > 0) {
          setSelectedChild(list[0]);
        }
      })
      .catch(err => console.error('Failed to load children:', err));
  }, []);

  // Whenever the selected child changes, fetch their enrolled subjects.
  useEffect(() => {
    setLoadingSubjects(true);
    setSubjects([]);
    setSelectedSubject(null);
    api.get('/subjects')
      .then(res => setSubjects(Array.isArray(res.data) ? res.data : []))
      .catch(err => console.error('Failed to load subjects:', err))
      .finally(() => setLoadingSubjects(false));
  }, [selectedChild?.id]);

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

  return (
    <div className="p-4 sm:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <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})`
              : selectedChild
                ? `Browse resources for ${selectedChild.first_name}`
                : `Browse ${terms.subjects} for your children`}
          </p>
        </div>

        <div className="flex items-center gap-3 flex-wrap">
          {/* Child picker */}
          {children.length > 0 && (
            <div className="relative">
              <button
                type="button"
                onClick={() => setShowChildPicker(s => !s)}
                className="flex items-center gap-2 px-4 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm"
              >
                <div className="w-7 h-7 rounded-lg bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center text-primary text-xs font-black border border-blue-100 dark:border-blue-800">
                  {selectedChild?.first_name?.[0]}{selectedChild?.last_name?.[0]}
                </div>
                <span className="hidden sm:inline">{selectedChild ? `${selectedChild.first_name} ${selectedChild.last_name}` : `Select child`}</span>
                <ChevronDown size={14} className={`text-text-muted/30 transition-transform ${showChildPicker ? 'rotate-180' : ''}`} />
              </button>
              {showChildPicker && (
                <div className="absolute right-0 top-full mt-2 w-64 bg-card border border-border rounded-2xl shadow-2xl z-50 p-2">
                  <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted px-4 py-2">Switch child</p>
                  {children.map(c => (
                    <button
                      key={c.id}
                      type="button"
                      onClick={() => {
                        setSelectedChild(c);
                        setShowChildPicker(false);
                      }}
                      className={`w-full flex items-center gap-3 p-3 rounded-xl text-left transition-all ${selectedChild?.id === c.id ? 'bg-primary/5' : 'hover:bg-muted/50'}`}
                    >
                      <div className="w-9 h-9 rounded-xl bg-muted border border-border flex items-center justify-center text-primary text-xs font-black shadow-sm">
                        {c.first_name[0]}{c.last_name[0]}
                      </div>
                      <div className="min-w-0">
                        <p className="text-sm font-bold text-text truncate">{c.first_name} {c.last_name}</p>
                        <p className="text-[0.6rem] text-text-muted font-bold uppercase">{c.grade || c.class_name}</p>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </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>
      </div>

      {!selectedChild ? (
        <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">No children linked yet</p>
        </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 ${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>

          {loadingSubjects ? (
            <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
                  ? `${selectedChild.first_name} has no enrolled ${terms.subjects.toLowerCase()}`
                  : `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 the 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.toLowerCase()}.`}
                captionPrefix={activeSubTab}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}