"use client";

import { useCallback } from "react";
import { Copy, Building2, Clock } from "lucide-react";
import type { FinanceViewModel } from "@/lib/farmer-dashboard";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { ProgressRing } from "@/components/ui/progress-ring";
import { EligibilityGauge } from "./EligibilityGauge";
import { tf } from "@/lib/i18n/dashboard-labels";
import type { AppLocale } from "@/lib/i18n/config";
import { cn } from "@/lib/utils";

export interface CaseHeaderMetricsProps {
  finance: FinanceViewModel;
  gisVerified?: boolean;
  locale: AppLocale;
  className?: string;
}

function formatDueDate(iso: string, locale: AppLocale): string {
  try {
    return new Intl.DateTimeFormat(locale === "uz" ? "uz-UZ" : locale === "ru" ? "ru-RU" : "en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(iso));
  } catch {
    return iso;
  }
}

export function CaseHeaderMetrics({
  finance,
  gisVerified = false,
  locale,
  className,
}: CaseHeaderMetricsProps) {
  const copyCaseId = useCallback(() => {
    if (finance.caseId) {
      void navigator.clipboard.writeText(finance.caseId);
    }
  }, [finance.caseId]);

  const sla = finance.sla;
  const institution = finance.routedInstitution;

  return (
    <div
      className={cn(
        "grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4",
        className,
      )}
    >
      <Card padding="md" className="flex flex-col gap-3">
        <span className="font-inter text-xs font-medium uppercase tracking-wide text-muted">
          {tf("caseId", locale)}
        </span>
        <div className="flex items-center gap-2">
          <span className="font-onest text-lg font-bold text-ink truncate">
            {finance.caseId}
          </span>
          <button
            type="button"
            onClick={copyCaseId}
            className="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted transition-colors hover:bg-surface-elevated hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-green-deep focus-visible:ring-offset-2"
            aria-label={tf("copyCaseId", locale)}
          >
            <Copy className="size-4" aria-hidden="true" />
          </button>
        </div>
        {gisVerified ? (
          <Badge variant="success">{tf("gisVerified", locale)}</Badge>
        ) : null}
      </Card>

      <EligibilityGauge
        score={finance.eligibilityScore ?? 0}
        label={finance.eligibilityLabel}
        locale={locale}
      />

      <Card padding="md" className="flex flex-col gap-2">
        <div className="flex items-start gap-2">
          <Building2 className="size-4 shrink-0 text-brand-green mt-0.5" aria-hidden="true" />
          <div className="min-w-0">
            <span className="font-inter text-xs font-medium uppercase tracking-wide text-muted">
              {tf("routed", locale)}
            </span>
            <p className="font-onest text-xl font-bold text-ink mt-1">
              {institution?.name ?? "—"}
            </p>
            {institution?.priority ? (
              <p className="font-inter text-sm text-success-green mt-0.5">
                {tf("priority", locale)}: {institution.priority}
              </p>
            ) : null}
          </div>
        </div>
        {institution?.isBestMatch ? (
          <Badge variant="brand" className="self-start">
            {tf("bestMatch", locale)}
          </Badge>
        ) : null}
      </Card>

      {sla ? (
        <Card padding="md" className="flex flex-col gap-2">
          <div className="flex items-center gap-4">
            <ProgressRing
              value={sla.remainingHours}
              max={sla.totalHours}
              label={tf("sla", locale)}
              variant="circle"
              size="sm"
              showFraction={false}
              unit={tf("hrsUnit", locale)}
            />
            <div className="min-w-0 flex-1">
              <p className="font-inter text-sm text-ink">
                {tf("slaRemaining", locale, {
                  remaining: sla.remainingHours,
                  total: sla.totalHours,
                })}
              </p>
              <p className="font-inter text-xs text-muted mt-2 flex items-center gap-1">
                <Clock className="size-3 shrink-0" aria-hidden="true" />
                {tf("due", locale)}: {formatDueDate(sla.dueAt, locale)}
              </p>
            </div>
          </div>
        </Card>
      ) : (
        <Card padding="md" className="flex flex-col justify-center">
          <span className="font-inter text-xs font-medium uppercase tracking-wide text-muted">
            {tf("sla", locale)}
          </span>
          <p className="font-onest text-xl font-bold text-ink mt-1">—</p>
        </Card>
      )}
    </div>
  );
}
