import React, { useEffect, 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
} from 'lucide-react';
import { useAuthStore } from '../../store/auth';
import api from '../../store/api';
import { useTestStore, type TestPaper, type TestSubmission } from '../../store/tests';
import { AttachmentUploader } from '../../components/AttachmentUploader';
import { useEducationTerms } from '../../utils/educationTerms';
import { AttachmentList } from '../../components/AttachmentList';

type TestStatus = 'draft' | 'published' | 'closed';

interface Course {
  id: number;
  name: string;
  code: string;
  class_name?: string;
  class_id?: number;
}

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

export default function TestsPage() {
  const user = useAuthStore(s => s.user);
  const terms = useEducationTerms();
  const { 
    items, current, submissions, loading, error,
    list, get, create, update, remove, submit, grade, returnSubmission
  } = useTestStore();

  const [activeTab, setActiveTab] = useState<TestStatus>('draft');
  const [search, setSearch] = useState('');
  const [courses, setCourses] = useState<Course[]>([]);
  const [showCreate, setShowCreate] = useState(false);
  const [editing, setEditing] = useState<TestPaper | null>(null);
  const [openTest, setOpenTest] = useState<TestPaper | null>(null);
  const [grading, setGrading] = useState<TestSubmission | null>(null);
  const [form, setForm] = useState({
    subject_id: '',
    class_id: '',
    title: '',
    description: '',
    instructions: '',
    test_date: '',
    duration_minutes: 60,
    max_score: 100,
    allow_late_submission: false
  });
  const [gradeForm, setGradeForm] = useState({ grade: 0, feedback: '' });
  const [formError, setFormError] = useState<string | null>(null);

  const loadData = async () => {
    try {
      await list();
      const res = await api.get(user?.role === 'teacher' ? '/teacher/subjects' : '/subjects');
      setCourses(Array.isArray(res.data) ? res.data : []);
    } catch (e) {
      console.error(e);
    }
  };

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

  const handleOpenEdit = (t: TestPaper) => {
    setEditing(t);
    setForm({
      subject_id: String(t.subject_id),
      class_id: t.class_id ? String(t.class_id) : '',
      title: t.title,
      description: t.description || '',
      instructions: t.instructions || '',
      test_date: t.test_date ? t.test_date.substring(0, 16) : '',
      duration_minutes: t.duration_minutes || 60,
      max_score: t.max_score || 100,
      allow_late_submission: !!t.allow_late_submission
    });
    setShowCreate(true);
  };

  const handleOpenCreate = () => {
    setEditing(null);
    setForm({
      subject_id: '',
      class_id: '',
      title: '',
      description: '',
      instructions: '',
      test_date: '',
      duration_minutes: 60,
      max_score: 100,
      allow_late_submission: false
    });
    setShowCreate(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);
    if (!form.subject_id) {
      setFormError(`${terms.subject} is required`);
      return;
    }
    if (!form.title.trim()) {
      setFormError('Title is required');
      return;
    }

    try {
      const selectedCourse = courses.find(c => String(c.id) === form.subject_id);
      const classId = selectedCourse?.class_id || null;

      const payload = {
        subject_id: Number(form.subject_id),
        class_id: classId,
        title: form.title.trim(),
        description: form.description || null,
        instructions: form.instructions || null,
        test_date: form.test_date || null,
        duration_minutes: Number(form.duration_minutes) || null,
        max_score: Number(form.max_score) || 100,
        allow_late_submission: form.allow_late_submission ? 1 : 0
      };

      if (editing) {
        await update(editing.id, payload);
      } else {
        await create(payload);
      }
      setShowCreate(false);
      setEditing(null);
      await list();
    } catch (err: any) {
      setFormError(err?.response?.data?.error || err.message || 'Could not save');
    }
  };

  const handleOpenSubmissions = async (t: TestPaper) => {
    setOpenTest(t);
    await get(t.id);
  };

  const handleLifecycle = async (action: 'publish' | 'close' | 'delete', id: number) => {
    try {
      if (action === 'publish') {
        await update(id, { status: 'published' });
      } else if (action === 'close') {
        await update(id, { status: 'closed' });
      } else if (action === 'delete') {
        if (confirm('Are you sure you want to delete this test?')) {
          await remove(id);
          if (openTest?.id === id) setOpenTest(null);
        }
      }
      await list();
    } catch (err: any) {
      alert(err?.response?.data?.error || err.message || 'Action failed');
    }
  };

  const submitGrade = async () => {
    if (!openTest || !grading) return;
    try {
      await grade(openTest.id, grading.id, {
        grade: gradeForm.grade,
        feedback: gradeForm.feedback
      });
      alert('Grade saved successfully');
      setGrading(null);
      await get(openTest.id);
    } catch (err: any) {
      alert(err?.response?.data?.error || err.message || 'Could not grade');
    }
  };

  // Filtered Tests list
  const filteredItems = items.filter(t => {
    const matchesTab = t.status === activeTab;
    const matchesSearch = t.title.toLowerCase().includes(search.toLowerCase()) || 
                          t.subject_name?.toLowerCase().includes(search.toLowerCase());
    return matchesTab && matchesSearch;
  });

  const getSubmissions = () => {
    if (!openTest) return [];
    return submissions[openTest.id] || [];
  };

  return (
    <div className="p-4 sm:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-border pb-6">
        <div>
          <h1 className="text-2xl font-black text-text tracking-tight uppercase">Test Manager</h1>
          <p className="text-xs text-text-muted mt-1 uppercase font-bold tracking-widest">
            Deploy assessments, check answers, and return marked script scripts
          </p>
        </div>
        <button
          onClick={handleOpenCreate}
          className="flex items-center gap-2 px-5 py-3 bg-primary hover:bg-primary/90 text-white rounded-2xl transition-all shadow-lg active:scale-95 text-xs font-black uppercase tracking-widest shrink-0"
        >
          <Plus size={16} /> Deploy Test
        </button>
      </div>

      {/* Tabs & Search */}
      <div className="flex flex-col md:flex-row gap-4 justify-between items-stretch md:items-center">
        <div className="flex bg-card border border-border p-1.5 rounded-2xl gap-1 shrink-0 overflow-x-auto no-scrollbar">
          {STATUS_TABS.map(tab => {
            const isSelected = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2.5 rounded-xl text-xs font-black uppercase tracking-wider transition-all whitespace-nowrap ${
                  isSelected ? 'bg-primary text-white shadow-md' : 'text-text-muted hover:text-text'
                }`}
              >
                {tab.label}
              </button>
            );
          })}
        </div>

        <div className="flex max-w-md w-full bg-card border border-border rounded-2xl px-4 py-3 items-center gap-3">
          <Search className="text-text-muted/40 shrink-0" size={18} />
          <input
            type="text"
            placeholder="Search tests..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="w-full bg-transparent border-none outline-none text-sm font-semibold placeholder:text-text-muted/40 text-text"
          />
        </div>
      </div>

      {/* Tests Grid */}
      {loading ? (
        <div 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-xs font-black uppercase tracking-widest text-text-muted">Syncing Pedagogical Vault...</p>
        </div>
      ) : filteredItems.length === 0 ? (
        <div className="py-20 text-center bg-card border border-border rounded-3xl">
          <FileText size={48} className="mx-auto text-text-muted/20 mb-4" />
          <p className="text-xs font-black uppercase tracking-widest text-text-muted">No tests scheduled</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredItems.map(t => (
            <div
              key={t.id}
              className="bg-card border border-border rounded-3xl p-6 hover:shadow-xl hover:shadow-primary/5 transition-all group flex flex-col justify-between"
            >
              <div>
                <div className="flex justify-between items-start gap-2">
                  <span className="text-[0.6rem] font-black uppercase tracking-widest px-2.5 py-1 rounded-lg bg-primary/10 text-primary border border-primary/10">
                    {t.subject_name}
                  </span>
                  <div className="flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => handleOpenEdit(t)}
                      className="p-2 rounded-xl bg-muted border border-border text-text-muted hover:text-primary hover:bg-primary/5 transition-colors"
                      title="Edit"
                    >
                      <Edit2 size={12} />
                    </button>
                    <button
                      onClick={() => handleLifecycle('delete', t.id)}
                      className="p-2 rounded-xl bg-muted border border-border text-text-muted hover:text-rose-600 hover:bg-rose-50 transition-colors"
                      title="Delete"
                    >
                      <Trash2 size={12} />
                    </button>
                  </div>
                </div>

                <h3 className="text-base font-bold text-text mt-4 leading-snug">
                  {t.title}
                </h3>
                {t.description && (
                  <p className="text-xs text-text-muted mt-2 line-clamp-2">
                    {t.description}
                  </p>
                )}

                <div className="flex flex-wrap gap-x-4 gap-y-1.5 mt-4">
                  <div className="flex items-center gap-1.5 text-[0.7rem] text-text-muted font-bold uppercase tracking-wide">
                    <Calendar size={12} />
                    <span>Date: {t.test_date ? new Date(t.test_date).toLocaleDateString() : 'No date'}</span>
                  </div>
                  {t.duration_minutes && (
                    <div className="flex items-center gap-1.5 text-[0.7rem] text-text-muted font-bold uppercase tracking-wide">
                      <Clock size={12} />
                      <span>{t.duration_minutes} mins</span>
                    </div>
                  )}
                </div>
              </div>

              <div className="border-t border-border/50 pt-4 mt-6 flex justify-between items-center">
                <div className="text-[0.65rem] font-bold text-text-muted uppercase">
                  {t.submission_count || 0} Submissions
                </div>

                <div className="flex gap-2">
                  {t.status === 'draft' && (
                    <button
                      onClick={() => handleLifecycle('publish', t.id)}
                      className="px-3.5 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-[0.6rem] font-black uppercase tracking-widest transition-all"
                    >
                      Publish
                    </button>
                  )}
                  {t.status === 'published' && (
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleOpenSubmissions(t)}
                        className="px-3.5 py-2 bg-primary text-white rounded-xl text-[0.6rem] font-black uppercase tracking-widest transition-all shadow-md"
                      >
                        Grade
                      </button>
                      <button
                        onClick={() => handleLifecycle('close', t.id)}
                        className="px-3.5 py-2 bg-rose-50 text-rose-600 border border-rose-100 rounded-xl text-[0.6rem] font-black uppercase tracking-widest transition-all"
                      >
                        Close
                      </button>
                    </div>
                  )}
                  {t.status === 'closed' && (
                    <button
                      onClick={() => handleOpenSubmissions(t)}
                      className="px-3.5 py-2 bg-muted text-text-muted border border-border rounded-xl text-[0.6rem] font-black uppercase tracking-widest transition-all"
                    >
                      View Grades
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create/Edit Modal */}
      {showCreate && createPortal(
        <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-sm z-[200] flex items-center justify-center p-3 sm:p-4" onClick={() => setShowCreate(false)}>
          <div className="bg-card rounded-3xl 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" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-6 bg-muted 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 text-left">
                <h2 className="text-lg font-black text-text tracking-tight uppercase">{editing ? 'Edit Test' : 'New Test'}</h2>
                <p className="text-[0.55rem] font-bold text-text-muted uppercase tracking-widest mt-1">Setup test parameters</p>
              </div>
              <button onClick={() => setShowCreate(false)} className="relative z-10 w-9 h-9 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-6 space-y-6 overflow-y-auto flex-1 custom-scrollbar text-left">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Test Title</label>
                <input 
                  className="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                  value={form.title}
                  onChange={e => setForm({...form, title: e.target.value})} 
                  placeholder="e.g., Algebra Midterm Exam" 
                  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} Registry</label>
                  <select 
                    className="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text" 
                    value={form.subject_id} 
                    onChange={e => setForm({...form, subject_id: e.target.value})} 
                    required
                  >
                    <option value="">Select {terms.subject}</option>
                    {courses.map(c => (
                      <option key={c.id} value={c.id}>{c.name} ({c.class_name || 'No 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">Test Date</label>
                  <input 
                    type="datetime-local"
                    className="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text font-mono" 
                    value={form.test_date} 
                    onChange={e => setForm({...form, test_date: e.target.value})} 
                    required
                  />
                </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">Duration (minutes)</label>
                  <input 
                    type="number"
                    min={1}
                    className="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text font-mono" 
                    value={form.duration_minutes} 
                    onChange={e => setForm({...form, duration_minutes: Number(e.target.value) || 60})} 
                    required
                  />
                </div>

                <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 
                    type="number"
                    className="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text font-mono" 
                    value={form.max_score} 
                    onChange={e => setForm({...form, max_score: Number(e.target.value) || 100})} 
                    required
                  />
                </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-xl 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</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="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text"
                  rows={2}
                  value={form.description}
                  onChange={e => setForm({ ...form, description: e.target.value })}
                  placeholder="Short description"
                />
              </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="w-full px-4 py-3 bg-muted/50 border border-border rounded-xl text-sm focus:ring-2 focus:ring-primary/20 outline-none transition-all text-text"
                  rows={3}
                  value={form.instructions}
                  onChange={e => setForm({ ...form, instructions: e.target.value })}
                  placeholder="Rules, resources allowed, deliverables..."
                />
              </div>

              {editing && (
                <div className="space-y-2 p-4 bg-muted/20 border border-border rounded-xl">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Reference Materials (Attachments)</label>
                  <AttachmentList
                    parent_kind="test"
                    parent_id={editing.id}
                    emptyMessage="No files uploaded yet."
                  />
                  <AttachmentUploader
                    parent_kind="test"
                    parent_id={editing.id}
                  />
                </div>
              )}

              {formError && (
                <p className="text-rose-500 text-xs font-bold">{formError}</p>
              )}

              <button type="submit" className="w-full py-4 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-[0.65rem] rounded-xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 cursor-pointer">
                <CheckCircle2 size={18} />
                {editing ? 'Save Changes' : 'Create Test'}
              </button>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Submissions Drawer */}
      {openTest && createPortal(
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[140] flex items-stretch justify-end" onClick={() => setOpenTest(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-6 sm:px-8 py-6 border-b border-border flex justify-between items-center shrink-0">
              <div className="min-w-0 flex-1 pr-2">
                <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Submissions</p>
                <h2 className="text-xl font-black text-text truncate">{openTest.title}</h2>
                <p className="text-xs text-text-muted mt-1 uppercase font-bold truncate">
                  {openTest.subject_name} · Max {openTest.max_score}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setOpenTest(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="flex-1 overflow-y-auto p-4 sm:p-8 space-y-3 custom-scrollbar">
              {loading ? (
                <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>
              ) : getSubmissions().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>
              ) : (
                getSubmissions().map(s => (
                  <div key={s.id} className="border border-border rounded-2xl p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4 hover:bg-muted/30 transition-colors">
                    <div className="flex items-center gap-3 min-w-0 w-full sm:w-auto">
                      <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 shrink-0">
                        {s.student_name?.[0] ?? '?'}
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="font-bold text-text truncate">{s.student_name}</div>
                        <div className="text-[0.65rem] text-text-muted">
                          Submitted {s.submitted_at ? new Date(s.submitted_at).toLocaleString() : 'N/A'}
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center justify-between sm:justify-end gap-4 w-full sm:w-auto shrink-0 border-t sm:border-t-0 pt-2 sm:pt-0 border-border">
                      <div className="text-right shrink-0">
                        {s.status === 'graded' || s.status === 'returned' ? (
                          <div>
                            <div className="font-black text-emerald-600">{s.grade} / {openTest.max_score}</div>
                            <div className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{s.status}</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 cursor-pointer"
                      >
                        <Award size={14} /> <span>Grade</span>
                      </button>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Grade modal */}
      {grading && openTest && 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 Test</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 Score: {openTest.max_score} · Submitted {grading.submitted_at ? new Date(grading.submitted_at).toLocaleString() : 'N/A'}
            </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/35 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={openTest.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="Feedback comments..."
                />
              </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={loading}
                  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(openTest.id, grading.id);
                        alert('Test marked script returned to student');
                        setGrading(null);
                        await get(openTest.id);
                      } 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>
  );
}
