import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Search, Plus, FileText, Clock } from "lucide-react";
import { useInstitutionalExamSessions } from "@/hooks/queries";
import { api } from "@/lib/api-client";
import { Link } from "react-router-dom";

interface CustomExam {
  id: number;
  title: string;
  status: string;
  total_time_min: number;
  sections: { id: number; title: string; skill: string }[];
  teacher_id: number | null;
  template_id: number | null;
  description: string;
}

const statusColors: Record<string, "default" | "secondary" | "outline" | "destructive"> = {
  published: "default",
  draft: "secondary",
  archived: "outline",
};

export default function ExamsListPage() {
  const [search, setSearch] = useState("");
  const [tab, setTab] = useState<"custom" | "sessions">("custom");

  const customQ = useQuery({
    queryKey: ["custom-exams", search],
    queryFn: () => api.get<{ items: CustomExam[]; total: number }>(`/exam/custom/list?search=${encodeURIComponent(search)}&per_page=50`),
  });

  const sessionsQ = useInstitutionalExamSessions();
  const sessionItems = sessionsQ.data?.items ?? [];
  const sessions: Record<string, string>[] = Array.isArray(sessionItems)
    ? (sessionItems as unknown as Record<string, string>[])
    : [];

  const customExams = customQ.data?.items ?? [];
  const q = search.toLowerCase();
  const filteredSessions = sessions.filter((s) =>
    s.name?.toLowerCase().includes(q) || s.course_name?.toLowerCase().includes(q),
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Exams List</h1>
          <p className="text-muted-foreground">Browse and manage all exams and exam sessions.</p>
        </div>
        <Link to="/admin/exam/create">
          <Button><Plus className="h-4 w-4 mr-2" /> Create Exam</Button>
        </Link>
      </div>

      <div className="flex gap-2">
        <Button variant={tab === "custom" ? "default" : "outline"} size="sm" onClick={() => setTab("custom")}>
          <FileText className="h-4 w-4 mr-1" /> Custom Exams ({customExams.length})
        </Button>
        <Button variant={tab === "sessions" ? "default" : "outline"} size="sm" onClick={() => setTab("sessions")}>
          <Clock className="h-4 w-4 mr-1" /> Exam Sessions ({filteredSessions.length})
        </Button>
      </div>

      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input placeholder="Search exams..." className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      {tab === "custom" && (
        customQ.isLoading ? (
          <div className="flex items-center justify-center min-h-[200px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>
        ) : (
          <Card className="border-0 shadow-sm">
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">#</TableHead>
                    <TableHead>Title</TableHead>
                    <TableHead>Modules</TableHead>
                    <TableHead>Duration</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {customExams.length === 0 && (
                    <TableRow><TableCell colSpan={5} className="text-center text-muted-foreground py-8">No custom exams found. Submit one from the Generation page.</TableCell></TableRow>
                  )}
                  {customExams.map((exam, i) => (
                    <TableRow key={exam.id}>
                      <TableCell className="text-muted-foreground">{exam.id}</TableCell>
                      <TableCell className="font-medium">{exam.title}</TableCell>
                      <TableCell>
                        <div className="flex gap-1 flex-wrap">
                          {exam.sections.length > 0
                            ? exam.sections.map((s) => (
                                <Badge key={s.id} variant="outline" className="text-xs capitalize">{s.skill || s.title}</Badge>
                              ))
                            : <span className="text-muted-foreground text-xs">—</span>}
                        </div>
                      </TableCell>
                      <TableCell>{exam.total_time_min ? `${exam.total_time_min} min` : "—"}</TableCell>
                      <TableCell>
                        <Badge variant={statusColors[exam.status] ?? "outline"} className="capitalize">{exam.status}</Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )
      )}

      {tab === "sessions" && (
        sessionsQ.isLoading ? (
          <div className="flex items-center justify-center min-h-[200px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>
        ) : (
          <Card className="border-0 shadow-sm">
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>#</TableHead>
                    <TableHead>Name</TableHead>
                    <TableHead>Course</TableHead>
                    <TableHead>Batch</TableHead>
                    <TableHead>Start</TableHead>
                    <TableHead>End</TableHead>
                    <TableHead>State</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredSessions.length === 0 && (
                    <TableRow><TableCell colSpan={7} className="text-center text-muted-foreground py-8">No exam sessions found.</TableCell></TableRow>
                  )}
                  {filteredSessions.map((s, i) => (
                    <TableRow key={s.id}>
                      <TableCell>{i + 1}</TableCell>
                      <TableCell className="font-medium">{s.name}</TableCell>
                      <TableCell>{s.course_name || "—"}</TableCell>
                      <TableCell>{s.batch_name || "—"}</TableCell>
                      <TableCell>{s.start_date || "—"}</TableCell>
                      <TableCell>{s.end_date || "—"}</TableCell>
                      <TableCell>
                        <Badge variant={s.state === "done" ? "default" : s.state === "schedule" ? "secondary" : "outline"} className="capitalize">{s.state}</Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )
      )}
    </div>
  );
}
