import { useQuery } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { ArrowRight, Flag, Sparkles } from "lucide-react";
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, XAxis, YAxis } from "recharts";

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 { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { Skeleton } from "@/components/ui/skeleton";
import { bandClass, levelAction, levelBlurb } from "@/lib/assessment";
import { getMyResults } from "@/lib/assessment.functions";

export const Route = createFileRoute("/_authenticated/dashboard")({
  head: () => ({
    meta: [
      { title: "Your Dashboard | UZIA Academy" },
      {
        name: "description",
        content: "Your UZIA growth score, pillar breakdown and sequenced UZIA course pathway.",
      },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: Dashboard,
});

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

  if (isLoading) {
    return (
      <AppShell title="Your dashboard">
        <div className="grid gap-4">
          <Skeleton className="h-40 w-full" />
          <Skeleton className="h-64 w-full" />
        </div>
      </AppShell>
    );
  }

  if (!data?.result) {
    return (
      <AppShell
        title="Your dashboard"
        description="You haven't completed the UZIA growth assessment yet."
      >
        <div className="overflow-hidden rounded-3xl bg-sunset p-10 text-center text-primary-foreground shadow-lift">
          <Sparkles className="mx-auto size-8 text-gold" />
          <h2 className="mt-4 font-display text-2xl">Start with your growth score</h2>
          <p className="mx-auto mt-3 max-w-lg text-sm opacity-90">
            36 questions across the 12 UZIA Academy Pillars, about ten minutes. You'll get a 0–100 score per
            domain and a sequenced UZIA course pathway.
          </p>
          <Button
            asChild
            size="lg"
            className="mt-7 rounded-full bg-gold text-gold-foreground hover:bg-gold/90"
          >
            <Link to="/assess">Take the assessment</Link>
          </Button>
        </div>
      </AppShell>
    );
  }

  const { result, breakdown, pathway } = data;
  const chartData = breakdown.map((b) => ({ name: `${b.code} ${b.name}`, score: b.score }));

  return (
    <AppShell
      title="Your dashboard"
      description={`Last assessed ${new Date(result.created_at).toLocaleDateString()}`}
    >
      <div className="grid gap-6 lg:grid-cols-[320px_1fr]">
        <div className="relative overflow-hidden rounded-3xl bg-sunset p-8 text-primary-foreground shadow-lift">
          <div className="motif-chevron absolute inset-0 opacity-20" aria-hidden />
          <div className="relative">
            <p className="text-xs font-semibold uppercase tracking-[0.22em] text-gold">
              Growth score
            </p>
            <p className="mt-4 font-display text-6xl font-extrabold">{result.overall_score}</p>
            <p className="mt-1 text-sm opacity-80">out of 100</p>
            <p className="mt-6 inline-flex rounded-full bg-gold px-3 py-1 text-sm font-semibold text-gold-foreground">
              {result.level}
            </p>
            <p className="mt-4 text-sm opacity-90">{levelBlurb(result.level)}</p>
            <Button
              asChild
              variant="outline"
              className="mt-7 w-full rounded-full border-white/40 bg-transparent text-primary-foreground hover:bg-white/10"
            >
              <Link to="/assess">Retake assessment</Link>
            </Button>
          </div>
        </div>

        <div className="rounded-3xl border border-border bg-card p-6">
          <h2 className="text-lg">Scores by UZIA Academy Pillar</h2>
          <ChartContainer
            config={{ score: { label: "Score", color: "var(--color-primary)" } }}
            className="mt-4 h-[420px] w-full"
          >
            <ResponsiveContainer>
              <BarChart data={chartData} layout="vertical" margin={{ left: 8, right: 16 }}>
                <CartesianGrid horizontal={false} strokeOpacity={0.2} />
                <XAxis type="number" domain={[0, 100]} tickLine={false} axisLine={false} />
                <YAxis
                  type="category"
                  dataKey="name"
                  width={180}
                  tickLine={false}
                  axisLine={false}
                  tick={{ fontSize: 11 }}
                />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Bar dataKey="score" fill="var(--color-score)" radius={5} />
              </BarChart>
            </ResponsiveContainer>
          </ChartContainer>
        </div>
      </div>

      <div className="mt-12">
        <div className="flex flex-wrap items-end justify-between gap-3">
          <h2 className="text-lg">Your growth pathway</h2>
          <Link to="/results" className="text-sm font-semibold text-primary hover:underline">
            See full results <ArrowRight className="inline size-3.5" />
          </Link>
        </div>

        {pathway.length === 0 ? (
          <p className="mt-4 rounded-2xl border border-border bg-surface p-6 text-sm text-muted-foreground">
            Every domain scored 75 or above — you're on the Executive MSME pathway. Explore mastery
            programmes in the catalogue.
          </p>
        ) : (
          <div className="mt-5 space-y-8">
            {pathway.slice(0, 4).map((step, i) => (
              <div key={step.domain.slug}>
                <div className="flex flex-wrap items-center gap-3">
                  <span className="grid size-8 place-items-center rounded-xl bg-ember font-display text-sm font-bold text-primary-foreground">
                    {i + 1}
                  </span>
                  <p className="font-display text-base font-bold">
                    {step.domain.code} · {step.domain.name}
                  </p>
                  <Badge className={bandClass(step.domain.score)}>
                    {step.domain.score}/100 · {step.domain.level}
                  </Badge>
                  {step.mandatory ? (
                    <Badge variant="outline" className="border-destructive/50 text-destructive">
                      <Flag className="mr-1 size-3" /> Priority
                    </Badge>
                  ) : (
                    <Badge variant="outline">Growth option</Badge>
                  )}
                </div>
                <p className="mt-2 text-sm text-muted-foreground">
                  Recommended action: {levelAction(step.domain.level)}
                </p>
                <div className="mt-4 grid gap-6 md:grid-cols-2 xl:grid-cols-3">
                  {step.courses.map((course) => (
                    <CourseCard key={course.slug} course={course} isPro={data.isPro} />
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </AppShell>
  );
}
