import { useState } from "react";
import { useParams, Link } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { useAssignments } from "@/hooks/queries";
import { ArrowLeft } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function TeacherAssignmentDetail() {
  const { id } = useParams();
  const { data: assignmentsData, isLoading } = useAssignments();
  const assignments = assignmentsData?.items ?? [];
  const submissions: { id: string; assignmentId: string; studentId: string; studentName: string; submittedAt: string; status: string; grade?: number; feedback?: string; file?: string }[] = [];
  const [gradeOpen, setGradeOpen] = useState(false);
  const [selectedStudent, setSelectedStudent] = useState<string>("");
  const { toast } = useToast();

  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  const assignment = assignments.find(a => String(a.id) === id);
  const subs = submissions.filter(s => s.assignmentId === id);
  const maxGrade = 100;

  if (!assignment) return <div className="p-8 text-center text-muted-foreground">Assignment not found.</div>;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" asChild><Link to="/teacher/assignments"><ArrowLeft className="h-4 w-4" /></Link></Button>
        <div>
          <h1 className="text-2xl font-bold">{assignment.title}</h1>
          <p className="text-muted-foreground">{assignment.entity_name} · Due: {assignment.end_date}</p>
        </div>
      </div>

      <Card>
        <CardHeader><CardTitle className="text-lg">Submissions ({subs.length})</CardTitle></CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Student</TableHead>
                <TableHead>Submitted</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Grade</TableHead>
                <TableHead></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {subs.map(s => (
                <TableRow key={s.id}>
                  <TableCell className="font-medium">{s.studentName}</TableCell>
                  <TableCell className="text-sm">{s.submittedAt}</TableCell>
                  <TableCell><Badge variant={s.status === "graded" ? "default" : "secondary"} className="capitalize">{s.status}</Badge></TableCell>
                  <TableCell>{s.grade ?? "—"}</TableCell>
                  <TableCell>
                    {s.status === "pending" && (
                      <Button size="sm" onClick={() => { setSelectedStudent(s.studentName); setGradeOpen(true); }}>Grade</Button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={gradeOpen} onOpenChange={setGradeOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Grade Submission — {selectedStudent}</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2"><Label>Grade (out of {maxGrade})</Label><Input type="number" placeholder="0" /></div>
            <div className="space-y-2"><Label>Feedback</Label><Textarea placeholder="Write feedback..." rows={4} /></div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setGradeOpen(false)}>Cancel</Button>
            <Button onClick={() => { setGradeOpen(false); toast({ title: "Grade Saved", description: `${selectedStudent}'s submission has been graded.` }); }}>Save Grade</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
