import { useState, useEffect } from 'react';
import api, { useAuthStore } from '../../store/auth';
import { 
  Plus, BookOpen, Users, FileText, Eye, 
  FolderOpen, TrendingUp, Clock, ChevronRight,
  Search, X, Download, Filter, Sparkles,
  BookMarked, GraduationCap, CheckCircle2,
  Calendar, MoreHorizontal
} from 'lucide-react';

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 { user } = useAuthStore();
  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 [newCourseForm, setNewCourseForm] = useState({
    name: '',
    class_id: '',
    schedule: '',
  });
  const [classes, setClasses] = useState<any[]>([]);

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

  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(mockCourses);
    } finally {
      setLoading(false);
    }
  };

  const loadClasses = async () => {
    try {
      const res = await api.get('/classes');
      setClasses(res.data);
    } catch (error) {
      setClasses([
        { id: 1, name: 'Grade 10-B' },
        { id: 2, name: 'Grade 11-A' },
        { id: 3, name: 'Advanced Placement' },
      ]);
    }
  };

  const handleNewCourse = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/subjects', newCourseForm);
      setShowNewCourseModal(false);
      setNewCourseForm({ name: '', class_id: '', schedule: '' });
      loadCourses();
    } catch (error) {
      alert('Failed to establish course records.');
    }
  };

  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 Courses', value: courses.length, icon: BookMarked, color: 'blue', trend: 'Academic' },
    { label: 'Assigned Learners', value: totalStudents, icon: Users, color: 'emerald', trend: 'Verified' },
    { label: 'Learning Velocity', value: `${avgProgress}%`, icon: TrendingUp, color: 'orange', trend: 'Optimal' },
    { 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 Subjects</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button 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} />
            Initialize Course
          </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 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={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>

        <button className="px-5 py-3 bg-muted/50 hover:bg-muted text-text-muted rounded-2xl border border-border transition-all flex items-center justify-center gap-2">
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest text-text-muted">Semester View</span>
        </button>
      </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">Accessing Curriculum Intelligence...</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 Courses Identified</h3>
          <p className="text-text-muted font-medium mb-8 max-w-sm mx-auto">No subjects 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 Course
          </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} 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-110 transition-transform`}>
                      <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}-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>

                  {/* Academic Pulse 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}`}>Academic Pulse: {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 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} />
                      Course Room
                      <ChevronRight size={14} className="group-hover/btn:translate-x-1 transition-transform" />
                    </button>
                    <button 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">
                      <MoreHorizontal size={24} />
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* New Course Modal */}
      {showNewCourseModal && (
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Sparkles size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight font-heading">Initialize Course</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Establish new academic record</p>
              </div>
              <button onClick={() => setShowNewCourseModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all">
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleNewCourse} className="p-10 space-y-6">
              <div className="space-y-2">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">Subject Name</label>
                <input
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all"
                  value={newCourseForm.name}
                  onChange={(e) => setNewCourseForm({ ...newCourseForm, name: e.target.value })}
                  placeholder="e.g., Theoretical Physics II"
                  required
                />
              </div>

              <div className="space-y-2">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">Class Section</label>
                <select
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:border-primary transition-all appearance-none cursor-pointer"
                  value={newCourseForm.class_id}
                  onChange={(e) => setNewCourseForm({ ...newCourseForm, class_id: e.target.value })}
                  required
                >
                  <option value="">Select an academic section...</option>
                  {classes.map((cls) => (
                    <option key={cls.id} value={cls.id}>
                      {cls.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="space-y-2">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">Lecture Schedule</label>
                <div className="relative">
                  <Calendar size={18} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50" />
                  <input
                    className="w-full bg-muted/50 border border-border rounded-2xl pl-12 pr-4 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all"
                    value={newCourseForm.schedule}
                    onChange={(e) => setNewCourseForm({ ...newCourseForm, schedule: e.target.value })}
                    placeholder="e.g., Mon, Wed, Fri - 10:00 AM"
                  />
                </div>
              </div>

              <button 
                type="submit" 
                className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl shadow-blue-900/20 active:scale-95 flex items-center justify-center gap-3"
              >
                <Sparkles size={18} />
                Generate Course Records
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

// Mock data for demo purposes
const mockCourses: Course[] = [
  {
    id: 1,
    name: 'Advanced Mathematics',
    class_name: 'Grade 11-A',
    instructor_name: 'Dr. John Smith',
    student_count: 32,
    assignment_count: 14,
    completed_assignments: 10,
    material_count: 28,
    progress: 82,
    schedule: 'Mon, Wed, Fri',
    color: 'blue'
  },
  {
    id: 2,
    name: 'Quantum Physics',
    class_name: 'Grade 12-C',
    instructor_name: 'Dr. Michael Chen',
    student_count: 28,
    assignment_count: 10,
    completed_assignments: 4,
    material_count: 18,
    progress: 45,
    schedule: 'Tue, Thu',
    color: 'purple'
  },
  {
    id: 3,
    name: 'English Literature II',
    class_name: 'Grade 10-B',
    instructor_name: 'Prof. Elena Rodriguez',
    student_count: 35,
    assignment_count: 8,
    completed_assignments: 7,
    material_count: 22,
    progress: 94,
    schedule: 'Mon, Thu',
    color: 'emerald'
  }
];