import React, { useEffect, useState } from 'react';
import {
  BookOpen, FileText, Upload, Trash2, ChevronLeft,
  Download, Eye, Search, AlertCircle, BookMarked,
  Sparkles, FileSpreadsheet, FileArchive, HelpCircle
} from 'lucide-react';
import { useAuthStore } from '../../store/auth';
import api from '../../store/api';
import { AttachmentList } from '../../components/AttachmentList';
import { AttachmentUploader } from '../../components/AttachmentUploader';
import type { Attachment } from '../../store/attachments';
import { useAttachmentStore } from '../../store/attachments';
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: FileArchive },
};

export default function Resources() {
  const user = useAuthStore(s => s.user);
  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<'syllabus' | 'test_paper' | 'homework_sheet' | 'past_exam'>('syllabus');
  const [uploaderKey, setUploaderKey] = useState(0);

  const loadSubjects = async () => {
    setLoading(true);
    try {
      const endpoint = user?.role === 'teacher' ? '/teacher/subjects' : '/subjects';
      const res = await api.get(endpoint);
      setSubjects(Array.isArray(res.data) ? res.data : []);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSubjects();
  }, []);

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

  const handleBack = () => {
    setSelectedSubject(null);
  };

  // Re-fetch attachments after a upload success
  const handleUploaded = () => {
    setUploaderKey(prev => prev + 1);
  };

  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">Pedagogical Resources</h1>
          </div>
          <p className="text-xs text-text-muted mt-1 uppercase font-bold tracking-widest">
            {selectedSubject ? `${selectedSubject.name} (${selectedSubject.code})` : `Browse ${terms.subjects} to manage resources`}
          </p>
        </div>
        {selectedSubject && (
          <button
            onClick={handleBack}
            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 ? (
        // Grid of Subjects
        <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>

          {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 {terms.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">No {terms.subjects.toLowerCase()} found</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>
      ) : (
        // Subject Resource Manager Tabs
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Side Tabs Selection */}
          <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 no-scrollbar">
            {([
              { id: 'syllabus', label: 'Curriculum & Syllabus' },
              { id: 'test_paper', label: 'Test Papers' },
              { id: 'homework_sheet', label: 'Homework Sheets' },
              { id: 'past_exam', label: 'Past Exam Papers' },
            ] as const).map(tab => {
              const isSelected = activeSubTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveSubTab(tab.id)}
                  className={`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'
                  }`}
                >
                  {tab.label}
                </button>
              );
            })}
          </div>

          {/* Files List & Uploaders */}
          <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>
  );
}