"use client";

import Link from "next/link";
import type { ComponentType } from "react";
import {
  ArrowRight,
  BadgeCheck,
  ClipboardList,
  FileClock,
  FileX2,
  Timer,
  Truck,
  UserCheck,
} from "lucide-react";
import { useDashboardStats } from "@/features/dashboard/overview-data";
import { useCan } from "@/features/auth/use-can";
import { useI18n, useT } from "@/i18n";
import { formatNumber } from "@/lib/format";
import { cn } from "@/lib/cn";

/**
 * The "what needs you now" panel. Every row is a decision sitting on the data the
 * modules already count: applications waiting for a review, orders nobody has picked
 * up, papers about to (or already) running out, company cars with no plate. A row
 * only appears when there is something to actually do, and each one deep-links to the
 * screen that settles it — the list end of a click-through that never dead-ends.
 */
export function DecisionInboxWidget() {
  const t = useT();
  const { locale } = useI18n();
  const { can } = useCan();
  const { data } = useDashboardStats();

  const pendingApplications =
    (data?.drivers.by_status.pending ?? 0) + (data?.drivers.by_status.documents_required ?? 0);
  const pendingOrders = data?.orders.by_status.pending ?? 0;
  const failedOrders = data?.orders.by_status.delivery_failed ?? 0;
  const expiringPapers =
    (data?.vehicles.documents.registration.expiring_soon ?? 0) +
    (data?.vehicles.documents.insurance.expiring_soon ?? 0);
  const overduePapers =
    (data?.vehicles.documents.registration.expired ?? 0) +
    (data?.vehicles.documents.insurance.expired ?? 0);
  const awaitingCars = data?.vehicles.awaiting_assignment ?? 0;

  const rows = [
    can("drivers.review") && pendingApplications > 0 && {
      href: "/applications",
      label: t("widgets.decisionInbox.pendingApplications"),
      count: pendingApplications,
      tone: "bg-warning-soft text-warning",
      icon: UserCheck,
    },
    can(["orders.assign", "orders.view"]) && pendingOrders > 0 && {
      href: "/orders?status=pending",
      label: t("widgets.decisionInbox.pendingOrders"),
      count: pendingOrders,
      tone: "bg-primary-soft text-primary",
      icon: ClipboardList,
    },
    can(["orders.assign", "orders.view"]) && failedOrders > 0 && {
      href: "/orders?status=delivery_failed",
      label: t("widgets.decisionInbox.failedOrders"),
      count: failedOrders,
      tone: "bg-destructive/10 text-destructive",
      icon: Timer,
    },
    can("vehicles.view") && overduePapers > 0 && {
      href: "/vehicles?documents=expired",
      label: t("widgets.decisionInbox.overduePapers"),
      count: overduePapers,
      tone: "bg-destructive/10 text-destructive",
      icon: FileX2,
    },
    can("vehicles.view") && expiringPapers > 0 && {
      href: "/vehicles?documents=expiring_soon",
      label: t("widgets.decisionInbox.expiringPapers"),
      count: expiringPapers,
      tone: "bg-warning-soft text-warning",
      icon: FileClock,
    },
    can("vehicles.view") && awaitingCars > 0 && {
      href: "/vehicles?awaiting=1",
      label: t("widgets.decisionInbox.awaitingCars"),
      count: awaitingCars,
      tone: "bg-accent-soft text-accent",
      icon: Truck,
    },
  ].filter(Boolean) as {
    href: string;
    label: string;
    count: number;
    tone: string;
    icon: ComponentType<{ className?: string }>;
  }[];

  return (
    <div>
      {rows.length === 0 ? (
        <div className="flex items-center gap-2 rounded-lg border border-success/20 bg-success-soft/40 px-4 py-3 text-sm text-success">
          <BadgeCheck className="h-4 w-4 shrink-0" aria-hidden />
          <span>{t("widgets.decisionInbox.allClear")}</span>
        </div>
      ) : (
        <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
          {rows.map((row) => {
            const Icon = row.icon;
            return (
              <Link
                key={row.href}
                href={row.href}
                className="group flex items-center gap-3 rounded-lg border bg-surface p-3 transition-colors hover:border-primary/30 hover:bg-primary-soft/30"
              >
                <span className={cn("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg", row.tone)} aria-hidden>
                  <Icon className="h-[18px] w-[18px]" />
                </span>
                <span className="min-w-0 flex-1">
                  <span className="numeric block text-lg font-bold leading-tight text-foreground">
                    {formatNumber(row.count, locale)}
                  </span>
                  <span className="block truncate text-xs text-muted-foreground">{row.label}</span>
                </span>
                <ArrowRight
                  className="h-4 w-4 shrink-0 text-muted-foreground transition-transform rtl:rotate-180 group-hover:translate-x-0.5 rtl:group-hover:-translate-x-0.5 group-hover:text-primary"
                  aria-hidden
                />
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}