import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../../store/auth';
import {
  Plus, BookOpen, Users, FileText, Eye,
  FolderOpen, TrendingUp, Clock, ChevronRight,
  Search, X, Download, Sparkles,
  BookMarked, GraduationCap, CheckCircle2,
  Calendar, MoreHorizontal
} from 'lucide-react';
import { useEducationTerms } from '../../utils/educationTerms';
import { useSchoolSettingsStore } from '../../store/schoolSettings';
import { getRoomTerm } from '../../utils/eduLevel';
import { Modal, ModalBody } from '../../components/ui/Modal';

interface Course {
  id: number;
  name: string;
  class_name: string;
  instructor_name: string;
  student_count: number;
  assignment_count: number;
  completed_assignments: number;
  material_count: number;
  progress: number;
  schedule: string;
  color?: string;
}

export default function MyCourses() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const educationLevel = useSchoolSettingsStore((s) => s.educationLevel);
  const fetchSettings = useSchoolSettingsStore((s) => s.fetchSettings);
  const [courses, setCourses] = useState<Course[]>([]);
  const [filteredCourses, setFilteredCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);
  const [showNewCourseModal, setShowNewCourseModal] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [activePopover, setActivePopover] = useState<number | null>(null);
  const [newCourseForm, setNewCourseForm] = useState({
    name: '',
    code: '',
    class_id: '',
    schedule: '',
    credits: 0,
    description: '',
  });
  const [classes, setClasses] = useState<any[]>([]);

  useEffect(() => {
    fetchSettings();
    loadCourses();
    loadClasses();
  }, [fetchSettings]);

  useEffect(() => {
    const filtered = courses.filter(c =>
      c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.class_name.toLowerCase().includes(searchQuery.toLowerCase())
    );
    setFilteredCourses(filtered);
  }, [searchQuery, courses]);

  const loadCourses = async () => {
    try {
      setLoading(true);
      const res = await api.get('/subjects');
      const courseData: Course[] = res.data.map((subject: any, idx: number) => ({
        id: subject.id,
        name: subject.name,
        class_name: subject.class_name || 'General Section',
        instructor_name: `${user?.first_name || ''} ${user?.last_name || ''}`.trim() || 'Faculty Head',
        student_count: subject.student_count || 24,
        assignment_count: subject.assignment_count || 12,
        completed_assignments: subject.completed_assignments || 8,
        material_count: subject.material_count || 15,
        progress: subject.progress || 75,
        schedule: subject.schedule || 'Mon, Wed, Fri',
        color: ['blue', 'emerald', 'orange', 'purple', 'rose', 'indigo'][idx % 6]
      }));
      setCourses(courseData);
    } catch (error) {
      setCourses([]);
    } finally {
      setLoading(false);
    }
  };

  const loadClasses = async () => {
    try {
      const res = await api.get('/classes');
      setClasses(res.data);
    } catch (error) {
      setClasses([]);
    }
  };

  const handleNewCourse = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/subjects', {
        ...newCourseForm,
        // Auto-derive a code from the name when the teacher didn't set one
        code: newCourseForm.code || newCourseForm.name.toUpperCase().replace(/[^A-Z0-9]+/g, '').slice(0, 8),
      });
      setShowNewCourseModal(false);
      setNewCourseForm({ name: '', class_id: '', schedule: '', code: '', credits: 0, description: '' });
      loadCourses();
    } catch (error: any) {
      const msg = error?.response?.data?.error || error?.message || 'Unknown error';
      alert(`Failed to create ${terms.subject.toLowerCase()}: ${msg}`);
    }
  };

  const getProgressStyles = (progress: number) => {
    if (progress >= 80) return { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-500', bar: 'bg-emerald-500', border: 'border-emerald-100 dark:border-emerald-800/30' };
    if (progress >= 50) return { text: 'text-primary dark:text-blue-400', bg: 'bg-primary', bar: 'bg-primary', border: 'border-blue-100/20 dark:border-blue-800/30' };
    return { text: 'text-rose-600 dark:text-rose-400', bg: 'bg-rose-500', bar: 'bg-rose-500', border: 'border-rose-100 dark:border-rose-800/30' };
  };

  const totalStudents = courses.reduce((sum, c) => sum + c.student_count, 0);
  const avgProgress = courses.length > 0
    ? Math.round(courses.reduce((sum, c) => sum + c.progress, 0) / courses.length)
    : 0;

  const stats = [
    { label: `Active ${terms.subjects}`, value: courses.length, icon: BookMarked, color: 'blue', trend: 'Academic' },
    { label: 'Assigned Learners', value: totalStudents, icon: Users, color: 'emerald', trend: 'Verified' },
    { label: 'Average Progress', value: `${avgProgress}%`, icon: TrendingUp, color: 'orange', trend: 'Across classes' },
    { label: 'Material Assets', value: courses.reduce((sum, c) => sum + c.material_count, 0), icon: FileText, color: 'purple', trend: 'Stored' },
  ];

  return (
    <>
      <div className="space-y-10 animate-in fade-in duration-700 pb-10">
        {/* Premium Header */}
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
          <div>
            <h2 className="text-3xl font-black text-text tracking-tight text-capitalize text-slate-900 dark:text-white">Curriculum Portfolio</h2>
            <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
              <span>Faculty Portal</span>
              <ChevronRight size={12} className="text-text-muted/30" />
              <span className="text-primary">Assigned {terms.subjects}</span>
            </nav>
          </div>
          <div className="flex gap-3">
            <button
              type="button"
              onClick={() => {
                const headers = ['ID', 'Subject', 'Class', 'Instructor', 'Learners', 'Tasks', 'Materials', 'Progress'];
                const rows = filteredCourses.map((c) => [
                  c.id,
                  `"${(c.name || '').replace(/"/g, '""')}"`,
                  `"${(c.class_name || '').replace(/"/g, '""')}"`,
                  `"${(c.instructor_name || '').replace(/"/g, '""')}"`,
                  c.student_count || 0,
                  c.assignment_count || 0,
                  c.material_count || 0,
                  c.progress || 0,
                ]);
                const csv = [headers.join(','), ...rows.map((r) => r.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', `my-${terms.subject.toLowerCase()}s-${new Date().toISOString().slice(0, 10)}.csv`);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
              }}
              className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
            >
              <Download size={18} />
              Syllabus Export
            </button>
            <button
              className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
              onClick={() => setShowNewCourseModal(true)}
            >
              <Plus size={18} />
              New {terms.subject}
            </button>
          </div>
        </div>

        {/* Stats Bento Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {stats.map((stat) => (
            <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
              <div className={`w-12 h-12 rounded-2xl flex items-center justify-center
                ${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 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={22} />
              </div>
              <div>
                <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
                <div className="flex items-baseline gap-2">
                  <p className="text-2xl font-black text-text">{stat.value}</p>
                  <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Directory Control Bar */}
        <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
          <div className="relative group flex-1">
            <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
            <input
              type="text"
              className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all"
              placeholder="Search by subject name or class section..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
            />
            {searchQuery && (
              <button onClick={() => setSearchQuery('')} className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500">
                <X size={16} />
              </button>
            )}
          </div>
        </div>

        {/* Course Grid */}
        {loading ? (
          <div className="py-20 text-center">
            <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-text-muted font-bold uppercase tracking-widest text-xs">Loading classes...</p>
          </div>
        ) : filteredCourses.length === 0 ? (
          <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
            <BookOpen size={64} className="mx-auto text-text-muted/30 mb-6" />
            <h3 className="text-2xl font-black text-text mb-2">No {terms.subjects} Identified</h3>
            <p className="text-text-muted font-medium mb-8 max-w-sm mx-auto">No {terms.subject.toLowerCase()}s match your current criteria. Establish new courses to begin curriculum tracking.</p>
            <button
              className="bg-primary text-white px-8 py-3.5 rounded-2xl font-bold transition-all shadow-lg shadow-blue-900/10 hover:bg-primary/90"
              onClick={() => setShowNewCourseModal(true)}
            >
              Create New {terms.subject}
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {filteredCourses.map((course) => {
              const styles = getProgressStyles(course.progress);
              const colorClass = course.color || 'blue';

              return (
                <div key={course.id} data-testid="course" className="bg-card rounded-[2.5rem] border border-border overflow-hidden hover:shadow-xl hover:shadow-blue-900/5 transition-all group flex flex-col">
                  {/* Visual Header */}
                  <div className="p-8 pb-6 relative overflow-hidden flex-shrink-0">
                    <div className={`absolute top-0 right-0 w-48 h-48 bg-${colorClass}-500 opacity-[0.03] dark:opacity-[0.08] rounded-bl-full -mr-16 -mt-16 group-hover:opacity-[0.06] dark:group-hover:opacity-[0.15] transition-opacity`}></div>
                    <div className="relative z-10 flex justify-between items-start mb-6">
                      <div className={`w-14 h-14 rounded-2xl bg-muted border border-border flex items-center justify-center text-${colorClass}-600 dark:text-${colorClass}-400 shadow-sm group-hover:scale`}>
                        <BookOpen size={28} />
                      </div>
                      <div className="bg-muted/50 dark:bg-muted/20 border border-border py-2 px-4 rounded-xl text-[0.65rem] font-black uppercase tracking-[2px] text-primary dark:text-blue-400">
                        {course.class_name}
                      </div>
                    </div>
                    <div className="relative z-10 space-y-1">
                      <h3 className="text-2xl font-black text-text tracking-tight line-clamp-1 group-hover:text-primary transition-colors">{course.name}</h3>
                      <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Section Portfolio 2024</p>
                    </div>
                  </div>

                  {/* Course Stats */}
                  <div className="px-8 flex-grow">
                    <div className="grid grid-cols-3 gap-3 mb-8">
                      {[
                        { val: course.assignment_count, label: 'Tasks', icon: FileText, c: 'blue' },
                        { val: course.material_count, label: 'Assets', icon: FolderOpen, c: 'purple' },
                        { val: course.student_count, label: 'Learners', icon: Users, c: 'emerald' },
                      ].map(s => (
                        <div key={s.label} className="bg-muted/50 dark:bg-muted/20 rounded-2xl p-3 border border-border hover:bg-card transition-colors text-center group/stat">
                          <div className={`text-${s.c}-600 dark:text-${s.c}-${s.c}-400 mb-1 flex justify-center`}><s.icon size={14} strokeWidth={2.5} /></div>
                          <p className="text-sm font-black text-text leading-none mb-1">{s.val}</p>
                          <p className="text-[0.55rem] font-black uppercase tracking-widest text-text-muted">{s.label}</p>
                        </div>
                      ))}
                    </div>

                    {/* Course Progress */}
                    <div className="space-y-4">
                      <div className="flex justify-between items-end">
                        <div>
                          <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted mb-0.5">Syllabus Completion</p>
                          <h4 className={`text-sm font-black ${styles.text}`}>Syllabus Progress: {course.progress}%</h4>
                        </div>
                        <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-tighter border ${styles.border} ${styles.text}`}>
                          {course.progress >= 80 ? 'Optimal' : 'Active'}
                        </span>
                      </div>
                      <div className="w-full h-1.5 bg-muted rounded-full overflow-hidden shadow-inner p-0.5">
                        <div
                          className={`h-full rounded-full transition-all duration-1000 ${styles.bar}`}
                          style={{ width: `${course.progress}%` }}
                        />
                      </div>
                    </div>
                  </div>

                  {/* Footer Actions */}
                  <div className="p-8 pt-6 mt-auto border-t border-border/50 bg-muted/20">
                    <div className="flex gap-3">
                      <button
                        type="button"
                        onClick={() => navigate('/classes')}
                        className="flex-1 flex items-center justify-center gap-2 bg-primary hover:bg-primary/90 text-white py-4 rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg shadow-blue-900/10 active:scale-95 group/btn"
                      >
                        <Eye size={18} />
                        {getRoomTerm(educationLevel)}
                        <ChevronRight size={14} className="group-hover/btn:translate-x-1 transition-transform" />
                      </button>
                    <div className="relative">
                      <button
                        type="button"
                        onClick={() => setActivePopover(activePopover === course.id ? null : course.id)}
                        className="w-14 h-14 flex items-center justify-center bg-muted dark:bg-muted/50 hover:bg-muted/80 text-text-muted hover:text-primary rounded-2xl border border-border transition-all"
                        title="More actions"
                      >
                        <MoreHorizontal size={24} />
                      </button>
                      {activePopover === course.id && (
                        <div className="absolute right-0 bottom-full mb-2 w-48 bg-card border border-border rounded-xl shadow-xl z-50 p-1 py-1.5 animate-in fade-in slide-in-from-bottom-2 duration-150">
                          <button
                            type="button"
                            onClick={() => {
                              setActivePopover(null);
                              navigate('/students', { state: { class_name: course.class_name } });
                            }}
                            className="w-full text-left px-4 py-2 hover:bg-muted text-sm font-bold text-text rounded-lg transition-colors flex items-center gap-2"
                          >
                            <Users size={16} className="text-text-muted" />
                            View Roster
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              setActivePopover(null);
                              navigate('/teacher-tools', { state: { activeTab: 'syllabus', editCourseId: course.id } });
                            }}
                            className="w-full text-left px-4 py-2 hover:bg-muted text-sm font-bold text-text rounded-lg transition-colors flex items-center gap-2"
                          >
                            <FileText size={16} className="text-text-muted" />
                            Edit Syllabus
                          </button>
                          <button
                            type="button"
                            onClick={async () => {
                              setActivePopover(null);
                              if (window.confirm(`Are you sure you want to archive "${course.name}"?`)) {
                                try {
                                  await api.delete(`/courses/${course.id}`);
                                  loadCourses();
                                } catch (err: any) {
                                  alert(`Failed to archive course: ${err?.response?.data?.error || err.message}`);
                                }
                              }
                            }}
                            className="w-full text-left px-4 py-2 hover:bg-rose-50 dark:hover:bg-rose-950/30 text-sm font-bold text-rose-600 rounded-lg transition-colors flex items-center gap-2"
                          >
                            <X size={16} className="text-rose-600" />
                            Archive Course
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* New Course Modal — premium design (per modals.md §1).
          - Portaled to document.body so the backdrop always covers the
            full viewport, regardless of any ancestor that establishes a
            containing block (transform/filter/will-change/contain).
          - Header block: bg-muted/50 border-b + watermark Sparkles +
            standardized close button, matching Classes.tsx's premium. */}
      {showNewCourseModal && (
        <Modal
          open={true}
          onClose={() => setShowNewCourseModal(false)}
          title={`New ${terms.subject}`}
          icon={Sparkles}
          subtitle="Establish new academic record for your teaching portfolio"
          maxWidth="max-w-xl"
          zIndex={150}
        >
          <ModalBody className="p-0 max-h-[90vh] flex flex-col">
            <form id="mycourses-create-form" onSubmit={handleNewCourse} className="p-4 sm:p-8 md:p-10 space-y-4 sm:space-y-6 overflow-y-auto custom-scrollbar">
              <div className="space-y-2">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">{terms.subject} Name</label>
                <input
                  type="text"
                  className="w-full bg-muted/50 border border-border rounded-2xl pl-4 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                  placeholder="e.g., Theoretical Physics II"
                  value={newCourseForm.name}
                  onChange={e => setNewCourseForm({ ...newCourseForm, name: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">{terms.subject} Code</label>
                <input
                  type="text"
                  className="w-full bg-muted/50 border border-border rounded-2xl pl-4 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                  placeholder="e.g., PHYS202"
                  value={newCourseForm.code}
                  onChange={e => setNewCourseForm({ ...newCourseForm, code: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Class Section</label>
                <select
                  className="w-full bg-muted/50 border border-border rounded-2xl pl-4 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                  value={newCourseForm.class_id}
                  onChange={e => setNewCourseForm({ ...newCourseForm, class_id: e.target.value })}
                >
                  <option value="">Select Section</option>
                  {classes.map(cls => (
                    <option key={cls.id} value={cls.id}>
                      {cls.name} {cls.section ? `- ${cls.section}` : ''}
                    </option>
                  ))}
                </select>
              </div>
              <div className="space-y-2">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Lecture Schedule</label>
                <input
                  type="text"
                  className="w-full bg-muted/50 border border-border rounded-2xl pl-4 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                  placeholder="e.g., Mon, Wed, Fri 10:00-11:30"
                  value={newCourseForm.schedule}
                  onChange={e => setNewCourseForm({ ...newCourseForm, schedule: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Credits</label>
                <input
                  type="number"
                  className="w-full bg-muted/50 border border-border rounded-2xl pl-4 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                  min="0"
                  max="12"
                  value={newCourseForm.credits}
                  onChange={e => setNewCourseForm({ ...newCourseForm, credits: Number(e.target.value) || 0 })}
                />
              </div>
              <div className="space-y-2">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Description</label>
                <textarea
                  className="w-full bg-muted/50 border border-border rounded-2xl pl-4 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                  placeholder="Brief overview of the subject scope and objectives"
                  value={newCourseForm.description}
                  onChange={e => setNewCourseForm({ ...newCourseForm, description: e.target.value })}
                />
              </div>
              <div className="pt-2">
                <button
                  type="submit"
                  className="w-full py-4 bg-primary hover:bg-primary-dark text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg active:scale-95 cursor-pointer"
                >
                  Create {terms.subject}
                </button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}
    </>
  );
}