import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Globe, BookOpen, GraduationCap, Languages, Plus, Lock, Sparkles } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { useInternationalTemplates, useCustomTemplates } from "@/hooks/queries/useExamTemplates";
import type { ExamTemplate } from "@/types";

function formatTime(min: number): string {
  const h = Math.floor(min / 60);
  const m = min % 60;
  if (h <= 0) return `${m}m`;
  return m ? `${h}h ${m}m` : `${h}h`;
}

function templateStats(t: ExamTemplate): { skillCount: number; totalQuestions: number; timeMin: number } {
  const skills = t.structure?.skills ?? [];
  const skillCount = t.skill_count ?? skills.length;
  const totalQuestions =
    t.total_questions ??
    skills.reduce(
      (acc, s) => acc + (s.parts ?? []).reduce((a, p) => a + (p.question_count ?? 0), 0),
      0,
    );
  const timeMin = t.total_time_min ?? skills.reduce((acc, s) => acc + (s.total_time_min ?? 0), 0);
  return { skillCount, totalQuestions, timeMin };
}

const iconForName = (name: string) => {
  const n = name.toLowerCase();
  if (n.includes("general")) return GraduationCap;
  if (n.includes("academic")) return BookOpen;
  if (n.includes("toefl")) return Languages;
  return Globe;
};

export default function ExamTemplateSelection() {
  const navigate = useNavigate();
  const intlQ = useInternationalTemplates();
  const customQ = useCustomTemplates();

  const international = useMemo(() => {
    const raw = intlQ.data;
    if (Array.isArray(raw)) return raw;
    if (raw && typeof raw === "object" && "data" in raw && Array.isArray((raw as { data: unknown }).data)) {
      return (raw as { data: ExamTemplate[] }).data;
    }
    if (raw && typeof raw === "object" && "items" in raw && Array.isArray((raw as { items: unknown }).items)) {
      return (raw as { items: ExamTemplate[] }).items;
    }
    return [] as ExamTemplate[];
  }, [intlQ.data]);

  const myTemplates = useMemo(() => {
    const raw = customQ.data;
    if (Array.isArray(raw)) return raw;
    if (raw && typeof raw === "object" && "data" in raw && Array.isArray((raw as { data: unknown }).data)) {
      return (raw as { data: ExamTemplate[] }).data;
    }
    if (raw && typeof raw === "object" && "items" in raw && Array.isArray((raw as { items: unknown }).items)) {
      return (raw as { items: ExamTemplate[] }).items;
    }
    return [] as ExamTemplate[];
  }, [customQ.data]);

  return (
    <div className="space-y-10 p-6 max-w-6xl mx-auto">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Create exam</h1>
        <p className="text-muted-foreground mt-1">Choose an international template or build a custom exam.</p>
      </div>

      <section className="space-y-4">
        <div className="flex items-center gap-2">
          <Sparkles className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-medium">International templates</h2>
        </div>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {intlQ.isLoading
            ? Array.from({ length: 3 }).map((_, i) => (
                <Card key={i} className="overflow-hidden">
                  <CardHeader className="space-y-2">
                    <Skeleton className="h-6 w-3/4" />
                    <Skeleton className="h-4 w-full" />
                  </CardHeader>
                  <CardContent>
                    <Skeleton className="h-20 w-full" />
                  </CardContent>
                </Card>
              ))
            : international.map((t) => {
                const Icon = iconForName(t.name);
                const { skillCount, totalQuestions, timeMin } = templateStats(t);
                const locked = !t.editable;
                return (
                  <Card
                    key={t.id}
                    className="cursor-pointer transition-shadow hover:shadow-md border-muted"
                    role="button"
                    tabIndex={0}
                    onClick={() => navigate("/admin/exam/ielts/create")}
                    onKeyDown={(e) => {
                      if (e.key === "Enter" || e.key === " ") {
                        e.preventDefault();
                        navigate("/admin/exam/ielts/create");
                      }
                    }}
                  >
                    <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
                      <div className="flex items-center gap-3">
                        <div className="rounded-lg bg-primary/10 p-2 text-primary">
                          <Icon className="h-6 w-6" />
                        </div>
                        <div>
                          <CardTitle className="text-base leading-tight">{t.name}</CardTitle>
                          <CardDescription className="mt-1">Structured international assessment</CardDescription>
                        </div>
                      </div>
                      {locked ? (
                        <Badge variant="secondary" className="shrink-0 gap-1">
                          <Lock className="h-3 w-3" />
                          Locked
                        </Badge>
                      ) : null}
                    </CardHeader>
                    <CardContent className="text-sm text-muted-foreground space-y-1">
                      <p>
                        <span className="font-medium text-foreground">{skillCount}</span> skills
                      </p>
                      <p>
                        <span className="font-medium text-foreground">{totalQuestions}</span> questions ·{" "}
                        <span className="font-medium text-foreground">{formatTime(timeMin)}</span> total
                      </p>
                    </CardContent>
                  </Card>
                );
              })}
        </div>
        {!intlQ.isLoading && international.length === 0 ? (
          <p className="text-sm text-muted-foreground">No international templates are available yet.</p>
        ) : null}
      </section>

      <section className="space-y-4">
        <h2 className="text-lg font-medium">Custom exam</h2>
        <Card
          className="cursor-pointer border-dashed border-2 transition-colors hover:border-primary/60 hover:bg-muted/30"
          role="button"
          tabIndex={0}
          onClick={() => navigate("/admin/exam/custom/create")}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              navigate("/admin/exam/custom/create");
            }
          }}
        >
          <CardHeader className="flex flex-row items-center gap-4">
            <div className="rounded-full bg-primary/15 p-3 text-primary">
              <Plus className="h-8 w-8" />
            </div>
            <div>
              <CardTitle>Create custom exam</CardTitle>
              <CardDescription>Define sections, scoring, and your own question mix.</CardDescription>
            </div>
          </CardHeader>
        </Card>
      </section>

      <Separator />

      <section className="space-y-4">
        <h2 className="text-lg font-medium">My templates</h2>
        {customQ.isLoading ? (
          <div className="grid gap-3 sm:grid-cols-2">
            <Skeleton className="h-24 w-full" />
            <Skeleton className="h-24 w-full" />
          </div>
        ) : myTemplates.length === 0 ? (
          <p className="text-sm text-muted-foreground">You have not saved any custom templates yet.</p>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2">
            {myTemplates.map((t) => {
              const { skillCount, totalQuestions, timeMin } = templateStats(t);
              return (
                <Card key={t.id} className="border-muted">
                  <CardHeader className="pb-2">
                    <CardTitle className="text-base">{t.name}</CardTitle>
                    <CardDescription>
                      {skillCount} skills · {totalQuestions} questions · {formatTime(timeMin)}
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="flex justify-end pt-0">
                    <Button variant="outline" size="sm" type="button" onClick={() => navigate("/admin/exam/custom/create")}>
                      Use as starting point
                    </Button>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}
      </section>
    </div>
  );
}
