import React from 'react';
import { motion } from 'motion/react';
import { 
  Users, FileText, CheckCircle2, Clock, AlertCircle, 
  Search, Filter, ArrowRight, MessageSquare, Award, Download, Trophy
} from 'lucide-react';
import { type Submission, type User } from '../types';
import { cn } from '../lib/utils';

interface TeacherDashboardProps {
  user: User;
  onLogout: () => void;
}

export function TeacherDashboard({ user, onLogout }: TeacherDashboardProps) {
  const [submissions, setSubmissions] = React.useState<Submission[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [filter, setFilter] = React.useState<'all' | 'pending' | 'reviewed'>('all');
  const [search, setSearch] = React.useState('');
  const [selectedSubmission, setSelectedSubmission] = React.useState<Submission | null>(null);
  const [vivaScore, setVivaScore] = React.useState<number>(0);
  const [teacherVivaMarks, setTeacherVivaMarks] = React.useState<number>(0);
  const [docMarks, setDocMarks] = React.useState({
    objective: 0,
    concepts: 0,
    explanation: 0,
    learningOutcome: 0
  });
  const [codeMarks, setCodeMarks] = React.useState({
    logic: 0,
    output: 0,
    concepts: 0
  });
  const [teacherRemarks, setTeacherRemarks] = React.useState<string>('');
  const [isUpdating, setIsUpdating] = React.useState(false);
  const [showSettings, setShowSettings] = React.useState(false);
  const [showReport, setShowReport] = React.useState(false);
  const [schoolName, setSchoolName] = React.useState(() => localStorage.getItem('rs_school_name') || '');
  const [principalName, setPrincipalName] = React.useState(() => localStorage.getItem('rs_principal_name') || '');

  const fetchSubmissions = async () => {
    try {
      const res = await fetch('/api/submissions');
      const data = await res.json();
      // Filter by teacher's assigned grade if applicable
      const filtered = user.assignedGrade 
        ? data.filter((s: Submission) => s.grade === user.assignedGrade)
        : data;
      setSubmissions(filtered);
    } catch (error) {
      console.error('Failed to fetch submissions:', error);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchSubmissions();
  }, []);

  const handleUpdateScore = async (submissionId: string) => {
    setIsUpdating(true);
    const docTotal = docMarks.objective + docMarks.concepts + docMarks.explanation + docMarks.learningOutcome;
    const codeTotal = codeMarks.logic + codeMarks.output + codeMarks.concepts;
    const vivaTotal = vivaScore + teacherVivaMarks;
    const totalScore = docTotal + codeTotal + vivaTotal;

    try {
      const res = await fetch(`/api/submissions/${submissionId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          marks: {
            documentation: { ...docMarks, total: docTotal },
            code: { ...codeMarks, total: codeTotal },
            viva: { aiScore: vivaScore, teacherScore: teacherVivaMarks, total: vivaTotal },
            total: totalScore
          },
          documentationMarks: docTotal,
          vivaScore: vivaScore,
          teacherVivaMarks: teacherVivaMarks,
          teacherRemarks,
          totalScore,
          status: 'reviewed'
        })
      });
      if (res.ok) {
        await fetchSubmissions();
        setSelectedSubmission(null);
      }
    } catch (error) {
      console.error('Failed to update score:', error);
    } finally {
      setIsUpdating(false);
    }
  };

  const filteredSubmissions = submissions.filter(s => {
    const matchesFilter = filter === 'all' || s.status === filter;
    const matchesSearch = s.studentName.toLowerCase().includes(search.toLowerCase()) || 
                         s.rollNumber.toLowerCase().includes(search.toLowerCase());
    return matchesFilter && matchesSearch;
  });

  return (
    <div className="space-y-8">
      <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-white">Teacher Dashboard 👩‍🏫</h2>
          <p className="text-slate-400 mt-1">Reviewing submissions for {user.assignedGrade || 'All Classes'}</p>
        </div>
        <div className="flex items-center gap-4">
          <button 
            onClick={() => setShowReport(true)}
            className="bg-orange-500/10 text-orange-500 px-4 py-2 rounded-xl font-bold border border-orange-500/20 hover:bg-orange-500 hover:text-white transition-all flex items-center gap-2"
          >
            <Award size={18} /> Class Report
          </button>
          <button 
            onClick={() => setShowSettings(true)}
            className="bg-[#0b8c9f]/10 text-[#0b8c9f] px-4 py-2 rounded-xl font-bold border border-[#0b8c9f]/20 hover:bg-[#0b8c9f] hover:text-white transition-all flex items-center gap-2"
          >
            <FileText size={18} /> School Settings
          </button>
          <div className="bg-dark-card px-4 py-2 rounded-xl border border-dark-border flex items-center gap-3">
            <Users size={20} className="text-[#0b8c9f]" />
            <span className="font-bold text-white">{submissions.length} Students</span>
          </div>
          <button 
            onClick={onLogout}
            className="bg-red-500/10 text-red-500 px-4 py-2 rounded-xl font-bold border border-red-500/20 hover:bg-red-500 hover:text-white transition-all"
          >
            Logout
          </button>
        </div>
      </div>

      {showReport && (
        <div className="fixed inset-0 bg-dark-bg/90 backdrop-blur-xl z-[100] flex items-center justify-center p-6 overflow-y-auto">
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="bg-dark-card rounded-3xl p-10 border border-dark-border max-w-4xl w-full shadow-2xl my-auto"
          >
            <div className="flex items-center justify-between mb-8">
              <div>
                <h3 className="text-3xl font-black text-white">Class Performance Report 📊</h3>
                <p className="text-slate-400">Comprehensive analysis for {user.assignedGrade || 'All Classes'}</p>
              </div>
              <button onClick={() => setShowReport(false)} className="p-2 hover:bg-slate-800 rounded-xl text-slate-500 transition-colors">
                <X size={24} />
              </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-10">
              <div className="bg-dark-bg p-6 rounded-2xl border border-dark-border">
                <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-2">Avg LEI</div>
                <div className="text-3xl font-black text-[#0b8c9f]">
                  {submissions.length > 0 
                    ? Math.round(submissions.reduce((acc, s) => acc + (s.lei || 0), 0) / submissions.length) 
                    : 0}
                </div>
              </div>
              <div className="bg-dark-bg p-6 rounded-2xl border border-dark-border">
                <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-2">Total Submissions</div>
                <div className="text-3xl font-black text-white">{submissions.length}</div>
              </div>
              <div className="bg-dark-bg p-6 rounded-2xl border border-dark-border">
                <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-2">Reviewed</div>
                <div className="text-3xl font-black text-green-500">
                  {submissions.filter(s => s.status === 'reviewed').length}
                </div>
              </div>
              <div className="bg-dark-bg p-6 rounded-2xl border border-dark-border">
                <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-2">Avg Time</div>
                <div className="text-3xl font-black text-orange-500">
                  {submissions.length > 0 
                    ? Math.round(submissions.reduce((acc, s) => acc + (s.timeSpent || 0), 0) / submissions.length) 
                    : 0}m
                </div>
              </div>
            </div>

            <div className="space-y-6">
              <h4 className="text-lg font-bold text-white flex items-center gap-2">
                <Trophy size={20} className="text-yellow-500" /> Top Performers (by LEI)
              </h4>
              <div className="bg-dark-bg rounded-2xl border border-dark-border overflow-hidden">
                <table className="w-full text-left text-sm">
                  <thead className="bg-slate-800/50">
                    <tr>
                      <th className="px-6 py-4 font-bold text-slate-400">Student</th>
                      <th className="px-6 py-4 font-bold text-slate-400">Roll No</th>
                      <th className="px-6 py-4 font-bold text-slate-400">Level</th>
                      <th className="px-6 py-4 font-bold text-slate-400 text-right">LEI Score</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-dark-border">
                    {[...submissions]
                      .sort((a, b) => (b.lei || 0) - (a.lei || 0))
                      .slice(0, 5)
                      .map((s, i) => (
                        <tr key={s.id} className="hover:bg-slate-800/30 transition-colors">
                          <td className="px-6 py-4 text-white font-medium">{s.studentName}</td>
                          <td className="px-6 py-4 text-slate-400">{s.rollNumber}</td>
                          <td className="px-6 py-4 text-slate-400">Level {s.level}</td>
                          <td className="px-6 py-4 text-right font-black text-[#0b8c9f]">{s.lei}</td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </div>

            <div className="mt-10 pt-8 border-t border-dark-border flex justify-between items-center">
              <div className="flex items-center gap-4">
                <div className="bg-white p-1 rounded-lg">
                  <img src="https://raw.githubusercontent.com/RS-Learning-Lab/assets/main/logo.png" alt="Logo" className="h-6" />
                </div>
                <div className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">
                  RS Learning Lab Official Report
                </div>
              </div>
              <button 
                onClick={() => window.print()}
                className="flex items-center gap-2 text-sm font-bold text-[#0b8c9f] hover:underline"
              >
                <Download size={16} /> Print Report
              </button>
            </div>
          </motion.div>
        </div>
      )}

      {showSettings && (
        <div className="fixed inset-0 bg-dark-bg/80 backdrop-blur-md z-[100] flex items-center justify-center p-6">
          <motion.div 
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-dark-card rounded-3xl p-8 border border-dark-border max-w-md w-full shadow-2xl"
          >
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-2xl font-bold text-white">School Settings</h3>
              <button onClick={() => setShowSettings(false)} className="text-slate-500 hover:text-white">
                <X size={24} />
              </button>
            </div>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1">School Name</label>
                <input 
                  type="text"
                  value={schoolName}
                  onChange={(e) => setSchoolName(e.target.value)}
                  placeholder="Enter school name"
                  className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1">Principal Name</label>
                <input 
                  type="text"
                  value={principalName}
                  onChange={(e) => setPrincipalName(e.target.value)}
                  placeholder="Enter principal name"
                  className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none"
                />
              </div>
              <button 
                onClick={() => {
                  // In a real app, we'd save this to the backend
                  localStorage.setItem('rs_school_name', schoolName);
                  localStorage.setItem('rs_principal_name', principalName);
                  setShowSettings(false);
                }}
                className="w-full bg-[#0b8c9f] text-white py-4 rounded-xl font-bold hover:bg-[#097a8a] transition-all shadow-lg shadow-[#0b8c9f]/20"
              >
                Save Settings
              </button>
            </div>
          </motion.div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Submissions List */}
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-dark-card rounded-3xl border border-dark-border overflow-hidden">
            <div className="p-6 border-b border-dark-border flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
              <div className="relative w-full sm:w-64">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" size={18} />
                <input 
                  type="text"
                  placeholder="Search students..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 rounded-xl bg-dark-bg border border-dark-border text-white text-sm focus:ring-2 focus:ring-[#0b8c9f] outline-none"
                />
              </div>
              <div className="flex items-center gap-2">
                <Filter size={18} className="text-slate-500" />
                <select 
                  value={filter}
                  onChange={(e) => setFilter(e.target.value as any)}
                  className="bg-dark-bg border border-dark-border text-white text-sm rounded-xl px-3 py-2 outline-none focus:ring-2 focus:ring-[#0b8c9f]"
                >
                  <option value="all">All Status</option>
                  <option value="pending">Pending</option>
                  <option value="reviewed">Reviewed</option>
                </select>
              </div>
            </div>

            <div className="divide-y divide-dark-border">
              {loading ? (
                <div className="p-12 text-center text-slate-500">Loading submissions...</div>
              ) : filteredSubmissions.length === 0 ? (
                <div className="p-12 text-center text-slate-500">No submissions found.</div>
              ) : (
                filteredSubmissions.map((s) => (
                  <button 
                    key={s.id}
                    onClick={() => {
                      setSelectedSubmission(s);
                      setDocMarks({
                        objective: s.marks?.documentation?.objective || 0,
                        concepts: s.marks?.documentation?.concepts || 0,
                        explanation: s.marks?.documentation?.explanation || 0,
                        learningOutcome: s.marks?.documentation?.learningOutcome || 0
                      });
                      setCodeMarks({
                        logic: s.marks?.code?.logic || 0,
                        output: s.marks?.code?.output || 0,
                        concepts: s.marks?.code?.concepts || 0
                      });
                      setVivaScore(s.vivaScore || 0);
                      setTeacherVivaMarks(s.teacherVivaMarks || 0);
                      setTeacherRemarks(s.teacherRemarks || '');
                    }}
                    className={cn(
                      "w-full p-6 flex items-center justify-between hover:bg-slate-800/50 transition-all text-left group",
                      selectedSubmission?.id === s.id && "bg-slate-800/80"
                    )}
                  >
                    <div className="flex items-center gap-4">
                      <div className="w-12 h-12 bg-slate-800 rounded-xl flex items-center justify-center text-white font-bold">
                        {s.studentName.charAt(0)}
                      </div>
                      <div>
                        <h4 className="font-bold text-white group-hover:text-[#0b8c9f] transition-colors">{s.studentName}</h4>
                        <div className="flex items-center gap-3 text-xs text-slate-500 mt-1">
                          <span>Roll: {s.rollNumber}</span>
                          <span>•</span>
                          <span>{s.grade}</span>
                          <span>•</span>
                          <span className="text-[#0b8c9f] font-bold">Lvl {s.level}</span>
                          <span>•</span>
                          <span className="text-orange-500">{s.language}</span>
                        </div>
                      </div>
                    </div>
                      <div className="flex items-center gap-6">
                        <div className="text-right hidden sm:block">
                          <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Total Score</div>
                          <div className="text-lg font-black text-white">{s.marks?.total || 0} <span className="text-[10px] text-slate-500">/ 50</span></div>
                          <div className="text-[10px] font-bold text-[#0b8c9f] uppercase">LEI: {s.lei || 0}</div>
                        </div>
                        <div className="text-right hidden sm:block">
                          <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Effort</div>
                          <div className="text-lg font-black text-white">{s.timeSpent}m / {s.attempts}a</div>
                        </div>
                        <div className={cn(
                        "px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest",
                        s.status === 'reviewed' ? "bg-green-500/10 text-green-500" : "bg-yellow-500/10 text-yellow-500"
                      )}>
                        {s.status}
                      </div>
                      <ArrowRight size={20} className="text-slate-700 group-hover:text-white transition-all" />
                    </div>
                  </button>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Evaluation Panel */}
        <div className="space-y-6">
          {selectedSubmission ? (
            <motion.div 
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              className="bg-dark-card rounded-3xl border border-dark-border p-8 sticky top-28"
            >
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold text-white">Evaluation</h3>
                <button onClick={() => setSelectedSubmission(null)} className="text-slate-500 hover:text-white">
                  <X size={20} />
                </button>
              </div>

              <div className="space-y-6">
                <div className="p-4 bg-slate-800/50 rounded-2xl border border-dark-border">
                  <div className="flex justify-between items-center mb-2">
                    <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Performance Metrics</div>
                    <div className="text-sm font-black text-[#0b8c9f]">LEI: {selectedSubmission.lei}</div>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <div className="p-2 bg-dark-bg rounded-lg text-center">
                      <div className="text-[10px] text-slate-500 uppercase">Time</div>
                      <div className="text-sm font-bold text-white">{selectedSubmission.timeSpent}m</div>
                    </div>
                    <div className="p-2 bg-dark-bg rounded-lg text-center">
                      <div className="text-[10px] text-slate-500 uppercase">Attempts</div>
                      <div className="text-sm font-bold text-white">{selectedSubmission.attempts}</div>
                    </div>
                    <div className="p-2 bg-dark-bg rounded-lg text-center">
                      <div className="text-[10px] text-slate-500 uppercase">Hints</div>
                      <div className="text-sm font-bold text-white">{selectedSubmission.hintsUsed}</div>
                    </div>
                  </div>
                </div>

                <div className="p-4 bg-slate-800/50 rounded-2xl border border-dark-border">
                  <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-2">Project Details</div>
                  <div className="text-sm font-bold text-white mb-1">{selectedSubmission.track === 'project' ? 'Final Project' : 'Track Challenge'}</div>
                  <div className="text-xs text-[#0b8c9f] font-mono">{selectedSubmission.language}</div>
                </div>

                <div className="p-4 bg-[#0b8c9f]/5 rounded-2xl border border-[#0b8c9f]/20">
                  <div className="text-xs font-bold text-[#0b8c9f] uppercase tracking-widest mb-2">Project Documentation</div>
                  <div className="text-xs text-slate-300 leading-relaxed whitespace-pre-wrap max-h-40 overflow-y-auto custom-scrollbar">
                    {selectedSubmission.docText}
                  </div>
                </div>

                <div className="p-4 bg-[#0b8c9f]/5 rounded-2xl border border-[#0b8c9f]/20">
                  <div className="text-xs font-bold text-[#0b8c9f] uppercase tracking-widest mb-2">AI Feedback</div>
                  <p className="text-xs text-slate-300 leading-relaxed italic">"{selectedSubmission.aiFeedback}"</p>
                </div>

                {selectedSubmission.vivaSummary && (
                  <div className="p-4 bg-yellow-500/5 rounded-2xl border border-yellow-500/20">
                    <div className="text-xs font-bold text-yellow-500 uppercase tracking-widest mb-4">AI Viva Practice Summary</div>
                    <div className="space-y-4">
                      <div>
                        <div className="text-[10px] font-bold text-slate-500 uppercase mb-1">Overall Rating</div>
                        <p className="text-xs text-white font-bold">{selectedSubmission.vivaSummary.finalQualitative}</p>
                      </div>
                      <div>
                        <div className="text-[10px] font-bold text-slate-500 uppercase mb-1">Strengths</div>
                        <ul className="space-y-1">
                          {selectedSubmission.vivaSummary.strengths.map((s, i) => (
                            <li key={i} className="text-[10px] text-slate-300 flex items-center gap-2">
                              <div className="w-1 h-1 bg-green-500 rounded-full" /> {s}
                            </li>
                          ))}
                        </ul>
                      </div>
                      <div>
                        <div className="text-[10px] font-bold text-slate-500 uppercase mb-1">Areas to Improve</div>
                        <ul className="space-y-1">
                          {selectedSubmission.vivaSummary.improvements.map((s, i) => (
                            <li key={i} className="text-[10px] text-slate-300 flex items-center gap-2">
                              <div className="w-1 h-1 bg-orange-500 rounded-full" /> {s}
                            </li>
                          ))}
                        </ul>
                      </div>
                    </div>
                  </div>
                )}

                {selectedSubmission.plagiarismReport && (
                  <div className={cn(
                    "p-4 rounded-2xl border",
                    selectedSubmission.plagiarismReport.status === 'Safe' ? "bg-green-500/5 border-green-500/20" :
                    selectedSubmission.plagiarismReport.status === 'Needs Review' ? "bg-yellow-500/5 border-yellow-500/20" :
                    "bg-red-500/5 border-red-500/20"
                  )}>
                    <div className="flex items-center justify-between mb-4">
                      <div className={cn(
                        "text-xs font-bold uppercase tracking-widest",
                        selectedSubmission.plagiarismReport.status === 'Safe' ? "text-green-500" :
                        selectedSubmission.plagiarismReport.status === 'Needs Review' ? "text-yellow-500" :
                        "text-red-500"
                      )}>
                        Anti-Copy Report: {selectedSubmission.plagiarismReport.status}
                      </div>
                      <div className="text-xl font-black text-white">
                        {selectedSubmission.plagiarismReport.score}%
                      </div>
                    </div>
                    <p className="text-xs text-slate-300 leading-relaxed mb-4 italic">
                      "{selectedSubmission.plagiarismReport.explanation}"
                    </p>
                    
                    {selectedSubmission.plagiarismReport.status !== 'Safe' && (
                      <button 
                        onClick={async () => {
                          try {
                            await fetch(`/api/submissions/${selectedSubmission.id}`, {
                              method: 'PATCH',
                              headers: { 'Content-Type': 'application/json' },
                              body: JSON.stringify({ vivaRequested: true })
                            });
                            alert('Viva explanation requested from student.');
                          } catch (err) {
                            console.error("Failed to request viva:", err);
                          }
                        }}
                        className="w-full mb-4 py-2 bg-yellow-500/10 hover:bg-yellow-500/20 text-yellow-500 rounded-xl text-[10px] font-bold border border-yellow-500/20 transition-all flex items-center justify-center gap-2"
                      >
                        <MessageSquare size={14} /> Request Viva Explanation
                      </button>
                    )}

                    {selectedSubmission.plagiarismReport.similarSubmissions.length > 0 && (
                      <div className="space-y-2">
                        <div className="text-[10px] font-bold text-slate-500 uppercase">Similar Submissions</div>
                        {selectedSubmission.plagiarismReport.similarSubmissions.map((s, i) => (
                          <div key={i} className="p-2 bg-black/20 rounded-lg flex items-center justify-between">
                            <div>
                              <div className="text-[10px] font-bold text-white">{s.studentName} ({s.rollNumber})</div>
                              <div className="text-[8px] text-slate-500">{s.reason}</div>
                            </div>
                            <div className="text-[10px] font-bold text-slate-400">{s.similarityScore}%</div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {selectedSubmission.code && (
                  <div className="p-4 bg-slate-950 rounded-2xl border border-dark-border">
                    <div className="flex items-center justify-between mb-2">
                      <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Submitted Code</div>
                      <button 
                        onClick={() => {
                          const blob = new Blob([selectedSubmission.code || ''], { type: 'text/javascript' });
                          const url = URL.createObjectURL(blob);
                          const a = document.createElement('a');
                          a.href = url;
                          a.download = `solution_${selectedSubmission.studentName.replace(/\s+/g, '_')}.js`;
                          a.click();
                        }}
                        className="text-[10px] text-[#0b8c9f] hover:underline flex items-center gap-1"
                      >
                        <Download size={12} /> Download Code
                      </button>
                    </div>
                    <pre className="text-[10px] text-slate-400 font-mono bg-black/30 p-3 rounded-lg overflow-x-auto max-h-40 custom-scrollbar">
                      {selectedSubmission.code}
                    </pre>
                  </div>
                )}

                <div className="space-y-4">
                  <div className="p-4 bg-slate-800/50 rounded-2xl border border-dark-border">
                    <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-4">Documentation (Max 20)</div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Objective (5)</label>
                        <input 
                          type="number" max={5} value={docMarks.objective}
                          onChange={(e) => setDocMarks({...docMarks, objective: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Concepts (5)</label>
                        <input 
                          type="number" max={5} value={docMarks.concepts}
                          onChange={(e) => setDocMarks({...docMarks, concepts: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Explanation (5)</label>
                        <input 
                          type="number" max={5} value={docMarks.explanation}
                          onChange={(e) => setDocMarks({...docMarks, explanation: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Outcome (5)</label>
                        <input 
                          type="number" max={5} value={docMarks.learningOutcome}
                          onChange={(e) => setDocMarks({...docMarks, learningOutcome: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="p-4 bg-slate-800/50 rounded-2xl border border-dark-border">
                    <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-4">Code Implementation (Max 15)</div>
                    <div className="grid grid-cols-3 gap-2">
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Logic (5)</label>
                        <input 
                          type="number" max={5} value={codeMarks.logic}
                          onChange={(e) => setCodeMarks({...codeMarks, logic: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Output (5)</label>
                        <input 
                          type="number" max={5} value={codeMarks.output}
                          onChange={(e) => setCodeMarks({...codeMarks, output: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Concept (5)</label>
                        <input 
                          type="number" max={5} value={codeMarks.concepts}
                          onChange={(e) => setCodeMarks({...codeMarks, concepts: Number(e.target.value)})}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="p-4 bg-slate-800/50 rounded-2xl border border-dark-border">
                    <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-4">Viva (Max 15)</div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">AI Viva (5)</label>
                        <input 
                          type="number" max={5} value={vivaScore}
                          onChange={(e) => setVivaScore(Number(e.target.value))}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                      <div>
                        <label className="block text-[10px] text-slate-500 uppercase mb-1">Teacher (10)</label>
                        <input 
                          type="number" max={10} value={teacherVivaMarks}
                          onChange={(e) => setTeacherVivaMarks(Number(e.target.value))}
                          className="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-white text-sm"
                        />
                      </div>
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-bold text-slate-500 uppercase tracking-widest mb-2">Teacher Remarks</label>
                    <textarea 
                      value={teacherRemarks}
                      onChange={(e) => setTeacherRemarks(e.target.value)}
                      placeholder="Enter qualitative feedback..."
                      className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white outline-none focus:ring-2 focus:ring-[#0b8c9f] min-h-[80px]"
                    />
                  </div>
                </div>

                <div className="pt-4">
                  <button 
                    disabled={isUpdating}
                    onClick={() => handleUpdateScore(selectedSubmission.id)}
                    className="w-full bg-[#0b8c9f] text-white py-4 rounded-xl font-bold hover:bg-[#097a8a] transition-all flex items-center justify-center gap-2 shadow-lg shadow-[#0b8c9f]/20"
                  >
                    {isUpdating ? 'Updating...' : 'Save Evaluation'} <Award size={20} />
                  </button>
                </div>
              </div>
            </motion.div>
          ) : (
            <div className="bg-dark-card rounded-3xl border border-dark-border p-12 text-center flex flex-col items-center justify-center h-full min-h-[400px]">
              <div className="w-20 h-20 bg-slate-800 rounded-full flex items-center justify-center text-slate-600 mb-6">
                <MessageSquare size={40} />
              </div>
              <h3 className="text-lg font-bold text-white mb-2">Select a Submission</h3>
              <p className="text-sm text-slate-500 max-w-[200px]">Click on a student to start the evaluation process.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function X({ size }: { size: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"></line>
      <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
  );
}
