import React, { useEffect, useState } from 'react';
import { 
  Plus, FileText, Target, BookOpen, 
  ChevronRight, ClipboardList,
  X, Download,
  Sparkles, CheckCircle2,
  TrendingUp, BookText, Search,
  Calendar, Trash2, ClipboardSignature
} from 'lucide-react';
import { useTeacherStore } from '../../store/teacher';
import api from '../../store/auth';
import { useEducationTerms } from '../../utils/educationTerms';
import { Modal, ModalBody } from '../../components/ui/Modal';
import { ProgressBar } from '../../components/ui/ProgressBar';
import { createAxiosUploadProgressHandler } from '../../lib/uploadProgress';

export function TeacherTools() {
  const terms = useEducationTerms();
  const {
    syllabuses, schemes, focusPoints, lessonPlans,
    fetchSyllabuses, fetchSchemes, fetchFocusPoints, fetchLessonPlans,
    createSyllabus, createScheme, createFocusPoint, createLessonPlan
  } = useTeacherStore();

  const [activeTab, setActiveTab] = useState('syllabus');
  const [showModal, setShowModal] = useState(false);
  const [formData, setFormData] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  const [syllabusFile, setSyllabusFile] = useState<File | null>(null);
  const [syllabusAttachments, setSyllabusAttachments] = useState<any[]>([]);
  const [syllabusUploadPercent, setSyllabusUploadPercent] = useState<number>(0);

  const loadSyllabusAttachments = async (subjList: any[]) => {
    try {
      const allAtts: any[] = [];
      for (const subj of subjList) {
        const res = await api.get('/attachments', {
          params: { parent_kind: 'subject', parent_id: subj.id }
        });
        const rows = Array.isArray(res.data) ? res.data : [];
        const sylls = rows.filter(r => r.caption && r.caption.startsWith('syllabus'));
        sylls.forEach(s => {
          let title = s.original_filename;
          let version = '1.0.0';
          if (s.caption.includes(':')) {
            const parts = s.caption.split(':');
            if (parts[1]) version = parts[1].replace('v', '');
            if (parts[2]) title = parts[2];
          }
          allAtts.push({
            id: s.id,
            uid: s.uid,
            title,
            version,
            subject_name: subj.name,
            file_path: null,
            stored_filename: s.stored_filename,
            original_filename: s.original_filename
          });
        });
      }
      setSyllabusAttachments(allAtts);
    } catch (e) {
      console.error(e);
    }
  };

  const handleDownloadSyllabus = async (title: string, record: any) => {
    const fileToGet = record.file_path || record.stored_filename;
    if (!fileToGet) {
      alert('No attachment uploaded for this syllabus');
      return;
    }
    try {
      const res = await api.get(`uploads/${fileToGet}`, { responseType: 'blob' });
      const blob = new Blob([res.data]);
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      const filename = record.original_filename || record.file_path || `${title}-syllabus`;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (err: any) {
      alert(`Failed to download syllabus: ${err?.message || 'Network error'}`);
    }
  };
  
  // Custom states for pedagogical tools
  const [subjects, setSubjects] = useState<any[]>([]);
  const [weeklyPlanner, setWeeklyPlanner] = useState<{ week: number; topic: string; objectives: string }[]>([
    { week: 1, topic: '', objectives: '' }
  ]);
  const [expandedSchemeId, setExpandedSchemeId] = useState<number | null>(null);
  const [expandedLessonId, setExpandedLessonId] = useState<number | null>(null);

  useEffect(() => {
    setLoading(true);
    Promise.all([
      fetchSyllabuses(),
      fetchSchemes(),
      fetchFocusPoints(),
      fetchLessonPlans(),
      api.get('/subjects').then(res => {
        setSubjects(res.data);
        loadSyllabusAttachments(res.data);
      }).catch(() => {})
    ]).finally(() => setLoading(false));
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (activeTab === 'syllabus') {
        if (!syllabusFile) {
          alert('Syllabus document file is required');
          return;
        }
        setLoading(true);
        setSyllabusUploadPercent(0);
        const cap = `syllabus:v${formData.version || '1.0.0'}:${formData.title}`;
        const fd = new FormData();
        fd.append('parent_kind', 'subject');
        fd.append('parent_id', String(formData.subject_id));
        fd.append('caption', cap);
        fd.append('files', syllabusFile);

        const onSyllabusUploadProgress = createAxiosUploadProgressHandler((percent) => {
          if (percent == null) return;
          setSyllabusUploadPercent(percent);
        });

        await api.post('/attachments', fd, {
          headers: { 'Content-Type': 'multipart/form-data' },
          onUploadProgress: onSyllabusUploadProgress,
        });

        setSyllabusUploadPercent(0);
        alert('Syllabus uploaded successfully');
        setShowModal(false);
        setFormData({});
        setSyllabusFile(null);
        api.get('/subjects').then(res => {
          setSubjects(res.data);
          loadSyllabusAttachments(res.data);
        }).catch(() => {});
        return;
      }
      if (activeTab === 'scheme') {
        const contentStr = JSON.stringify(weeklyPlanner);
        await createScheme({
          subject_id: Number(formData.subject_id),
          term: formData.term,
          academic_year: formData.academic_year,
          content: contentStr
        });
      }
      if (activeTab === 'focus') {
        await createFocusPoint({
          scheme_id: Number(formData.scheme_id),
          topic: formData.topic,
          objectives: formData.objectives,
          key_concepts: formData.key_concepts,
          resources_needed: formData.resources_needed
        });
      }
      if (activeTab === 'lesson') {
        await createLessonPlan({
          subject_id: Number(formData.subject_id),
          scheme_id: formData.scheme_id ? Number(formData.scheme_id) : null,
          focus_point_id: formData.focus_point_id ? Number(formData.focus_point_id) : null,
          date: formData.date,
          topic: formData.topic,
          objectives: formData.objectives,
          introduction: formData.introduction,
          development: formData.development,
          conclusion: formData.conclusion,
          assessment_method: formData.assessment_method,
          homework: formData.homework,
          reflections: formData.reflections,
          meet_url: formData.meet_url || null,
          classroom_url: formData.classroom_url || null
        });
      }
      setShowModal(false);
      setFormData({});
      setWeeklyPlanner([{ week: 1, topic: '', objectives: '' }]);
    } catch (err) {
      setSyllabusUploadPercent(0);
      alert('Error saving intellectual record');
    }
  };

  const handleOpenModal = () => {
    setFormData({});
    setSyllabusUploadPercent(0);
    setWeeklyPlanner([{ week: 1, topic: '', objectives: '' }]);
    setShowModal(true);
  };

  const stats = [
    { label: 'Syllabuses', value: syllabuses.length, icon: FileText, color: 'blue' },
    { label: 'Schemes', value: schemes.length, icon: BookOpen, color: 'emerald' },
    { label: 'Focus Points', value: focusPoints.length || 0, icon: Target, color: 'orange' },
    { label: 'Lesson Units', value: lessonPlans.length, icon: ClipboardList, color: 'purple' },
  ];

  const tabs = [
    { id: 'syllabus', label: 'Syllabus', icon: FileText },
    { id: 'scheme', label: 'Schemes', icon: BookOpen },
    { id: 'focus', label: 'Focus', icon: Target },
    { id: 'lesson', label: 'Lessons', icon: ClipboardList }
  ];

  const filteredSyllabuses = [
    ...syllabuses,
    ...syllabusAttachments
  ].filter(s => 
    s.title?.toLowerCase().includes(searchTerm.toLowerCase()) || 
    s.subject_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const filteredSchemes = schemes.filter(s => 
    s.subject_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    s.academic_year?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const filteredFocusPoints = focusPoints.filter(fp => 
    fp.topic?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    fp.subject_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const filteredLessonPlans = lessonPlans.filter(lp => 
    lp.topic?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    lp.subject_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6 sm:space-y-8 animate-in fade-in duration-700 pb-24 sm:pb-10 px-0 sm:px-0">
      {/* Premium Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 px-4 sm:px-0">
        <div className="w-full md:w-auto">
          <h2 className="text-2xl sm:text-3xl font-black text-text tracking-tight">Pedagogical Framework</h2>
          <nav className="flex text-[0.6rem] sm:text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span className="truncate">Faculty Workspace</span>
            <ChevronRight size={10} className="shrink-0" />
            <span className="text-primary truncate">Teacher Tools</span>
          </nav>
        </div>
        <div className="flex w-full md:w-auto gap-2 sm:gap-3">
          <button
            type="button"
            onClick={() => {
              const records = activeTab === 'syllabus' ? filteredSyllabuses
                : activeTab === 'scheme' ? filteredSchemes
                : activeTab === 'focus' ? filteredFocusPoints
                : filteredLessonPlans;
              const headers = ['UID', 'Title/Topic', 'Subject', 'Details'];
              const rows = (records as any[]).map((r: any) => [
                r.uid || '',
                `"${(r.title || r.topic || '').replace(/"/g, '""')}"`,
                r.subject_name || '',
                r.version ? `v${r.version}` : r.term ? `Term ${r.term}` : '',
              ]);
              const csv = [headers.join(','), ...rows.map((row) => row.join(','))].join('\n');
              const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
              const url = URL.createObjectURL(blob);
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', `teacher-tools-${activeTab}-${new Date().toISOString().slice(0, 10)}.csv`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              URL.revokeObjectURL(url);
            }}
            className="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2.5 sm:px-5 sm:py-3 bg-card border border-border text-text rounded-xl font-bold text-xs sm:text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
          >
            <Download size={16} className="sm:w-[18px] sm:h-[18px]" />
            <span className="hidden xs:inline">Export</span>
          </button>
          <button 
            className="flex-[2] md:flex-none flex items-center justify-center gap-2 px-4 py-2.5 sm:px-6 sm:py-3 bg-primary text-white rounded-xl font-bold text-xs sm:text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={handleOpenModal}
          >
            <Plus size={16} className="sm:w-[18px] sm:h-[18px]" />
            Add {tabs.find(t => t.id === activeTab)?.label}
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 px-4 sm:px-0">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-3 sm:p-5 rounded-2xl flex flex-col sm:flex-row items-start sm:items-center gap-2 sm:gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-10 h-10 sm:w-12 sm:h-12 rounded-xl sm:rounded-2xl flex items-center justify-center shrink-0
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800' : 
                stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800' : 
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800'} 
              group-hover:scale-110 transition-transform border`}>
              <stat.icon size={18} className="sm:w-[22px] sm:h-[22px]" />
            </div>
            <div className="min-w-0">
              <p className="text-[0.55rem] sm:text-[0.65rem] font-black uppercase tracking-wider text-text-muted truncate">{stat.label}</p>
              <div className="flex items-baseline gap-1 sm:gap-2">
                <p className="text-lg sm:text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.5rem] sm:text-[0.6rem] font-bold text-text-muted">Records</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Tool Navigation */}
      <div className="px-4 sm:px-0 sticky top-16 lg:static z-[80]">
        <div className="bg-card/80 backdrop-blur-md border border-border rounded-2xl sm:rounded-[2rem] p-1.5 sm:p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-3">
          <div className="flex p-1 bg-muted rounded-xl sm:rounded-2xl flex-1 overflow-x-auto no-scrollbar">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex-1 min-w-[80px] sm:min-w-0 px-3 sm:px-6 py-2 sm:py-3 rounded-lg sm:rounded-xl text-[0.6rem] sm:text-[0.7rem] font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2
                  ${activeTab === tab.id 
                    ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                    : 'text-text-muted hover:text-text'}
                `}
              >
                <tab.icon size={14} className="sm:w-4 sm:h-4" />
                <span className={activeTab === tab.id ? 'inline' : 'hidden xs:inline'}>{tab.label}</span>
              </button>
            ))}
          </div>

          <div className="flex gap-2">
            <div className="relative flex-1 lg:w-64">
              <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
              <input 
                type="text"
                placeholder="Search records..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 sm:py-3 bg-muted border border-transparent focus:border-primary focus:bg-card text-text rounded-xl text-xs sm:text-sm transition-all outline-none"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Content Area */}
      <div className="px-4 sm:px-0">
        <div className="bg-card border border-border rounded-2xl sm:rounded-[2.5rem] shadow-sm overflow-hidden min-h-[400px]">
          {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-[0.65rem] font-black uppercase tracking-widest text-text-muted">Accessing Pedagogical Vault...</p>
            </div>
          ) : (
            <div className="p-2 md:p-4">
              {/* Syllabuses Tab */}
              {activeTab === 'syllabus' && (
                <div className="flex flex-col">
                  {/* Desktop Table View */}
                  <div className="hidden md:block">
                    <table className="w-full text-left">
                      <thead>
                        <tr className="bg-muted border-b border-border">
                          <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Curriculum Title</th>
                          <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Core {terms.subject}</th>
                          <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Revision</th>
                          <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-border/50">
                        {filteredSyllabuses.length === 0 ? (
                          <tr>
                            <td colSpan={4} className="py-20 text-center">
                              <FileText size={48} className="mx-auto text-text-muted/30 mb-4" />
                              <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">No records found</p>
                            </td>
                          </tr>
                        ) : filteredSyllabuses.map((s) => (
                          <tr key={s.uid} className="hover:bg-muted/30 transition-colors group cursor-default">
                            <td className="px-8 py-5">
                              <div className="flex items-center gap-4">
                                <div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 flex items-center justify-center border border-blue-100 dark:border-blue-800 group-hover:scale-110 transition-transform">
                                  <BookText size={18} />
                                </div>
                                <div>
                                  <p className="text-[0.9rem] font-bold text-text leading-tight">{s.title}</p>
                                  <p className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">Ref: {s.uid.split('-')[0]}</p>
                                </div>
                              </div>
                            </td>
                            <td className="px-8 py-5">
                              <span className="px-3 py-1.5 rounded-lg bg-muted text-text-muted border border-border text-[0.6rem] font-black uppercase tracking-widest">
                                {s.subject_name}
                              </span>
                            </td>
                            <td className="px-8 py-5 text-center font-mono text-xs font-bold text-text-muted">v{s.version}</td>
                            <td className="px-8 py-5 text-right">
                              <button
                                type="button"
                                onClick={() => handleDownloadSyllabus(s.title, s)}
                                disabled={!s.file_path && !s.stored_filename}
                                className="inline-flex items-center gap-2 px-4 py-2 bg-primary/10 hover:bg-primary text-primary hover:text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-primary/10 disabled:hover:text-primary"
                              >
                                <Download size={14} /> Download
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* Mobile Card View */}
                  <div className="md:hidden divide-y divide-border/50">
                    {filteredSyllabuses.length === 0 ? (
                      <div className="py-20 text-center">
                        <FileText size={48} className="mx-auto text-text-muted/30 mb-4" />
                        <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">No records found</p>
                      </div>
                    ) : filteredSyllabuses.map((s) => (
                      <div key={s.uid} className="p-4 space-y-4">
                        <div className="flex items-start justify-between gap-4">
                          <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 flex items-center justify-center border border-blue-100 dark:border-blue-800 shrink-0">
                              <BookText size={18} />
                            </div>
                            <div className="min-w-0">
                              <p className="text-sm font-bold text-text leading-tight break-words">{s.title}</p>
                              <p className="text-[0.55rem] text-text-muted font-black tracking-tighter uppercase">v{s.version} • Ref: {s.uid.split('-')[0]}</p>
                            </div>
                          </div>
                          <span className="px-2 py-1 rounded-md bg-muted text-text-muted text-[0.55rem] font-black uppercase tracking-widest border border-border shrink-0">
                            {s.subject_name}
                          </span>
                        </div>
                        <button
                          type="button"
                          onClick={() => handleDownloadSyllabus(s.title, s)}
                          disabled={!s.file_path && !s.stored_filename}
                          className="w-full flex items-center justify-center gap-2 py-3 bg-primary/10 text-primary rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all active:scale-[0.98] disabled:opacity-40 disabled:cursor-not-allowed disabled:active:scale-100"
                        >
                          <Download size={14} /> Download Curriculum
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Schemes of Work Tab */}
              {activeTab === 'scheme' && (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 p-2 md:p-4">
                  {filteredSchemes.length === 0 ? (
                    <div className="col-span-full py-20 text-center opacity-30">
                      <BookOpen size={64} className="mx-auto mb-4" />
                      <p className="text-lg sm:text-xl font-black uppercase tracking-widest">No schemes yet</p>
                    </div>
                  ) : filteredSchemes.map((s) => {
                    const isExpanded = expandedSchemeId === s.id;
                    let weeklyPlannerData = [];
                    try {
                      weeklyPlannerData = JSON.parse(s.content || '[]');
                    } catch (e) {}

                    return (
                      <div key={s.uid} className="bg-card border border-border rounded-2xl sm:rounded-[2rem] p-5 sm:p-6 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative flex flex-col justify-between">
                        <div>
                          <div className="relative z-10 flex justify-between items-start mb-4">
                            <div className="w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border border-emerald-100 dark:border-emerald-800 flex items-center justify-center group-hover:scale-110 transition-transform shrink-0">
                              <TrendingUp size={22} />
                            </div>
                            <span className="px-2.5 py-1 bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400 text-[0.55rem] sm:text-[0.6rem] font-black rounded-lg uppercase tracking-widest border border-emerald-200 dark:border-emerald-800 shrink-0">
                              Term {s.term}
                            </span>
                          </div>

                          <div className="relative z-10 mb-4">
                            <h3 className="text-lg font-black text-text tracking-tighter group-hover:text-primary transition-colors leading-tight">{s.subject_name}</h3>
                            <p className="text-[0.6rem] sm:text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mt-1">Cycle: {s.academic_year}</p>
                            <span className="mt-2 inline-flex items-center px-2 py-0.5 bg-muted text-text-muted border border-border rounded-md text-[0.55rem] font-black uppercase tracking-wider">
                              {s.status || 'draft'}
                            </span>
                          </div>
                        </div>

                        {/* Collapsible weekly structure */}
                        <div className="relative z-10 mt-auto pt-4 border-t border-border">
                          <button
                            type="button"
                            onClick={() => setExpandedSchemeId(isExpanded ? null : s.id)}
                            className="w-full flex items-center justify-between text-[0.65rem] font-black text-primary uppercase tracking-widest hover:text-primary-dark transition-colors"
                          >
                            <span>{isExpanded ? 'Hide Schedule' : `View Weekly strategy (${weeklyPlannerData.length} Wks)`}</span>
                            <ChevronRight size={14} className={`transform transition-transform ${isExpanded ? 'rotate-90' : ''}`} />
                          </button>

                          {isExpanded && (
                            <div className="mt-3 space-y-2.5 max-h-60 overflow-y-auto pr-1 custom-scrollbar animate-in slide-in-from-top-2 duration-300">
                              {weeklyPlannerData.length === 0 ? (
                                <p className="text-xs text-text-muted italic py-4 text-center">No weekly strategy defined.</p>
                              ) : (
                                weeklyPlannerData.map((w: any, idx: number) => (
                                  <div key={idx} className="p-3 bg-muted/60 border border-border rounded-xl text-left">
                                    <p className="text-[0.65rem] font-black text-primary uppercase tracking-wider">Week {w.week || idx + 1}</p>
                                    <p className="text-xs font-bold text-text mt-0.5">{w.topic}</p>
                                    {w.objectives && (
                                      <p className="text-[0.65rem] text-text-muted mt-1 italic font-medium">"{w.objectives}"</p>
                                    )}
                                  </div>
                                ))
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Focus Points Tab */}
              {activeTab === 'focus' && (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 p-2 md:p-4">
                  {filteredFocusPoints.length === 0 ? (
                    <div className="col-span-full py-20 text-center opacity-30">
                      <Target size={64} className="mx-auto mb-4" />
                      <p className="text-lg sm:text-xl font-black uppercase tracking-widest">No Focus Points defined</p>
                    </div>
                  ) : filteredFocusPoints.map((fp) => (
                    <div key={fp.uid} className="bg-card border border-border rounded-2xl sm:rounded-[2rem] p-5 sm:p-6 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative flex flex-col justify-between text-left">
                      <div>
                        <div className="flex justify-between items-start mb-4">
                          <div className="w-10 h-10 rounded-xl bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border border-orange-100 dark:border-orange-800 flex items-center justify-center shrink-0">
                            <Target size={20} />
                          </div>
                          <span className="px-2 py-1 bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400 text-[0.55rem] font-black rounded-lg uppercase tracking-widest border border-orange-200 dark:border-orange-800">
                            {fp.subject_name || terms.subject}
                          </span>
                        </div>
                        
                        <h3 className="text-base sm:text-lg font-black text-text tracking-tighter mb-3 leading-tight">{fp.topic}</h3>
                        
                        <div className="space-y-3 mt-4 text-xs">
                          <div>
                            <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">Objectives</p>
                            <p className="text-text mt-0.5 leading-relaxed font-semibold">{fp.objectives}</p>
                          </div>
                          {fp.key_concepts && (
                            <div>
                              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">Key Concepts</p>
                              <p className="text-text mt-0.5 leading-relaxed font-medium text-text-muted">{fp.key_concepts}</p>
                            </div>
                          )}
                          {fp.resources_needed && (
                            <div>
                              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">Resources Required</p>
                              <p className="text-text mt-0.5 leading-relaxed font-medium text-text-muted">{fp.resources_needed}</p>
                            </div>
                          )}
                        </div>
                      </div>
                      
                      <div className="pt-4 border-t border-border mt-5 text-[0.55rem] font-black text-text-muted uppercase tracking-[1px] flex justify-between">
                        <span>Scheme Reference</span>
                        <span>Term {fp.scheme_term || 'N/A'} ({fp.scheme_academic_year || 'N/A'})</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Lesson Plans Tab */}
              {activeTab === 'lesson' && (
                <div className="p-2 md:p-4 space-y-4 text-left">
                  {filteredLessonPlans.length === 0 ? (
                    <div className="py-20 text-center opacity-30">
                      <ClipboardList size={64} className="mx-auto mb-4" />
                      <p className="text-lg sm:text-xl font-black uppercase tracking-widest">No Lesson Plans Created</p>
                    </div>
                  ) : filteredLessonPlans.map((lp) => {
                    const isExpanded = expandedLessonId === lp.id;
                    return (
                      <div key={lp.uid} className="bg-card border border-border rounded-2xl sm:rounded-[2rem] p-5 sm:p-6 hover:shadow-md transition-all">
                        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                          <div className="flex items-start gap-4">
                            <div className="w-10 h-10 rounded-xl bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border border-purple-100 dark:border-purple-800 flex items-center justify-center shrink-0">
                              <ClipboardList size={20} />
                            </div>
                            <div>
                              <h3 className="text-base sm:text-lg font-black text-text tracking-tighter leading-tight">{lp.topic}</h3>
                              <div className="flex flex-wrap items-center gap-2 text-[0.6rem] font-black uppercase tracking-wider text-text-muted mt-1.5">
                                <span className="px-2 py-0.5 bg-muted text-text rounded-md border border-border">{lp.subject_name}</span>
                                <span>•</span>
                                <span className="flex items-center gap-1"><Calendar size={10} /> {new Date(lp.date).toLocaleDateString()}</span>
                                {lp.scheme_term && (
                                  <>
                                    <span>•</span>
                                    <span>Term {lp.scheme_term}</span>
                                  </>
                                )}
                                {lp.focus_point_topic && (
                                  <>
                                    <span>•</span>
                                    <span className="truncate max-w-[150px]">Focus: {lp.focus_point_topic}</span>
                                  </>
                                )}
                              </div>
                            </div>
                          </div>
                          
                          <div className="flex items-center gap-2 w-full md:w-auto justify-between md:justify-end shrink-0">
                            <span className="px-2.5 py-1 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 text-[0.55rem] font-black rounded-lg uppercase tracking-widest border border-purple-200 dark:border-purple-800 shrink-0">
                              {lp.status || 'Pending'}
                            </span>
                            <button
                              type="button"
                              onClick={() => setExpandedLessonId(isExpanded ? null : lp.id)}
                              className="px-4 py-2 bg-muted hover:bg-muted/80 text-text rounded-xl text-[0.65rem] font-black uppercase tracking-widest border border-border transition-all flex items-center gap-1.5 active:scale-95"
                            >
                              {isExpanded ? 'Hide Lesson' : 'Explore Lesson'}
                            </button>
                          </div>
                        </div>
                        
                        {isExpanded && (
                          <div className="mt-6 pt-6 border-t border-border space-y-6 animate-in slide-in-from-top-2 duration-300">
                            <div>
                              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted mb-1.5">Specific Objectives</p>
                              <p className="text-sm font-semibold leading-relaxed text-text">{lp.objectives}</p>
                            </div>
                            
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                              <div className="p-4 bg-muted/40 rounded-2xl border border-border flex flex-col justify-between">
                                <div>
                                  <p className="text-[0.6rem] font-black uppercase tracking-[1px] text-primary mb-1.5">1. Hook & Intro (10m)</p>
                                  <p className="text-xs leading-relaxed font-semibold text-text-muted whitespace-pre-wrap">{lp.introduction || 'No introduction steps details.'}</p>
                                </div>
                              </div>
                              <div className="p-4 bg-muted/40 rounded-2xl border border-border flex flex-col justify-between">
                                <div>
                                  <p className="text-[0.6rem] font-black uppercase tracking-[1px] text-primary mb-1.5">2. Development (30m)</p>
                                  <p className="text-xs leading-relaxed font-semibold text-text-muted whitespace-pre-wrap">{lp.development || 'No conceptual development details.'}</p>
                                </div>
                              </div>
                              <div className="p-4 bg-muted/40 rounded-2xl border border-border flex flex-col justify-between">
                                <div>
                                  <p className="text-[0.6rem] font-black uppercase tracking-[1px] text-primary mb-1.5">3. Wrap-up & Recap (10m)</p>
                                  <p className="text-xs leading-relaxed font-semibold text-text-muted whitespace-pre-wrap">{lp.conclusion || 'No conclusion/exit activities details.'}</p>
                                </div>
                              </div>
                            </div>
                            
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 pt-4 border-t border-border/50">
                              <div>
                                <p className="text-[0.6rem] font-black uppercase tracking-wider text-text-muted mb-1">Assessment Methodology</p>
                                <p className="text-xs font-bold text-text mt-0.5">{lp.assessment_method || 'Unspecified assessment'}</p>
                              </div>
                              <div>
                                <p className="text-[0.6rem] font-black uppercase tracking-wider text-text-muted mb-1">Assigned Homework</p>
                                <p className="text-xs font-bold text-text mt-0.5">{lp.homework || 'No homework assigned'}</p>
                              </div>
                              <div>
                                <p className="text-[0.6rem] font-black uppercase tracking-wider text-text-muted mb-1">Teacher Reflections</p>
                                <p className="text-xs font-bold italic text-text-muted mt-0.5">{lp.reflections || 'Post-reflection pending.'}</p>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Dynamic Creation Modal */}
      {showModal && (
        <Modal
          open={true}
          onClose={() => setShowModal(false)}
          title={`Add ${tabs.find(t => t.id === activeTab)?.label}`}
          icon={Sparkles}
          subtitle="Fill out the details below"
          maxWidth="max-w-2xl"
          zIndex={200}
        >
          <ModalBody className="p-0 max-h-[95vh] flex flex-col">
            <form id="teacher-tools-create-form" onSubmit={handleSubmit} className="p-4 sm:p-8 md:p-10 space-y-4 sm:space-y-6 overflow-y-auto custom-scrollbar text-left">
              {/* Syllabus Form */}
              {activeTab === 'syllabus' && (
                <>
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Curriculum Title</label>
                    <input 
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                      value={formData.title || ''}
                      onChange={e => setFormData({...formData, title: e.target.value})} 
                      placeholder="e.g., Advanced Mathematics - Grade 12" 
                      required 
                    />
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject} Registry</label>
                      <select 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.subject_id || ''} 
                        onChange={e => setFormData({...formData, subject_id: e.target.value})} 
                        required
                      >
                        <option value="">Select {terms.subject}</option>
                        {subjects.map(s => (
                          <option key={s.id} value={s.id}>{s.name} ({s.class_name || 'No Class'})</option>
                        ))}
                      </select>
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Version Intel</label>
                      <input 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm font-mono focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.version || ''}
                        onChange={e => setFormData({...formData, version: e.target.value})} 
                        placeholder="1.0.0" 
                        required
                      />
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Curriculum Description</label>
                    <textarea 
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                      value={formData.description || ''}
                      onChange={e => setFormData({...formData, description: e.target.value})} 
                      placeholder="Summary of scope, topics, objectives..." 
                      rows={3} 
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Syllabus File (PDF/Document)</label>
                    <input
                      type="file"
                      accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.png,.jpg,.jpeg,.zip,.txt"
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text text-left"
                      onChange={e => setSyllabusFile(e.target.files?.[0] || null)}
                      disabled={loading}
                      required
                    />
                    {loading && activeTab === 'syllabus' && (
                      <div className="pt-2" aria-busy={loading}>
                        <ProgressBar
                          value={syllabusUploadPercent}
                          size="sm"
                          showValue
                          aria-label="Syllabus upload progress"
                        />
                      </div>
                    )}
                  </div>
                </>
              )}

              {/* Scheme Form */}
              {activeTab === 'scheme' && (
                <>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject}</label>
                      <select 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.subject_id || ''} 
                        onChange={e => setFormData({...formData, subject_id: e.target.value})} 
                        required
                      >
                        <option value="">Select {terms.subject}</option>
                        {subjects.map(s => (
                          <option key={s.id} value={s.id}>{s.name} ({s.class_name || 'No Class'})</option>
                        ))}
                      </select>
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                      <div className="space-y-1.5">
                        <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Term</label>
                        <select 
                          className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                          value={formData.term || ''} 
                          onChange={e => setFormData({...formData, term: e.target.value})} 
                          required
                        >
                          <option value="">Select Term</option>
                          <option value="1">Term 1</option>
                          <option value="2">Term 2</option>
                          <option value="3">Term 3</option>
                        </select>
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Year</label>
                        <select 
                          className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                          value={formData.academic_year || ''} 
                          onChange={e => setFormData({...formData, academic_year: e.target.value})} 
                          required
                        >
                          <option value="">Select Year</option>
                          <option value="2026">2026</option>
                          <option value="2027">2027</option>
                          <option value="2028">2028</option>
                        </select>
                      </div>
                    </div>
                  </div>
                  
                  <div className="space-y-3 pt-4 border-t border-border">
                    <div className="flex justify-between items-center">
                      <h4 className="text-xs font-black uppercase tracking-wider text-text">Weekly Strategy Planner</h4>
                      <button 
                        type="button" 
                        onClick={() => setWeeklyPlanner([...weeklyPlanner, { week: weeklyPlanner.length + 1, topic: '', objectives: '' }])}
                        className="flex items-center gap-1.5 px-3 py-1.5 bg-primary/10 hover:bg-primary text-primary hover:text-white rounded-lg text-[0.6rem] font-black uppercase tracking-wider transition-all"
                      >
                        <Plus size={12} /> Add Week
                      </button>
                    </div>
                    
                    <div className="space-y-4 max-h-60 overflow-y-auto pr-2 custom-scrollbar">
                      {weeklyPlanner.map((wp, index) => (
                        <div key={index} className="p-4 bg-muted/60 border border-border rounded-2xl space-y-3 relative group">
                          <div className="flex justify-between items-center">
                            <span className="text-[0.6rem] font-black uppercase tracking-wider text-primary font-black">Week {index + 1}</span>
                            {weeklyPlanner.length > 1 && (
                              <button 
                                type="button" 
                                onClick={() => setWeeklyPlanner(weeklyPlanner.filter((_, idx) => idx !== index))}
                                className="text-rose-500 hover:text-rose-600 transition-colors text-xs font-bold"
                              >
                                Remove
                              </button>
                            )}
                          </div>
                          <div className="space-y-2">
                            <input 
                              type="text" 
                              placeholder="Topic for this week" 
                              value={wp.topic}
                              onChange={e => {
                                const newPlanner = [...weeklyPlanner];
                                newPlanner[index].topic = e.target.value;
                                setWeeklyPlanner(newPlanner);
                              }}
                              className="w-full px-3 py-2 bg-card border border-border rounded-lg text-xs focus:ring-1 focus:ring-primary/20 outline-none transition-all text-text" 
                              required 
                            />
                            <textarea 
                              placeholder="Objectives / Concepts to cover" 
                              value={wp.objectives}
                              onChange={e => {
                                const newPlanner = [...weeklyPlanner];
                                newPlanner[index].objectives = e.target.value;
                                setWeeklyPlanner(newPlanner);
                              }}
                              className="w-full px-3 py-2 bg-card border border-border rounded-lg text-xs focus:ring-1 focus:ring-primary/20 outline-none transition-all text-text" 
                              rows={2}
                              required
                            />
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </>
              )}

              {/* Focus Point Form */}
              {activeTab === 'focus' && (
                <>
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Scheme of Work Reference</label>
                    <select 
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                      value={formData.scheme_id || ''} 
                      onChange={e => setFormData({...formData, scheme_id: e.target.value})} 
                      required
                    >
                      <option value="">Select Scheme</option>
                      {schemes.map(s => (
                        <option key={s.id} value={s.id}>{s.subject_name} - Term {s.term} ({s.academic_year})</option>
                      ))}
                    </select>
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Focus Topic</label>
                    <input 
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                      value={formData.topic || ''} 
                      onChange={e => setFormData({...formData, topic: e.target.value})} 
                      placeholder="e.g., Matrix Determinants and Inverses" 
                      required 
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Focus Objectives</label>
                    <textarea 
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                      value={formData.objectives || ''} 
                      onChange={e => setFormData({...formData, objectives: e.target.value})} 
                      placeholder="Learners should be able to calculate determinants of 3x3 matrices..." 
                      rows={3} 
                      required
                    />
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Key Concepts</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.key_concepts || ''} 
                        onChange={e => setFormData({...formData, key_concepts: e.target.value})} 
                        placeholder="Determinant, Cramer's Rule, Inverse Matrix" 
                        rows={3} 
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Resources Needed</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.resources_needed || ''} 
                        onChange={e => setFormData({...formData, resources_needed: e.target.value})} 
                        placeholder="Scientific Calculators, Graph Papers, Handouts" 
                        rows={3} 
                      />
                    </div>
                  </div>
                </>
              )}

              {/* Lesson Plan Form */}
              {activeTab === 'lesson' && (
                <>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject}</label>
                      <select 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.subject_id || ''} 
                        onChange={e => {
                          const val = e.target.value;
                          setFormData({...formData, subject_id: val, scheme_id: '', focus_point_id: ''});
                        }} 
                        required
                      >
                        <option value="">Select {terms.subject}</option>
                        {subjects.map(s => (
                          <option key={s.id} value={s.id}>{s.name} ({s.class_name || 'No Class'})</option>
                        ))}
                      </select>
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Scheme Reference</label>
                      <select 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.scheme_id || ''} 
                        disabled={!formData.subject_id}
                        onChange={e => {
                          const val = e.target.value;
                          setFormData({...formData, scheme_id: val, focus_point_id: ''});
                        }} 
                      >
                        <option value="">Select Scheme (Optional)</option>
                        {schemes
                          .filter(s => Number(s.subject_id) === Number(formData.subject_id))
                          .map(s => (
                            <option key={s.id} value={s.id}>Term {s.term} ({s.academic_year})</option>
                          ))
                        }
                      </select>
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Focus Point</label>
                      <select 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.focus_point_id || ''} 
                        disabled={!formData.scheme_id}
                        onChange={e => setFormData({...formData, focus_point_id: e.target.value})} 
                      >
                        <option value="">Select Focus Point (Optional)</option>
                        {focusPoints
                          .filter(fp => Number(fp.scheme_id) === Number(formData.scheme_id))
                          .map(fp => (
                            <option key={fp.id} value={fp.id}>{fp.topic}</option>
                          ))
                        }
                      </select>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Date</label>
                      <input 
                        type="date" 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.date || ''} 
                        onChange={e => setFormData({...formData, date: e.target.value})} 
                        required 
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Lesson Topic</label>
                      <input 
                        type="text" 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.topic || ''} 
                        onChange={e => setFormData({...formData, topic: e.target.value})} 
                        placeholder="e.g., Matrix Multiplication Mechanics" 
                        required 
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-1.5">
                    <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Specific Lesson Objectives</label>
                    <textarea 
                      className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                      value={formData.objectives || ''} 
                      onChange={e => setFormData({...formData, objectives: e.target.value})} 
                      placeholder="By the end of the lesson, pupils should be able to multiply two 2x2 matrices..." 
                      rows={2} 
                      required 
                    />
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Introduction (10m)</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.introduction || ''} 
                        onChange={e => setFormData({...formData, introduction: e.target.value})} 
                        placeholder="HOOK: Real-world network routing example..." 
                        rows={3} 
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Development (30m)</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.development || ''} 
                        onChange={e => setFormData({...formData, development: e.target.value})} 
                        placeholder="Present dot product formula and solve 3 examples on board..." 
                        rows={3} 
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Conclusion (10m)</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.conclusion || ''} 
                        onChange={e => setFormData({...formData, conclusion: e.target.value})} 
                        placeholder="Recap multiplication compatibility rules. Exit ticket problem..." 
                        rows={3} 
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Assessment Method</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.assessment_method || ''} 
                        onChange={e => setFormData({...formData, assessment_method: e.target.value})} 
                        placeholder="Exit ticket quiz, classroom group work observation" 
                        rows={2} 
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Homework Assignment</label>
                      <textarea 
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                        value={formData.homework || ''} 
                        onChange={e => setFormData({...formData, homework: e.target.value})} 
                        placeholder="Exercise 12B, numbers 1 to 5 in Textbook." 
                        rows={2} 
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Reflections / Notes</label>
                      <textarea
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text"
                        value={formData.reflections || ''}
                        onChange={e => setFormData({...formData, reflections: e.target.value})}
                        placeholder="To be filled after the lesson concludes..."
                        rows={2}
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                        Google Meet link (optional)
                      </label>
                      <input
                        type="url"
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-1 focus:ring-primary/20 outline-none transition-all text-text"
                        value={formData.meet_url || ''}
                        onChange={e => setFormData({...formData, meet_url: e.target.value})}
                        placeholder="https://meet.google.com/abc-defg-hij"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                        Google Classroom link (optional)
                      </label>
                      <input
                        type="url"
                        className="w-full px-4 py-3 bg-muted border border-border rounded-xl text-xs focus:ring-1 focus:ring-primary/20 outline-none transition-all text-text"
                        value={formData.classroom_url || ''}
                        onChange={e => setFormData({...formData, classroom_url: e.target.value})}
                        placeholder="https://classroom.google.com/c/NDAwMDAxMjM"
                      />
                    </div>
                  </div>
                </>
              )}

              <button type="submit" className="w-full py-4 sm:py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-[0.65rem] sm:text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 mt-4">
                <CheckCircle2 size={18} />
                Finalize Record
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
      `}</style>
    </div>
  );
}
