import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../../store/auth';
import {
  BookOpen, User, Trophy, Clock, CheckCircle2, Play,
  ChevronRight, Search, X, Download, Filter, Sparkles,
  BookMarked, GraduationCap, BarChart3, Calendar,
  MoreHorizontal, Eye
} from 'lucide-react';
import { useEducationTerms } from '../../utils/educationTerms';

interface Course {
  id: number;
  subject_name: string;
  class_name: string;
  instructor_name: string;
  grade_percentage: number;
  progress: number;
  lessons_completed: number;
  total_lessons: number;
  last_accessed: string;
  is_completed: boolean;
  color?: string;
}

export default function MyCourses() {
  const navigate = useNavigate();
  const terms = useEducationTerms();
  const { user } = useAuthStore();
  const [courses, setCourses] = useState<Course[]>([]);
  const [filteredCourses, setFilteredCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'all' | 'in_progress' | 'completed'>('all');
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    loadCourses();
  }, [user?.id]);

  useEffect(() => {
    const filtered = courses.filter(c => {
      const matchesSearch = c.subject_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          c.instructor_name.toLowerCase().includes(searchQuery.toLowerCase());

      if (activeTab === 'in_progress') return matchesSearch && !c.is_completed;
      if (activeTab === 'completed') return matchesSearch && c.is_completed;
      return matchesSearch;
    });
    setFilteredCourses(filtered);
  }, [searchQuery, activeTab, courses]);

  const loadCourses = async () => {
    try {
      setLoading(true);
      const res = await api.get(`/students/${user?.id}/courses`);
      const courseData = res.data.map((c: any, idx: number) => ({
        ...c,
        color: ['blue', 'emerald', 'orange', 'purple', 'rose', 'indigo'][idx % 6]
      }));
      setCourses(courseData);
    } catch (error) {
      setCourses([]);
    } finally {
      setLoading(false);
    }
  };

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

  // CSV export of academic record
  const handleExportRecord = () => {
    const rows: (string | number)[][] = [
      ['Course', 'Class', 'Instructor', 'Grade %', 'Progress %', 'Lessons Completed', 'Total Lessons', 'Last Accessed', 'Status'],
      ...courses.map(c => [
        c.subject_name, c.class_name, c.instructor_name,
        c.grade_percentage, c.progress,
        c.lessons_completed, c.total_lessons,
        c.last_accessed, c.is_completed ? 'Completed' : 'In Progress',
      ]),
    ];
    const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `academic-record-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const formatLastAccessed = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - date.getTime());
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return 'Today';
    if (diffDays === 1) return 'Yesterday';
    if (diffDays < 7) return `${diffDays} days ago`;
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  };

  const stats = [
    { label: `Active ${terms.subjects}`, value: courses.filter(c => !c.is_completed).length, icon: BookMarked, color: 'blue', trend: 'This term' },
    { label: 'Completions', value: courses.filter(c => c.is_completed).length, icon: CheckCircle2, color: 'emerald', trend: 'Confirmed' },
    { label: 'Average Mark', value: `${courses.length ? Math.round(courses.reduce((sum, c) => sum + c.grade_percentage, 0) / courses.length) : 0}%`, icon: Trophy, color: 'orange', trend: `Across ${terms.subjects.toLowerCase()}` },
    { label: 'Last Activity', value: formatLastAccessed(courses[0]?.last_accessed || new Date().toISOString()), icon: Clock, color: 'purple', trend: 'History' },
  ];

  if (loading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Loading {terms.subjects.toLowerCase()}...</p>
    </div>
  );

  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">My Curriculum</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Student Portal</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Learning Journey</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button onClick={handleExportRecord} 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} />
            Academic Record
          </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">
        {/* Status Tabs */}
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-grow lg:flex-grow-0 min-w-0">
          {(['all', 'in_progress', 'completed'] as const).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`
                flex-1 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all
                ${activeTab === tab
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border'
                  : 'text-text-muted hover:text-text'}
              `}
            >
              {tab.replace('_', ' ')}
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <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.5 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 ${terms.subjects.toLowerCase()} or instructors...`}
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
        </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">Current Semester</span>
        </button>
      </div>

      {/* Course Grid */}
      {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 uppercase tracking-tighter">Queue Clear</h3>
          <p className="text-text-muted font-medium max-w-xs mx-auto">No {activeTab.replace('_', ' ')} {terms.subjects.toLowerCase()} identified in your curriculum registry.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {filteredCourses.map((course) => {
            const styles = getProgressStyles(course.progress);
            return (
              <div key={course.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden flex flex-col sm:flex-row gap-8">
                {/* Visual Identity */}
                <div className="flex flex-col items-center sm:items-start gap-4">
                  <div className={`w-24 h-24 rounded-3xl bg-${course.color}-50/10 dark:bg-${course.color}-900/20 border border-${course.color}-100/20 dark:border-${course.color}-800/30 flex items-center justify-center text-${course.color}-600 dark:text-${course.color}-400 shadow-inner shrink-0 group-hover:scale-105 transition-transform`}>
                    <BookOpen size={40} />
                  </div>
                  {course.is_completed && (
                    <span className="px-3 py-1 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-full border border-emerald-100 dark:border-emerald-800 text-[0.6rem] font-black uppercase tracking-widest flex items-center gap-1">
                      <CheckCircle2 size={12} />
                      Completed
                    </span>
                  )}
                </div>

                {/* Content & Progress */}
                <div className="flex-1 min-w-0 space-y-6">
                    <div className="space-y-1">
                        <div className="flex justify-between items-start">
                            <h3 className="text-2xl font-black text-text tracking-tight truncate">{course.subject_name}</h3>
                            <div className="bg-muted/50 dark:bg-muted/20 border border-border py-1 px-3 rounded-lg text-[0.6rem] font-black uppercase tracking-widest text-primary dark:text-blue-400">
                                {course.class_name}
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <User size={14} className="text-text-muted/50" />
                            <p className="text-[0.8rem] font-bold text-text-muted">Instructor: <span className="text-text-secondary">{course.instructor_name}</span></p>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="bg-muted/50 dark:bg-muted/20 rounded-2xl p-4 border border-border">
                            <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1">Current Mark</p>
                            <div className="flex items-center gap-2">
                                <p className={`text-xl font-black ${course.grade_percentage >= 80 ? 'text-emerald-600 dark:text-emerald-400' : 'text-primary dark:text-blue-400'}`}>{course.grade_percentage}%</p>
                                <span className={`text-[0.6rem] font-black px-2 py-0.5 rounded-lg border ${course.grade_percentage >= 80 ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800'}`}>
                                    {course.grade_percentage >= 90 ? 'A+' : course.grade_percentage >= 80 ? 'A' : 'B'}
                                </span>
                            </div>
                        </div>
                        <div className="bg-muted/50 dark:bg-muted/20 rounded-2xl p-4 border border-border">
                            <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1">Lessons Done</p>
                            <p className="text-xl font-black text-text">{course.lessons_completed}<span className="text-text-muted/50 text-sm ml-1 font-bold">/{course.total_lessons}</span></p>
                        </div>
                    </div>

                    <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 Progress</p>
                                <h4 className={`text-sm font-black ${styles.text}`}>{terms.subject} Progress: {course.progress}%</h4>
                            </div>
                            <span className="text-[0.6rem] font-bold text-text-muted/50 uppercase tracking-widest">Last Activity: {formatLastAccessed(course.last_accessed)}</span>
                        </div>
                        <div className="w-full h-1.5 bg-muted dark:bg-muted/20 rounded-full overflow-hidden p-0.5 shadow-inner border border-border dark:border-blue-800/30">
                            <div
                                className={`h-full rounded-full transition-all duration-1000 ${styles.bar}`}
                                style={{ width: `${course.progress}%` }}
                            />
                        </div>
                    </div>

                    <div className="pt-2">
                        <button
                            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 flex items-center justify-center gap-3 group/btn"
                        >
                            {course.is_completed ? <Eye size={18} /> : <Play size={18} className="group-hover/btn:translate-x-1 transition-transform" />}
                            {course.is_completed ? `Review ${terms.subject}` : `Continue ${terms.subject}`}
                        </button>
                    </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
