import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useGapAnalysis, useAutoGenerateCourse } from "@/hooks/queries/useCourseGeneration";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Skeleton } from "@/components/ui/skeleton";
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

export default function GapAnalysis() {
  const [searchParams] = useSearchParams();
  const { user } = useAuth();
  const fromParam = searchParams.get("from");
  const source = fromParam === "placement" ? "placement" : "exam";
  const examId = Number(searchParams.get("examId"));
  const sessionId = Number(searchParams.get("sessionId"));
  const sourceId = source === "exam" ? examId : sessionId;
  const entityStudent = searchParams.get("entity") === "1";

  const enabled = source === "exam" ? Number.isFinite(examId) && examId > 0 : Number.isFinite(sessionId) && sessionId > 0;

  const { data, isLoading, isError } = useGapAnalysis(source, sourceId);
  const generate = useAutoGenerateCourse();

  const chartData = useMemo(() => {
    if (!data?.skill_gaps?.length) return [];
    return [...data.skill_gaps]
      .sort((a, b) => b.gap - a.gap)
      .map((g) => ({ skill: g.skill, gap: g.gap }));
  }, [data]);

  const canGenerate = user?.user_type === "student" && !entityStudent;

  return (
    <div className="mx-auto max-w-5xl space-y-8 p-6">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Skill gap analysis</h1>
          <p className="text-muted-foreground">
            {source === "exam" ? `From exam ${examId || "—"}` : `Placement session ${sessionId || "—"}`}
          </p>
        </div>
        {canGenerate ? (
          <Button
            type="button"
            onClick={() => generate.mutate(sourceId)}
            disabled={!enabled || generate.isPending}
          >
            Generate Course
          </Button>
        ) : null}
      </div>

      {entityStudent ? (
        <Alert>
          <AlertTitle>Entity-managed students</AlertTitle>
          <AlertDescription>
            Gap analysis is view-only for your organization. Contact your coordinator to assign a course.
          </AlertDescription>
        </Alert>
      ) : null}

      {!enabled ? (
        <Alert variant="destructive">
          <AlertTitle>Missing source</AlertTitle>
          <AlertDescription>
            Add <code className="rounded bg-muted px-1">?from=exam&amp;examId=…</code> or{" "}
            <code className="rounded bg-muted px-1">?from=placement&amp;sessionId=…</code> to the URL.
          </AlertDescription>
        </Alert>
      ) : null}

      {isLoading ? (
        <Skeleton className="h-96 w-full" />
      ) : isError || !data ? (
        <p className="text-destructive">Could not load gap analysis.</p>
      ) : (
        <>
          <Card>
            <CardHeader>
              <CardTitle>Skills ranked by gap</CardTitle>
              <CardDescription>Larger bars need more attention</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-72 w-full">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={chartData} layout="vertical" margin={{ left: 16 }}>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                    <XAxis type="number" domain={[0, "dataMax"]} />
                    <YAxis type="category" dataKey="skill" width={100} tickLine={false} axisLine={false} />
                    <Tooltip />
                    <Bar dataKey="gap" fill="hsl(var(--primary))" radius={[0, 4, 4, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Gap table</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Skill</TableHead>
                    <TableHead>Current</TableHead>
                    <TableHead>Target</TableHead>
                    <TableHead>Gap</TableHead>
                    <TableHead>Priority</TableHead>
                    <TableHead>Est. Hours</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {data.skill_gaps.map((g) => (
                    <TableRow key={g.skill}>
                      <TableCell className="font-medium">{g.skill}</TableCell>
                      <TableCell>{g.current_band ?? g.current_level}</TableCell>
                      <TableCell>{g.target_band ?? g.target_level}</TableCell>
                      <TableCell>{g.gap}</TableCell>
                      <TableCell className="capitalize">{g.priority}</TableCell>
                      <TableCell>{g.estimated_hours}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          <div>
            <h2 className="mb-3 text-lg font-semibold">Question-type weaknesses</h2>
            <Accordion type="multiple" className="w-full">
              {Object.entries(data.question_type_weaknesses).map(([skill, rows]) => (
                <AccordionItem key={skill} value={skill}>
                  <AccordionTrigger>{skill}</AccordionTrigger>
                  <AccordionContent>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Type</TableHead>
                          <TableHead>Accuracy</TableHead>
                          <TableHead>Correct</TableHead>
                          <TableHead>Total</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {rows.map((r) => (
                          <TableRow key={r.question_type}>
                            <TableCell>{r.question_type}</TableCell>
                            <TableCell>{Math.round(r.accuracy * 100)}%</TableCell>
                            <TableCell>{r.correct}</TableCell>
                            <TableCell>{r.total}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </AccordionContent>
                </AccordionItem>
              ))}
            </Accordion>
          </div>

          <div>
            <h2 className="mb-3 text-lg font-semibold">Topic weaknesses</h2>
            <div className="space-y-4">
              {Object.entries(data.topic_weaknesses).map(([cat, topics]) => (
                <Card key={cat}>
                  <CardHeader className="py-3">
                    <CardTitle className="text-base">{cat}</CardTitle>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Topic</TableHead>
                          <TableHead>Errors</TableHead>
                          <TableHead>Total</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {topics.map((t) => (
                          <TableRow key={t.topic}>
                            <TableCell>{t.topic}</TableCell>
                            <TableCell>{t.errors}</TableCell>
                            <TableCell>{t.total}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
