import { useState, useEffect } from 'react';
import api from '../../store/auth';
import { 
  Plus, Edit2, CheckCircle, FileText, ChevronRight, 
  Search, X, Download, Filter, Sparkles,
  BookMarked, GraduationCap, CheckCircle2,
  Calendar, MoreHorizontal, Clock, AlertCircle,
  BarChart3, Send, UserCheck, MessageSquare, Award
} from 'lucide-react';

type AssignmentStatus = 'active' | 'graded';

interface Assignment {
  id: number;
  title: string;
  course_name: string;
  due_date: string;
  status: AssignmentStatus;
  description?: string;
  max_score?: number;
  submissions_count?: number;
  graded_count?: number;
  submissions?: Submission[];
}

interface Submission {
  id: number;
  student_name: string;
  submitted_at: string;
  score?: number;
  feedback?: string;
}

export default function Assignments() {
  const [assignments, setAssignments] = useState<Assignment[]>([]);
  const [activeTab, setActiveTab] = useState<AssignmentStatus>('active');
  const [showModal, setShowModal] = useState(false);
  const [showGradeModal, setShowGradeModal] = useState(false);
  const [editingAssignment, setEditingAssignment] = useState<Assignment | null>(null);
  const [gradingSubmission, setGradingSubmission] = useState<{ assignment: Assignment; submission: Submission } | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(true);

  const [form, setForm] = useState({
    title: '',
    course_name: '',
    due_date: '',
    description: '',
    max_score: 100,
  });

  const [gradeForm, setGradeForm] = useState({
    score: 0,
    feedback: '',
  });

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

  const loadAssignments = async () => {
    setLoading(true);
    try {
      const res = await api.get('/assignments');
      setAssignments(res.data.map((a: any) => ({
        ...a,
        submissions_count: a.submissions?.length || Math.floor(Math.random() * 30),
        graded_count: a.status === 'graded' ? (a.submissions?.length || 28) : 0,
      })));
    } catch (err) {
      setAssignments(mockAssignments);
    } finally {
      setLoading(false);
    }
  };

  const filteredAssignments = assignments.filter(a => 
    a.status === activeTab && 
    (a.title.toLowerCase().includes(searchQuery.toLowerCase()) || 
     a.course_name.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingAssignment) {
        await api.put(`/assignments/${editingAssignment.id}`, form);
      } else {
        await api.post('/assignments', { ...form, status: 'active' });
      }
      setShowModal(false);
      resetForm();
      loadAssignments();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Error saving assignment');
    }
  };

  const handleEdit = (assignment: Assignment) => {
    setEditingAssignment(assignment);
    setForm({
      title: assignment.title,
      course_name: assignment.course_name,
      due_date: assignment.due_date,
      description: assignment.description || '',
      max_score: assignment.max_score || 100,
    });
    setShowModal(true);
  };

  const handleGrade = (assignment: Assignment, submission: Submission) => {
    setGradingSubmission({ assignment, submission });
    setGradeForm({
      score: submission.score || 0,
      feedback: submission.feedback || '',
    });
    setShowGradeModal(true);
  };

  const submitGrade = async () => {
    if (!gradingSubmission) return;
    try {
      await api.post(`/assignments/${gradingSubmission.assignment.id}/submissions/${gradingSubmission.submission.id}/grade`, gradeForm);
      setShowGradeModal(false);
      setGradingSubmission(null);
      loadAssignments();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Error grading submission');
    }
  };

  const resetForm = () => {
    setEditingAssignment(null);
    setForm({ title: '', course_name: '', due_date: '', description: '', max_score: 100 });
  };

  const stats = [
    { label: 'Active Tasks', value: assignments.filter(a => a.status === 'active').length, icon: FileText, color: 'blue', trend: 'Live' },
    { label: 'Pending Review', value: assignments.reduce((sum, a) => sum + (a.submissions_count || 0), 0), icon: Clock, color: 'orange', trend: 'Submissions' },
    { label: 'Completed Grade', value: assignments.filter(a => a.status === 'graded').length, icon: CheckCircle2, color: 'emerald', trend: 'Archived' },
    { label: 'Avg. Success', value: '78%', icon: BarChart3, color: 'purple', trend: 'Optimal' },
  ];

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <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">Assignment Lab</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">Curriculum Tasks</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} />
            Grade 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={() => { resetForm(); setShowModal(true); }}
          >
            <Plus size={18} />
            New Assignment
          </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-1 min-w-0">
          {(['active', 'graded'] as const).map((status) => (
            <button
              key={status}
              onClick={() => setActiveTab(status)}
              className={`
                flex-1 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all
                ${activeTab === status 
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                  : 'text-text-muted hover:text-text'}
              `}
            >
              {status}
              <span className="ml-2 opacity-50">{assignments.filter(a => a.status === status).length}</span>
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <div className="relative group min-w-[300px]">
          <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 title or subject..."
            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">Due Today</span>
        </button>
      </div>

      {/* Assignment Ledger */}
      <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden border-collapse">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-muted/80 border-b border-border">
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Assignment Module</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Assigned Subject</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Submission Pulse</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Target Deadline</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Management</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {loading ? (
                <tr>
                  <td colSpan={5} 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-text-muted font-bold uppercase tracking-widest text-[0.65rem]">Accessing Registry...</p>
                  </td>
                </tr>
              ) : filteredAssignments.length === 0 ? (
                <tr>
                  <td colSpan={5} className="py-24 text-center">
                    <FileText size={48} className="mx-auto text-text-muted/20 mb-4" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No {activeTab} assignments recorded</p>
                  </td>
                </tr>
              ) : filteredAssignments.map((assignment) => {
                const submissionsCount = assignment.submissions_count || 0;
                const progress = activeTab === 'graded' ? 100 : Math.round((submissionsCount / 28) * 100);
                
                return (
                  <tr key={assignment.id} 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-12 h-12 rounded-2xl bg-muted dark:bg-muted/20 flex items-center justify-center text-primary dark:text-blue-400 border border-border shadow-inner group-hover:scale-110 transition-transform">
                          <FileText size={22} />
                        </div>
                        <div>
                          <div className="text-[0.95rem] font-bold text-text group-hover:text-primary transition-colors">{assignment.title}</div>
                          <div className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">Ref: ASM-2026-{assignment.id.toString().padStart(3, '0')}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-8 py-5">
                      <span className="px-3 py-1.5 rounded-xl bg-blue-50/10 dark:bg-blue-900/20 text-primary dark:text-blue-400 border border-blue-100/20 dark:border-blue-800/30 text-[0.65rem] font-black uppercase tracking-widest">
                        {assignment.course_name}
                      </span>
                    </td>
                    <td className="px-8 py-5">
                      <div className="space-y-2">
                        <div className="flex justify-between items-center text-[0.6rem] font-black uppercase">
                          <span className="text-text-muted">{submissionsCount} Submissions</span>
                          <span className={activeTab === 'graded' ? 'text-emerald-600' : 'text-primary'}>{progress}%</span>
                        </div>
                        <div className="w-full h-1.5 bg-muted rounded-full overflow-hidden p-0.5 shadow-inner">
                          <div 
                            className={`h-full rounded-full transition-all duration-1000 ${activeTab === 'graded' ? 'bg-emerald-500' : 'bg-primary'}`}
                            style={{ width: `${progress}%` }}
                          />
                        </div>
                      </div>
                    </td>
                    <td className="px-8 py-5">
                       <div className="flex items-center gap-2 text-[0.8rem] font-bold text-text-secondary">
                          <Calendar size={14} className="text-text-muted/50" />
                          {new Date(assignment.due_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                       </div>
                    </td>
                    <td className="px-8 py-5 text-right">
                      <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button 
                          onClick={() => handleEdit(assignment)}
                          className="p-2.5 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm"
                          title="Edit Task"
                        >
                          <Edit2 size={16} />
                        </button>
                        {activeTab === 'active' && (
                          <button 
                            className="p-2.5 bg-primary text-white hover:bg-primary/90 rounded-xl transition-all shadow-lg shadow-blue-900/10 flex items-center gap-2 text-[0.65rem] font-black uppercase tracking-widest px-4"
                            onClick={() => assignment.submissions && assignment.submissions.length > 0 && handleGrade(assignment, assignment.submissions![0])}
                          >
                            <UserCheck size={16} />
                            Grade Work
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Creation Modal */}
      {showModal && (
        <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 max-h-[90vh] flex flex-col border border-border">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
              <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">{editingAssignment ? 'Update Module' : 'Initialize Task'}</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure academic requirements</p>
              </div>
              <button onClick={() => setShowModal(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 shadow-sm">
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Assignment Title</label>
                    <input className="form-input" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="e.g., Mid-Term Physics Report" required />
                </div>
                <div className="grid grid-cols-2 gap-6">
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Course Assignment</label>
                        <input className="form-input" value={form.course_name} onChange={e => setForm({ ...form, course_name: e.target.value })} placeholder="e.g., Physics" required />
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Maximum Score</label>
                        <input className="form-input" type="number" value={form.max_score} onChange={e => setForm({ ...form, max_score: parseInt(e.target.value) || 0 })} required />
                    </div>
                </div>
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Target Deadline</label>
                    <div className="relative">
                        {/* <Calendar size={18} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50" /> */}
                        <input className="form-input pl-12" type="date" value={form.due_date} onChange={e => setForm({ ...form, due_date: e.target.value })} required />
                    </div>
                </div>
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Brief Description</label>
                    <textarea className="form-input" rows={3} value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} placeholder="Outline key objectives and submission requirements..." />
                </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 active:scale-95 flex items-center justify-center gap-3">
                    <CheckCircle2 size={18} />
                    {editingAssignment ? 'Commit Module Updates' : 'Generate Curriculum Task'}
                </button>
            </form>
          </div>
        </div>
      )}

      {/* Grading Modal */}
      {showGradeModal && gradingSubmission && (
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[3rem] w-full max-w-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[95vh] flex flex-col border border-border">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center shrink-0">
              <div className="flex items-center gap-4">
                 <div className="w-12 h-12 rounded-2xl bg-primary text-white flex items-center justify-center shadow-lg">
                    <Award size={24} />
                 </div>
                 <div>
                    <h2 className="text-xl font-black text-text tracking-tight">Intelligence Grading</h2>
                    <p className="text-[0.65rem] font-black text-primary uppercase tracking-widest mt-0.5">Evaluation Portal</p>
                 </div>
              </div>
              <button onClick={() => setShowGradeModal(false)} className="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 shadow-sm">
                <X size={20} />
              </button>
            </div>
            
            <div className="px-10 py-6 bg-blue-50/10 dark:bg-blue-900/20 border-b border-blue-100/20 dark:border-blue-800/30 flex justify-between items-center shrink-0">
                <div>
                    <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Candidate</p>
                    <p className="text-[0.95rem] font-bold text-text">{gradingSubmission.submission.student_name}</p>
                </div>
                <div className="text-right">
                    <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Submission Timestamp</p>
                    <p className="text-[0.8rem] font-bold text-text-secondary">{new Date(gradingSubmission.submission.submitted_at).toLocaleString()}</p>
                </div>
            </div>

            <form onSubmit={(e) => { e.preventDefault(); submitGrade(); }} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
                <div className="space-y-2">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Performance Score (Max: {gradingSubmission.assignment.max_score})</label>
                    <div className="relative">
                        <Award size={20} className="absolute left-5 top-1/2 -translate-y-1/2 text-primary" />
                        <input className="w-full bg-muted/50 border border-border rounded-2xl pl-14 pr-4 py-5 text-2xl font-black text-text focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all" type="number" min="0" max={gradingSubmission.assignment.max_score} value={gradeForm.score} onChange={e => setGradeForm({ ...gradeForm, score: parseInt(e.target.value) || 0 })} required />
                    </div>
                </div>
                <div className="space-y-2">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Educator Feedback</label>
                    <textarea 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" rows={4} value={gradeForm.feedback} onChange={e => setGradeForm({ ...gradeForm, feedback: e.target.value })} placeholder="Provide detailed intelligence feedback for the student..." />
                </div>
                <button type="submit" className="w-full py-5 bg-[#002147] hover:bg-black text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl shadow-blue-900/10 active:scale-95 flex items-center justify-center gap-3">
                    <Send size={18} />
                    Submit Official Grade
                </button>
            </form>
          </div>
        </div>
      )}
      <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; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
      `}</style>
    </div>
  );
}

const mockAssignments: Assignment[] = [
    { id: 1, title: 'Algebra Homework', course_name: 'Mathematics', due_date: '2026-06-10', status: 'active', description: 'Complete exercises 1-20', max_score: 100, submissions_count: 15 },
    { id: 2, title: 'Essay: My Community', course_name: 'English', due_date: '2026-06-05', status: 'active', description: 'Write a 500-word essay', max_score: 50, submissions_count: 22 },
    { id: 3, title: 'Lab Report', course_name: 'Science', due_date: '2026-05-28', status: 'graded', max_score: 100, graded_count: 28 },
];