import { useQuery } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { Lock } from "lucide-react";

import { AppShell } from "@/components/app-shell";
import { CourseCard } from "@/components/course-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { LEVELS, bandClass, levelAction, levelBlurb } from "@/lib/assessment";
import { getMyResults } from "@/lib/assessment.functions";

export const Route = createFileRoute("/_authenticated/results")({
  head: () => ({
    meta: [
      { title: "Your Assessment Results | UZIA Academy" },
      {
        name: "description",
        content: "Your UZIA Academy Pillar breakdown, score bands and personalised UZIA course plan.",
      },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: Results,
});

function Results() {
  const fetchResults = useServerFn(getMyResults);
  const { data, isLoading } = useQuery({ queryKey: ["my-results"], queryFn: () => fetchResults() });

  if (isLoading) {
    return (
      <AppShell title="Your results">
        <Skeleton className="h-64 w-full" />
      </AppShell>
    );
  }

  if (!data?.result) {
    return (
      <AppShell title="Your results" description="No assessment on file yet.">
        <Button asChild className="rounded-full bg-gold text-gold-foreground hover:bg-gold/90">
          <Link to="/assess">Take the assessment</Link>
        </Button>
      </AppShell>
    );
  }

  const { result, breakdown, pathway, recommended, isPro, lockedDomains } = data;
  const mandatory = pathway.filter((p) => p.mandatory);
  const growth = pathway.filter((p) => !p.mandatory);

  return (
    <AppShell
      title={`You scored ${result.overall_score}/100 — ${result.level}`}
      description={levelBlurb(result.level)}
    >
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="rounded-3xl border border-border bg-card p-6">
          <h2 className="text-lg">Pillar breakdown</h2>
          <ul className="mt-5 space-y-4">
            {breakdown.map((b) => (
              <li key={b.slug}>
                <div className="flex flex-wrap items-center justify-between gap-2 text-sm">
                  <span className="font-medium">
                    <span className="font-display text-xs font-bold text-primary">{b.code}</span>{" "}
                    {b.name}
                  </span>
                  <Badge className={bandClass(b.score)}>
                    {b.score} · {b.level}
                  </Badge>
                </div>
                <Progress value={b.score} className="mt-2" />
              </li>
            ))}
          </ul>
        </div>

        <div className="space-y-6">
          <div className="rounded-3xl border border-border bg-surface p-6">
            <h2 className="text-lg">Priority gaps to close first</h2>
            {mandatory.length === 0 ? (
              <p className="mt-3 text-sm text-muted-foreground">
                No pillar scored below 60 — nothing is critical. Use the growth options below to
                push further.
              </p>
            ) : (
              <ul className="mt-4 space-y-3">
                {mandatory.map((p) => (
                  <li key={p.domain.slug} className="rounded-2xl border border-border bg-card p-4">
                    <p className="text-sm font-semibold">
                      {p.domain.code} · {p.domain.name}{" "}
                      <span className="text-muted-foreground">· {p.domain.score}/100</span>
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">{p.domain.description}</p>
                    <p className="mt-2 text-xs font-semibold text-primary">
                      {levelAction(p.domain.level)}
                    </p>
                  </li>
                ))}
              </ul>
            )}
          </div>

          <div className="rounded-3xl border border-border bg-card p-6">
            <h2 className="text-lg">Growth opportunities (60–74)</h2>
            {growth.length === 0 ? (
              <p className="mt-3 text-sm text-muted-foreground">
                None right now — focus on the priority gaps.
              </p>
            ) : (
              <ul className="mt-4 flex flex-wrap gap-2">
                {growth.map((p) => (
                  <Badge key={p.domain.slug} variant="outline">
                    {p.domain.code} {p.domain.name} · {p.domain.score}
                  </Badge>
                ))}
              </ul>
            )}
          </div>

          <div className="rounded-3xl border border-border bg-surface p-6">
            <h2 className="text-lg">How bands work</h2>
            <ul className="mt-4 space-y-2 text-sm text-muted-foreground">
              {LEVELS.map((l) => (
                <li key={l.level}>
                  <span className="font-semibold text-foreground">
                    {l.min}–{l.max} {l.level}
                  </span>{" "}
                  → {l.action}
                </li>
              ))}
            </ul>
          </div>

          <Button asChild variant="outline" className="w-full rounded-full">
            <Link to="/assess">Retake the assessment</Link>
          </Button>
        </div>
      </div>

      {!isPro ? (
        <div className="mt-10 rounded-3xl border border-border bg-surface p-6">
          <div className="flex items-center gap-2">
            <Lock className="size-4 text-primary" />
            <h2 className="text-lg">Your full action plan is a Pro feature</h2>
          </div>
          <p className="mt-3 max-w-2xl text-sm text-muted-foreground">
            You are seeing the single most urgent pillar.{" "}
            {lockedDomains > 0
              ? `${lockedDomains} more pillar${lockedDomains === 1 ? "" : "s"} need attention.`
              : ""}{" "}
            Pro unlocks the sequenced action plan for every pillar, unlimited assessments and the
            full 50-course catalogue.
          </p>
          <Button asChild className="mt-5 rounded-full">
            <Link to="/pricing">See Pro plans</Link>
          </Button>
        </div>
      ) : null}

      <div className="mt-12">
        <h2 className="text-lg">Your personalised course plan</h2>
        <div className="mt-5 grid gap-6 md:grid-cols-2 xl:grid-cols-3">
          {recommended.map((course) => (
            <CourseCard key={course.slug} course={course} isPro={isPro} />
          ))}
        </div>
      </div>
    </AppShell>
  );
}
