/**
 * Teacher Assignments Page
 *
 * Teacher-side control plane for /api/assignments:
 *   - Draft / Published / Closed status tabs
 *   - Create assignment modal (course picked from /subjects)
 *   - Lifecycle actions: publish, unpublish, close, delete
 *   - Submissions drawer with per-submission grading
 *   - CSV export of filtered assignments
 *
 * Talks to:
 *   client/src/store/teacherAssignments.ts (Zustand)
 *   server/src/controllers/assignments.controller.js
 */

import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import {
  Plus, FileText, Calendar, ChevronRight, Search, X, Download,
  Sparkles, CheckCircle2, Clock, Edit2, Send, Eye,
  Award, MessageSquare, Trash2, Filter, BarChart3,
  PlayCircle, PauseCircle, StopCircle
} from 'lucide-react';
import { useEducationTerms } from '../../utils/educationTerms';
import { useAuthStore } from '../../store/auth';
import api from '../../store/api';
import {
  useTeacherAssignmentStore,
  type Assignment,
  type AssignmentPayload,
  type AssignmentStatus,
  type Submission,
  type TeacherCourse,
} from '../../store/teacherAssignments';
import { AttachmentUploader } from '../../components/AttachmentUploader';
import { AttachmentList } from '../../components/AttachmentList';

const STATUS_TABS: { id: AssignmentStatus; label: string; tone: string }[] = [
  { id: 'draft', label: 'Draft', tone: 'amber' },
  { id: 'published', label: 'Published', tone: 'blue' },
  { id: 'closed', label: 'Closed', tone: 'slate' },
];

const DUE_FILTERS = ['all', 'today', 'week', 'overdue'] as const;
type DueFilter = (typeof DUE_FILTERS)[number];

const EMPTY_FORM: AssignmentPayload & { allow_late_submission: boolean } = {
  course_id: 0,
  title: '',
  description: '',
  instructions: '',
  due_date: '',
  max_score: 100,
  submission_type: 'file',
  allow_late_submission: false,
};

function isOverdue(due: string | null | undefined, status: AssignmentStatus) {
  if (!due || status === 'closed') return false;
  return new Date(due) < new Date();
}

function formatDue(due: string | null | undefined) {
  if (!due) return 'No deadline';
  return new Date(due).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

export default function TeacherAssignments() {
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const {
    assignments, current, submissions, isLoading, isMutating, error,
    fetchAssignments, fetchAssignment,
    createAssignment, updateAssignment, deleteAssignment,
    publishAssignment, unpublishAssignment, closeAssignment,
    gradeSubmission, returnSubmission,
  } = useTeacherAssignmentStore();

  const [activeTab, setActiveTab] = useState<AssignmentStatus>('draft');
  const [search, setSearch] = useState('');
  const [dueFilter, setDueFilter] = useState<DueFilter>('all');
  const [courses, setCourses] = useState<TeacherCourse[]>([]);
  const [showCreate, setShowCreate] = useState(false);
  const [editing, setEditing] = useState<Assignment | null>(null);
  const [form, setForm] = useState(EMPTY_FORM);
  const [formError, setFormError] = useState<string | null>(null);
  const [openAssignment, setOpenAssignment] = useState<Assignment | null>(null);
  const [grading, setGrading] = useState<Submission | null>(null);
  const [gradeForm, setGradeForm] = useState({ grade: 0, feedback: '' });

  useEffect(() => {
    fetchAssignments({ status: activeTab }).catch(() => {});
  }, [activeTab, fetchAssignments]);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        // /api/courses is the real courses/subjects table the assignments controller
        // FK-references. /api/subjects is a separate, unrelated subject registry used
        // by attendance; MyCourses.tsx happens to call /subjects and quietly falls
        // back to mocks when it returns 0 rows. Use /courses here so the picker
        // reflects what the assignments POST will actually accept.
        const res = await api.get('/courses');
        if (!cancelled) {
          const mine = (res.data as any[]).filter(
            (s) => !user?.id || s.teacher_id === user.id
          );
          setCourses(
            mine.map((s) => ({ id: s.id, name: s.name, class_name: s.class_name }))
          );
        }
      } catch {
        if (!cancelled) setCourses([]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [user?.id]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    const now = new Date();
    const startToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const endToday = new Date(startToday.getTime() + 24 * 60 * 60 * 1000);
    const endWeek = new Date(startToday.getTime() + 7 * 24 * 60 * 60 * 1000);

    return assignments.filter((a) => {
      if (a.status !== activeTab) return false;
      if (q && !`${a.title} ${a.course_name ?? ''}`.toLowerCase().includes(q)) return false;
      const due = a.due_date ? new Date(a.due_date) : null;
      if (dueFilter === 'today' && (!due || due < startToday || due >= endToday)) return false;
      if (dueFilter === 'week' && (!due || due < startToday || due >= endWeek)) return false;
      if (dueFilter === 'overdue' && (!due || due >= startToday || a.status === 'closed')) return false;
      return true;
    });
  }, [assignments, activeTab, search, dueFilter]);

  const counts = useMemo(
    () => ({
      draft: assignments.filter((a) => a.status === 'draft').length,
      published: assignments.filter((a) => a.status === 'published').length,
      closed: assignments.filter((a) => a.status === 'closed').length,
    }),
    [assignments]
  );

  const totalsForVisible = useMemo(() => {
    const submitted = filtered.reduce((s, a) => s + (a.submission_count ?? 0), 0);
    const graded = filtered.reduce((s, a) => s + (a.graded_count ?? 0), 0);
    return { submitted, graded };
  }, [filtered]);

  const openEditor = (assignment?: Assignment) => {
    setFormError(null);
    if (assignment) {
      setEditing(assignment);
      setForm({
        course_id: assignment.course_id,
        title: assignment.title,
        description: assignment.description ?? '',
        instructions: assignment.instructions ?? '',
        due_date: assignment.due_date ? assignment.due_date.slice(0, 10) : '',
        max_score: assignment.max_score ?? 100,
        submission_type: assignment.submission_type ?? 'file',
        allow_late_submission: !!assignment.allow_late_submission,
      });
    } else {
      setEditing(null);
      setForm({ ...EMPTY_FORM, course_id: courses[0]?.id ?? 0 });
    }
    setShowCreate(true);
  };

  const submitForm = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);
    if (!form.course_id) {
      setFormError(`Pick a ${terms.subject.toLowerCase()}`);
      return;
    }
    if (!form.title.trim()) {
      setFormError('Title is required');
      return;
    }
    try {
      const payload: AssignmentPayload = {
        course_id: form.course_id,
        title: form.title.trim(),
        description: form.description || undefined,
        instructions: form.instructions || undefined,
        due_date: form.due_date || null,
        max_score: form.max_score,
        submission_type: form.submission_type,
        allow_late_submission: form.allow_late_submission,
      };
      if (editing) {
        await updateAssignment(editing.id, payload);
      } else {
        await createAssignment(payload);
      }
      setShowCreate(false);
      setEditing(null);
      setForm(EMPTY_FORM);
      await fetchAssignments({ status: activeTab });
    } catch (err: any) {
      setFormError(err?.response?.data?.error || err?.message || 'Could not save');
    }
  };

  const handleLifecycle = async (action: 'publish' | 'unpublish' | 'close' | 'delete', id: number) => {
    const map = {
      publish: publishAssignment,
      unpublish: unpublishAssignment,
      close: closeAssignment,
      delete: deleteAssignment,
    } as const;
    try {
      await map[action](id);
      if (openAssignment?.id === id) setOpenAssignment(null);
      await fetchAssignments({ status: activeTab });
    } catch (err: any) {
      alert(err?.response?.data?.error || err?.message || 'Action failed');
    }
  };

  const openSubmissions = async (assignment: Assignment) => {
    setOpenAssignment(assignment);
    await fetchAssignment(assignment.id);
  };

  const submitGrade = async () => {
    if (!grading || !openAssignment) return;
    try {
      await gradeSubmission(openAssignment.id, grading.id, {
        grade: gradeForm.grade,
        feedback: gradeForm.feedback,
      });
      setGrading(null);
      setGradeForm({ grade: 0, feedback: '' });
    } catch (err: any) {
      alert(err?.response?.data?.error || err?.message || 'Could not save grade');
    }
  };

  const exportCsv = () => {
    const headers = ['ID', 'Title', terms.subject, 'Due Date', 'Status', 'Submissions', 'Graded', 'Max Score'];
    const rows = filtered.map((a) => [
      a.id,
      `"${(a.title || '').replace(/"/g, '""')}"`,
      `"${(a.course_name || '').replace(/"/g, '""')}"`,
      a.due_date ?? '',
      a.status,
      a.submission_count ?? 0,
      a.graded_count ?? 0,
      a.max_score ?? 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', `assignments-${activeTab}-${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* 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-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
            type="button"
            onClick={exportCsv}
            disabled={!filtered.length}
            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 disabled:opacity-40 disabled:cursor-not-allowed"
          >
            <Download size={18} />
            Export CSV
          </button>
          <button
            type="button"
            onClick={() => openEditor()}
            disabled={!courses.length}
            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 disabled:opacity-40 disabled:cursor-not-allowed"
            title={courses.length ? 'Create a new assignment' : `You need to be assigned to at least one ${terms.subject.toLowerCase()} first`}
          >
            <Plus size={18} />
            New Assignment
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {STATUS_TABS.slice(0, 3).map((tab) => (
          <div
            key={tab.id}
            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 bg-blue-50 dark:bg-blue-900/20 text-primary dark:text-blue-400 border-blue-100 dark:border-blue-800 flex items-center justify-center group-hover:scale-110 transition-transform border">
              <FileText size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{tab.label}</p>
              <p className="text-2xl font-black text-text">{counts[tab.id]}</p>
            </div>
          </div>
        ))}
        <div 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 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800 flex items-center justify-center group-hover:scale-110 transition-transform border">
            <BarChart3 size={22} />
          </div>
          <div>
            <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">
              Visible: Submitted / Graded
            </p>
            <p className="text-2xl font-black text-text">
              {totalsForVisible.submitted} <span className="text-text-muted text-base">/ {totalsForVisible.graded}</span>
            </p>
          </div>
        </div>
      </div>

      {/* Toolbar */}
      <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="flex p-1 bg-muted/50 rounded-2xl flex-1 min-w-0">
          {STATUS_TABS.map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => setActiveTab(tab.id)}
              className={`flex-1 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all ${
                activeTab === tab.id
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border'
                  : 'text-text-muted hover:text-text'
              }`}
            >
              {tab.label}
              <span className="ml-2 opacity-50">{counts[tab.id]}</span>
            </button>
          ))}
        </div>
        <div className="relative group min-w-[260px]">
          <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"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder={`Search by title or ${terms.subject.toLowerCase()}...`}
            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"
          />
        </div>
        <button
          type="button"
          onClick={() => setDueFilter((cur) => DUE_FILTERS[(DUE_FILTERS.indexOf(cur) + 1) % DUE_FILTERS.length])}
          className={`px-5 py-3 rounded-2xl border transition-all flex items-center justify-center gap-2 ${
            dueFilter !== 'all'
              ? 'bg-primary text-white border-primary'
              : 'bg-muted/50 hover:bg-muted text-text-muted border-border'
          }`}
          title="Cycle due-date filter"
        >
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest">
            {dueFilter === 'all' && 'All Due'}
            {dueFilter === 'today' && 'Due Today'}
            {dueFilter === 'week' && 'This Week'}
            {dueFilter === 'overdue' && 'Overdue'}
          </span>
        </button>
      </div>

      {/* Table */}
      <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
        <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
                </th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">{terms.subject}</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Deadline</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">
                  Submissions
                </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">
              {isLoading ? (
                <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" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">
                      Loading assignments...
                    </p>
                  </td>
                </tr>
              ) : error ? (
                <tr>
                  <td colSpan={5} className="py-20 text-center">
                    <p className="text-rose-500 font-bold">{error}</p>
                  </td>
                </tr>
              ) : filtered.length === 0 ? (
                <tr>
                  <td colSpan={5} className="py-24 text-center">
                    <FileText size={48} className="mx-auto text-text-muted/20 mb-4" />
                    {courses.length === 0 ? (
                      <>
                        <p className="text-text font-black uppercase tracking-widest text-[0.7rem]">
                          Not assigned to any {terms.subject.toLowerCase()} yet
                        </p>
                        <p className="text-text-muted text-xs font-bold mt-2 max-w-sm mx-auto">
                          Once an administrator links you to a {terms.subject.toLowerCase()}, new assignments can be created from here.
                        </p>
                      </>
                    ) : (
                      <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">
                        No {activeTab} assignments
                      </p>
                    )}
                  </td>
                </tr>
              ) : (
                filtered.map((a) => (
                  <tr key={a.id} className="hover:bg-muted/30 transition-colors group">
                    <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">
                            {a.title}
                          </div>
                          <div className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">
                            Ref: ASM-{a.id.toString().padStart(4, '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">
                        {a.course_name || '—'}
                      </span>
                    </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" />
                        <span className={isOverdue(a.due_date, a.status) ? 'text-rose-500' : ''}>
                          {formatDue(a.due_date)}
                        </span>
                      </div>
                    </td>
                    <td className="px-8 py-5">
                      <div className="space-y-1">
                        <div className="text-[0.6rem] font-black uppercase text-text-muted">
                          {a.submission_count ?? 0} submitted · {a.graded_count ?? 0} graded
                        </div>
                        <div className="w-32 h-1.5 bg-muted rounded-full overflow-hidden shadow-inner">
                          <div
                            className="h-full bg-primary rounded-full transition-all duration-700"
                            style={{
                              width: `${Math.min(
                                100,
                                Math.round(((a.graded_count ?? 0) / Math.max(1, a.submission_count ?? 0)) * 100)
                              )}%`,
                            }}
                          />
                        </div>
                      </div>
                    </td>
                    <td className="px-8 py-5 text-right">
                      <div className="flex justify-end gap-2 flex-wrap">
                        <button
                          type="button"
                          onClick={() => openSubmissions(a)}
                          className="p-2.5 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm flex items-center gap-2 px-3 text-[0.65rem] font-black uppercase tracking-widest"
                        >
                          <Eye size={14} /> View
                        </button>
                        {a.status === 'draft' && (
                          <>
                            <button
                              type="button"
                              onClick={() => openEditor(a)}
                              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"
                              disabled={isMutating}
                            >
                              <Edit2 size={16} />
                            </button>
                            <button
                              type="button"
                              onClick={() => handleLifecycle('publish', a.id)}
                              className="p-2.5 bg-emerald-500 text-white hover:bg-emerald-600 rounded-xl transition-all shadow-lg flex items-center gap-2 px-3 text-[0.65rem] font-black uppercase tracking-widest"
                              disabled={isMutating}
                            >
                              <PlayCircle size={14} /> Publish
                            </button>
                          </>
                        )}
                        {a.status === 'published' && (
                          <>
                            <button
                              type="button"
                              onClick={() => handleLifecycle('unpublish', a.id)}
                              className="p-2.5 bg-card border border-border text-text-muted hover:text-amber-500 hover:border-amber-500 rounded-xl transition-all shadow-sm flex items-center gap-2 px-3 text-[0.65rem] font-black uppercase tracking-widest"
                              disabled={isMutating}
                            >
                              <PauseCircle size={14} /> Unpublish
                            </button>
                            <button
                              type="button"
                              onClick={() => handleLifecycle('close', a.id)}
                              className="p-2.5 bg-slate-700 text-white hover:bg-slate-900 rounded-xl transition-all shadow-lg flex items-center gap-2 px-3 text-[0.65rem] font-black uppercase tracking-widest"
                              disabled={isMutating}
                            >
                              <StopCircle size={14} /> Close
                            </button>
                          </>
                        )}
                        {(a.status === 'draft' || a.status === 'closed') && (
                          <button
                            type="button"
                            onClick={() => {
                              if (confirm(`Delete "${a.title}"? This cannot be undone.`)) {
                                handleLifecycle('delete', a.id);
                              }
                            }}
                            className="p-2.5 bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-500 rounded-xl transition-all shadow-sm"
                            title="Delete"
                            disabled={isMutating}
                          >
                            <Trash2 size={16} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create / Edit modal */}
      {showCreate && createPortal(
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowCreate(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 sm:px-10 py-6 sm: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 pointer-events-none">
                <Sparkles size={180} />
              </div>
              <div className="relative z-10 min-w-0 flex-1 pr-3">
                <h2 className="text-xl sm:text-2xl font-black text-text tracking-tight truncate">
                  {editing ? 'Update Assignment' : 'New Assignment'}
                </h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1 truncate">
                  {editing ? `Editing ${editing.title}` : 'Saved as draft. Publish when ready.'}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setShowCreate(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 shrink-0 cursor-pointer"
              >
                <X size={20} />
              </button>
            </div>
            <form onSubmit={submitForm} className="p-4 sm:p-8 md:p-10 space-y-4 sm:space-y-5 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">Title</label>
                <input
                  className="form-input text-text"
                  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-1 sm:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject}</label>
                  <select
                    className="form-input text-text"
                    value={form.course_id}
                    onChange={(e) => setForm({ ...form, course_id: Number(e.target.value) })}
                    required
                  >
                    <option value={0}>Select a {terms.subject.toLowerCase()}</option>
                    {courses.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name}
                        {c.class_name ? ` — ${c.class_name}` : ''}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Deadline</label>
                  <input
                    className="form-input text-text"
                    type="date"
                    value={form.due_date}
                    onChange={(e) => setForm({ ...form, due_date: e.target.value })}
                  />
                </div>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Max score</label>
                  <input
                    className="form-input"
                    type="number"
                    min={1}
                    value={form.max_score}
                    onChange={(e) => setForm({ ...form, max_score: Number(e.target.value) || 0 })}
                    required
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Submission type</label>
                  <select
                    className="form-input"
                    value={form.submission_type}
                    onChange={(e) => setForm({ ...form, submission_type: e.target.value as AssignmentPayload['submission_type'] })}
                  >
                    <option value="file">File upload</option>
                    <option value="text">Text response</option>
                    <option value="online">Online (in-app)</option>
                    <option value="offline">Offline (in-class)</option>
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Late policy</label>
                  <label className="flex items-center gap-2 h-[46px] px-4 rounded-2xl border border-border bg-muted/40">
                    <input
                      type="checkbox"
                      checked={form.allow_late_submission}
                      onChange={(e) => setForm({ ...form, allow_late_submission: e.target.checked })}
                      className="w-4 h-4 accent-primary"
                    />
                    <span className="text-xs font-bold text-text-secondary">Allow late submissions</span>
                  </label>
                </div>
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Description</label>
                <textarea
                  className="form-input"
                  rows={2}
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  placeholder="Short summary visible to students"
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Instructions</label>
                <textarea
                  className="form-input"
                  rows={3}
                  value={form.instructions}
                  onChange={(e) => setForm({ ...form, instructions: e.target.value })}
                  placeholder="Detailed instructions, rubric, deliverables..."
                />
              </div>
              {!editing && (
                <div className="p-4 bg-blue-50/20 border border-blue-100 rounded-2xl">
                  <p className="text-xs font-bold text-blue-700/80 uppercase tracking-wider flex items-center gap-1.5">
                    <span>💡</span> Attachments & Media
                  </p>
                  <p className="text-[0.7rem] text-text-muted mt-1 leading-relaxed">
                    Once you save this assignment, select it from your list to attach supplementary PDFs, Word (DOCX) files, video clips, audios, or zip archives.
                  </p>
                </div>
              )}
              {editing && (
                <div className="space-y-2 p-4 bg-muted/20 border border-border rounded-2xl">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Reference Materials (Attachments)</label>
                  <AttachmentList
                    parent_kind="assignment"
                    parent_id={editing.id}
                    emptyMessage="No files uploaded yet."
                  />
                  <AttachmentUploader
                    parent_kind="assignment"
                    parent_id={editing.id}
                  />
                </div>
              )}
              {formError && (
                <p className="text-rose-500 text-xs font-bold">{formError}</p>
              )}
              <button
                type="submit"
                disabled={isMutating}
                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 disabled:opacity-40"
              >
                <CheckCircle2 size={18} />
                {editing ? 'Save Changes' : 'Save as Draft'}
              </button>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Submissions drawer */}
      {openAssignment && createPortal(
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[140] flex items-stretch justify-end" onClick={() => setOpenAssignment(false)}>
          <div className="bg-card w-full max-w-2xl shadow-2xl border-l border-border flex flex-col" onClick={(e) => e.stopPropagation()}>
            <div className="px-8 py-6 border-b border-border flex justify-between items-center shrink-0">
              <div>
                <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                  Submissions
                </p>
                <h2 className="text-xl font-black text-text">{openAssignment.title}</h2>
                <p className="text-xs text-text-muted mt-1">
                  {openAssignment.course_name} · max {openAssignment.max_score}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setOpenAssignment(null)}
                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="flex-1 overflow-y-auto p-8 space-y-3">
              {isLoading ? (
                <div className="text-center py-20">
                  <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-3" />
                  <p className="text-text-muted text-xs font-bold uppercase tracking-widest">Loading...</p>
                </div>
              ) : submissions.length === 0 ? (
                <div className="text-center py-20">
                  <MessageSquare size={40} className="mx-auto text-text-muted/20 mb-3" />
                  <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">
                    No submissions yet
                  </p>
                </div>
              ) : (
                submissions.map((s) => (
                  <div
                    key={s.id}
                    className="border border-border rounded-2xl p-4 flex items-center gap-4 hover:bg-muted/30 transition-colors"
                  >
                    <div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/20 text-primary flex items-center justify-center font-black">
                      {s.student_name?.[0] ?? '?'}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-bold text-text truncate">{s.student_name}</div>
                      <div className="text-[0.65rem] text-text-muted">
                        Submitted {new Date(s.submitted_at).toLocaleString()}
                      </div>
                    </div>
                    <div className="text-right">
                      {s.status === 'graded' ? (
                        <div>
                          <div className="font-black text-emerald-600">
                            {s.grade} / {openAssignment.max_score}
                          </div>
                          <div className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">
                            graded
                          </div>
                        </div>
                      ) : (
                        <div className="text-[0.65rem] uppercase font-black tracking-widest text-amber-600">
                          pending
                        </div>
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        setGrading(s);
                        setGradeForm({
                          grade: s.grade ?? 0,
                          feedback: s.feedback ?? '',
                        });
                      }}
                      className="p-2.5 bg-primary text-white hover:bg-primary/90 rounded-xl transition-all shadow-lg flex items-center gap-2 px-3 text-[0.65rem] font-black uppercase tracking-widest"
                    >
                      <Award size={14} /> Grade
                    </button>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Grade modal */}
      {grading && openAssignment && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[160] flex items-center justify-center p-3 sm:p-6 overflow-y-auto" onClick={() => setGrading(null)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col border border-border my-auto" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 sm:px-10 py-6 sm:py-8 bg-muted/50 border-b border-border flex justify-between items-center shrink-0">
              <div className="flex items-center gap-3 sm:gap-4 min-w-0 flex-1 pr-2">
                <div className="w-10 h-10 sm:w-12 sm:h-12 rounded-2xl bg-primary text-white flex items-center justify-center shadow-lg shrink-0">
                  <Award size={22} />
                </div>
                <div className="min-w-0 flex-1">
                  <h2 className="text-lg sm:text-xl font-black text-text tracking-tight truncate">Grade Submission</h2>
                  <p className="text-[0.65rem] font-black text-primary uppercase tracking-widest mt-0.5 truncate">
                    {grading.student_name}
                  </p>
                </div>
              </div>
              <button
                type="button"
                onClick={() => setGrading(null)}
                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 shrink-0 cursor-pointer"
              >
                <X size={20} />
              </button>
            </div>
            <div className="px-6 sm:px-10 py-3 sm:py-4 bg-blue-50/10 dark:bg-blue-900/20 border-b border-blue-100/20 dark:border-blue-800/30 text-[0.65rem] uppercase tracking-widest text-text-muted font-black">
              Max: {openAssignment.max_score} · Submitted {new Date(grading.submitted_at).toLocaleString()}
            </div>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                submitGrade();
              }}
              className="p-4 sm:p-8 md:p-10 space-y-4 sm:space-y-5 overflow-y-auto max-h-[60vh] custom-scrollbar text-left"
            >
              {grading.content && (
                <div className="space-y-1.5 p-4 bg-muted/30 rounded-2xl border border-border">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Student Comments / Text</label>
                  <p className="text-sm font-semibold text-text whitespace-pre-wrap">{grading.content}</p>
                </div>
              )}
              
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Student's Uploaded Files</label>
                <AttachmentList
                  parent_kind="submission"
                  parent_id={grading.id}
                  emptyMessage="No files uploaded by student."
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Score</label>
                <input
                  type="number"
                  min={0}
                  max={openAssignment.max_score}
                  step="0.5"
                  value={gradeForm.grade}
                  onChange={(e) => setGradeForm({ ...gradeForm, grade: Number(e.target.value) || 0 })}
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 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"
                  required
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Feedback</label>
                <textarea
                  rows={4}
                  value={gradeForm.feedback}
                  onChange={(e) => setGradeForm({ ...gradeForm, feedback: e.target.value })}
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all"
                  placeholder="What did this student do well? What needs work?"
                />
              </div>

              <div className="space-y-1.5 border-t border-border pt-4">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Marked Script Upload (PDF/Doc/Image)</label>
                <AttachmentList
                  parent_kind="marked_script"
                  parent_id={grading.id}
                  emptyMessage="No marked script uploaded yet."
                />
                <AttachmentUploader
                  parent_kind="marked_script"
                  parent_id={grading.id}
                  compact={true}
                />
              </div>

              <div className="flex flex-col gap-3 pt-2">
                <button
                  type="submit"
                  disabled={isMutating}
                  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 active:scale-95 flex items-center justify-center gap-3 disabled:opacity-40"
                >
                  <Send size={18} />
                  {grading.status === 'graded' || grading.status === 'returned' ? 'Update Grade & Feedback' : 'Submit Grade & Feedback'}
                </button>
                
                {grading.status !== 'returned' && (
                  <button
                    type="button"
                    onClick={async () => {
                      try {
                        await returnSubmission(openAssignment.id, grading.id);
                        alert('Assignment marked script returned to student');
                        setGrading(null);
                        await fetchAssignments({ status: activeTab });
                      } catch (err: any) {
                        alert(err?.response?.data?.error || err.message);
                      }
                    }}
                    className="w-full py-4 bg-emerald-600 hover:bg-emerald-700 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} />
                    Return to Student
                  </button>
                )}
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}
    </div>
  );
}