"use client";

import Link from "next/link";
import { AlertTriangle, FileCheck2, FileClock, FileX2, FileQuestion } from "lucide-react";
import { useDashboardStats } from "@/features/dashboard/overview-data";
import { useI18n, useT } from "@/i18n";
import { formatNumber } from "@/lib/format";
import { cn } from "@/lib/cn";
import { useAnimatedNumber } from "./shared";
import type { VehicleDocumentBreakdown, VehicleDocumentState } from "@/types/dashboard";

/** Document states in the order a dispatcher thinks about them, most alarming first. */
const DOC_STATES: { key: VehicleDocumentState; tone: string; icon: typeof FileQuestion }[] = [
  { key: "expired", tone: "bg-destructive", icon: FileX2 },
  { key: "expiring_soon", tone: "bg-warning", icon: FileClock },
  { key: "missing", tone: "bg-muted", icon: FileQuestion },
  { key: "valid", tone: "bg-success", icon: FileCheck2 },
];

function DocumentStatRow({ state, count, totals }: { state: VehicleDocumentState; count: number; totals: number }) {
  const t = useT();
  const { locale } = useI18n();
  const { key, tone, icon: Icon } = DOC_STATES.find((s) => s.key === state) ?? {
    key: state,
    tone: "bg-muted",
    icon: FileQuestion,
  };
  const animated = useAnimatedNumber(count);
  const share = totals > 0 ? Math.min(100, (count / totals) * 100) : 0;

  return (
    <li className="flex items-center gap-2">
      <Icon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
      <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{t(`widgets.fleetDocuments.${key}`)}</span>
      <span className="numeric shrink-0 text-xs font-semibold text-foreground">{formatNumber(animated, locale)}</span>
      <span className="h-2 w-10 shrink-0 overflow-hidden rounded-full bg-muted" dir="ltr">
        <span className={cn("block h-full rounded-full", tone)} style={{ width: `${share}%` }} />
      </span>
    </li>
  );
}

function DocumentGroup({ label, docs }: { label: string; docs: VehicleDocumentBreakdown }) {
  const totals = DOC_STATES.reduce((sum, s) => sum + docs[s.key], 0);

  return (
    <div className="rounded-lg border bg-surface p-3">
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <ul className="mt-2 space-y-1.5">
        {DOC_STATES.map(({ key }) => (
          <DocumentStatRow key={key} state={key} count={docs[key] ?? 0} totals={totals} />
        ))}
      </ul>
    </div>
  );
}

export function FleetDocumentsWidget() {
  const t = useT();
  const { locale } = useI18n();
  const { data } = useDashboardStats();
  const documents = data?.vehicles.documents;

  const expiringSoon =
    (documents?.registration.expiring_soon ?? 0) + (documents?.insurance.expiring_soon ?? 0);
  const expired = (documents?.registration.expired ?? 0) + (documents?.insurance.expired ?? 0);
  const attention = expiringSoon + expired;
  const animatedAttention = useAnimatedNumber(attention);

  return (
    <div>
      <div className="flex items-center justify-between gap-2">
        <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
          {t("widgets.fleetDocuments.title")}
        </p>
        {attention > 0 ? (
          <Link
            href="/vehicles?documents=expiring_soon"
            className={cn(
              "inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-semibold transition-colors hover:underline",
              expired > 0 ? "bg-destructive/10 text-destructive" : "bg-warning-soft text-warning",
            )}
          >
            <AlertTriangle className="h-3 w-3" aria-hidden />
            <span className="numeric">{formatNumber(animatedAttention, locale)}</span>
            {t("widgets.fleetDocuments.attention")}
          </Link>
        ) : null}
      </div>
      <div className="mt-3 flex flex-col gap-3">
        <DocumentGroup label={t("widgets.fleetDocuments.registration")} docs={documents?.registration ?? EMPTY_DOCS} />
        <DocumentGroup label={t("widgets.fleetDocuments.insurance")} docs={documents?.insurance ?? EMPTY_DOCS} />
      </div>
    </div>
  );
}

const EMPTY_DOCS: VehicleDocumentBreakdown = {
  missing: 0,
  expired: 0,
  expiring_soon: 0,
  valid: 0,
};