"use client";

import { IconPlus, IconTrendingUp, IconExternalLink, IconChevronRight } from "@tabler/icons-react";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { useSitesQuery, useAddSiteMutation, type SiteWithLatest } from "@/data/sites/hooks";
import { useRouter } from "@/i18n/navigation";
import { formatMetricValue, formatBytes } from "@/lib/scoring";

export default function DashboardPage() {
  const t = useTranslations("Dashboard");
  const tCommon = useTranslations("Common");
  const { data: sites, isLoading } = useSitesQuery();

  const completed = sites?.filter((s) => s.latestTest?.performanceScore != null) ?? [];
  const avgScore =
    completed.length > 0
      ? Math.round(
          completed.reduce((sum, s) => sum + (s.latestTest?.performanceScore ?? 0), 0) /
            completed.length,
        )
      : null;
  const avgLcp =
    completed.length > 0
      ? completed.reduce((sum, s) => sum + (s.latestTest?.lcp ?? 0), 0) / completed.length
      : null;

  return (
    <div className="mx-auto max-w-[1400px] space-y-12 px-4 lg:px-6">
      {/* Hero */}
      <section className="relative flex min-h-[280px] items-center overflow-hidden rounded-xl bg-surface-container-low p-10">
        <div className="pointer-events-none absolute inset-0 bg-gradient-to-br from-primary/10 via-transparent to-transparent" />
        <div className="absolute -right-20 -bottom-20 h-80 w-80 rounded-full bg-primary/5 blur-[100px]" />
        <div className="relative z-10 grid w-full grid-cols-1 gap-12 lg:grid-cols-2">
          <div>
            <p className="mb-4 text-xs font-bold tracking-[0.2em] text-primary uppercase">
              {t("hero.eyebrow")}
            </p>
            <h1 className="mb-6 font-[family-name:var(--font-manrope)] text-4xl leading-tight font-extrabold text-foreground lg:text-5xl">
              {sites && sites.length > 0 ? t("hero.headlineHealthy") : t("hero.headlineEmpty")}
            </h1>
            {sites && sites.length > 0 && (
              <span className="inline-flex items-center gap-2 rounded-full bg-perf-good/10 px-4 py-2 text-sm font-semibold text-perf-good">
                <IconTrendingUp className="size-4" />
                {t("hero.monitoredCount", { count: sites.length })}
              </span>
            )}
          </div>
          <div className="flex items-center justify-around gap-16 lg:justify-end">
            <div className="text-center">
              <p className="mb-1 text-sm tracking-wider text-muted-foreground uppercase">
                {t("hero.avgScore")}
              </p>
              <span className="font-[family-name:var(--font-manrope)] text-7xl font-extrabold text-primary">
                {avgScore ?? "--"}
              </span>
            </div>
            <div className="text-center">
              <p className="mb-1 text-sm tracking-wider text-muted-foreground uppercase">
                {t("hero.avgLcp")}
              </p>
              <span className="font-[family-name:var(--font-manrope)] text-7xl font-extrabold text-perf-good">
                {avgLcp != null ? (
                  <>
                    {(avgLcp / 1000).toFixed(1)}
                    <small className="text-2xl font-normal opacity-60">s</small>
                  </>
                ) : (
                  "--"
                )}
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* Monitored Properties */}
      <section className="space-y-6">
        <div className="flex items-end justify-between">
          <div>
            <h2 className="font-[family-name:var(--font-manrope)] text-2xl font-bold">
              {t("monitoredProperties.title")}
            </h2>
            <p className="text-sm text-muted-foreground">
              {t("monitoredProperties.subtitle", { count: sites?.length ?? 0 })}
            </p>
          </div>
          <AddSiteDialog />
        </div>

        {isLoading ? (
          <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
        ) : !sites || sites.length === 0 ? (
          <div className="rounded-xl bg-surface-container-low py-20 text-center">
            <p className="mb-4 text-muted-foreground">{t("monitoredProperties.empty")}</p>
            <AddSiteDialog />
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-6">
            {sites.map((site) => (
              <SiteRow key={site.id} site={site} />
            ))}
          </div>
        )}
      </section>

      {/* Bottom Stats */}
      {completed.length > 0 && (
        <div className="grid grid-cols-1 gap-8 md:grid-cols-3">
          <div className="rounded-xl border-t-2 border-primary/20 bg-surface-container-low p-6">
            <h4 className="mb-4 text-xs tracking-widest text-muted-foreground uppercase">
              {t("stats.totalRequests")}
            </h4>
            <div className="flex items-baseline gap-2">
              <span className="font-[family-name:var(--font-manrope)] text-3xl font-bold">
                {completed.reduce((s, site) => s + (site.latestTest?.requests ?? 0), 0)}
              </span>
            </div>
          </div>
          <div className="rounded-xl border-t-2 border-perf-good/20 bg-surface-container-low p-6">
            <h4 className="mb-4 text-xs tracking-widest text-muted-foreground uppercase">
              {t("stats.avgFullyLoaded")}
            </h4>
            <div className="flex items-baseline gap-2">
              <span className="font-[family-name:var(--font-manrope)] text-3xl font-bold">
                {formatMetricValue(
                  "lcp",
                  completed.reduce((s, site) => s + (site.latestTest?.fullyLoaded ?? 0), 0) /
                    completed.length,
                )}
              </span>
            </div>
          </div>
          <div className="rounded-xl border-t-2 border-perf-warning/20 bg-surface-container-low p-6">
            <h4 className="mb-4 text-xs tracking-widest text-muted-foreground uppercase">
              {t("stats.avgTransferSize")}
            </h4>
            <div className="flex items-baseline gap-2">
              <span className="font-[family-name:var(--font-manrope)] text-3xl font-bold">
                {formatBytes(
                  completed.reduce((s, site) => s + (site.latestTest?.transferSize ?? 0), 0) /
                    completed.length,
                )}
              </span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ── Site Row (Stitch "Monitored Properties" style) ── */
function SiteRow({ site }: { site: SiteWithLatest }) {
  const router = useRouter();
  const tr = useTranslations("Dashboard.siteRow");
  const locale = useLocale();
  const dateLocale = locale === "fr" ? "fr-FR" : locale === "es" ? "es-ES" : "en-US";
  const t = site.latestTest;
  const score = t?.performanceScore;

  const scoreColor =
    score != null
      ? score >= 90
        ? "text-perf-good"
        : score >= 70
          ? "text-foreground"
          : score >= 50
            ? "text-perf-warning"
            : "text-perf-danger"
      : "text-muted-foreground";

  const borderColor =
    score != null
      ? score >= 70
        ? "border-l-perf-good"
        : score >= 50
          ? "border-l-perf-warning"
          : "border-l-perf-danger"
      : "border-l-muted";

  return (
    <div
      onClick={() => router.push(`/dashboard/sites/${site.id}`)}
      className={`group rounded-xl border-l-2 bg-surface-container-low p-6 transition-all duration-300 hover:bg-surface-container ${borderColor} cursor-pointer`}
    >
      <div className="flex flex-wrap items-center gap-8">
        {/* Site info */}
        <div className="min-w-[200px] flex-1">
          <h3 className="flex items-center gap-2 font-[family-name:var(--font-manrope)] text-lg font-bold text-foreground">
            {site.hostname}
            <IconExternalLink className="size-4 text-primary opacity-0 transition-opacity group-hover:opacity-100" />
          </h3>
          <p className="text-xs text-muted-foreground">
            {t
              ? tr("lastTest", { date: new Date(t.createdAt).toLocaleDateString(dateLocale) })
              : tr("noTest")}
          </p>
        </div>

        {/* CWV mini metrics */}
        {t && (
          <div className="flex items-center gap-12">
            <MiniMetric label="LCP" value={t.lcp} metric="lcp" />
            <MiniMetric label="TBT" value={t.tbt} metric="tbt" />
            <MiniMetric label="CLS" value={t.cls} metric="cls" />
          </div>
        )}

        {/* Sparkline */}
        {site.sparkline.length > 0 && (
          <div className="flex h-12 w-32 items-end gap-[2px]">
            {site.sparkline.map((point, i) => {
              const s = point.performanceScore ?? 0;
              const h = Math.max(10, s);
              const color =
                s >= 70 ? "bg-perf-good/30" : s >= 50 ? "bg-perf-warning/30" : "bg-perf-danger/30";
              return (
                <div
                  key={i}
                  className={`flex-1 ${color} rounded-t-sm`}
                  style={{ height: `${h}%` }}
                />
              );
            })}
          </div>
        )}

        {/* Score */}
        <div className="flex items-center gap-4 border-l border-[#45464d]/15 pl-8">
          <div className="text-right">
            <p className="text-[10px] tracking-widest text-muted-foreground uppercase">
              {tr("perfScore")}
            </p>
            <p
              className={`font-[family-name:var(--font-manrope)] text-3xl font-extrabold ${scoreColor}`}
            >
              {score ?? "--"}
            </p>
          </div>
          <IconChevronRight className="size-5 text-muted-foreground transition-transform group-hover:translate-x-1" />
        </div>
      </div>
    </div>
  );
}

/* ── Mini Metric (inside site row) ── */
function MiniMetric({
  label,
  value,
  metric,
}: {
  label: string;
  value: number | null;
  metric: string;
}) {
  const color =
    value == null
      ? "text-muted-foreground"
      : metric === "cls"
        ? value <= 0.1
          ? "text-perf-good"
          : value <= 0.25
            ? "text-perf-warning"
            : "text-perf-danger"
        : metric === "lcp"
          ? value <= 2500
            ? "text-perf-good"
            : value <= 4000
              ? "text-perf-warning"
              : "text-perf-danger"
          : value <= 200
            ? "text-perf-good"
            : value <= 600
              ? "text-perf-warning"
              : "text-perf-danger";

  return (
    <div className="text-center">
      <p className="mb-1 text-[10px] tracking-widest text-muted-foreground uppercase">{label}</p>
      <p className={`text-sm font-bold ${color}`}>
        {value != null ? formatMetricValue(metric, value) : "--"}
      </p>
      {value != null && (
        <div className="mx-auto mt-1 h-1 w-12 overflow-hidden rounded-full bg-current/20">
          <div
            className={`h-full ${color.replace("text-", "bg-")} rounded-full`}
            style={{
              width: `${Math.min(100, metric === "cls" ? (1 - value / 0.3) * 100 : metric === "lcp" ? (1 - value / 5000) * 100 : (1 - value / 800) * 100)}%`,
            }}
          />
        </div>
      )}
    </div>
  );
}

/* ── Add Site Dialog ── */
function AddSiteDialog() {
  const t = useTranslations("Dashboard.addSite");
  const [open, setOpen] = useState(false);
  const [url, setUrl] = useState("");
  const mutation = useAddSiteMutation();
  const router = useRouter();

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className="gap-2 bg-primary text-xs font-bold tracking-wider text-primary-foreground uppercase">
          <IconPlus className="size-4" />
          {t("trigger")}
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t("title")}</DialogTitle>
          <DialogDescription>{t("description")}</DialogDescription>
        </DialogHeader>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            const trimmed = url.trim();
            if (!trimmed) return;
            mutation.mutate(trimmed, {
              onSuccess: (site) => {
                setOpen(false);
                setUrl("");
                router.push(`/dashboard/sites/${site.id}`);
              },
              onError: (err) => toast.error(err.message),
            });
          }}
        >
          <Input
            placeholder={t("placeholder")}
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            required
            autoFocus
          />
          <DialogFooter className="mt-4">
            <Button type="submit" disabled={mutation.isPending}>
              {mutation.isPending ? t("submitting") : t("submit")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
