"use client";

import {
  CircleCheck,
  CircleX,
  CircleMinus,
  FileText,
  Send,
  ExternalLink,
  TriangleAlert,
} from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate, formatDateTime } from "@/shared/lib/format-date";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/presentation/components/ui/sheet";
import { Button } from "@/presentation/components/ui/button";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import {
  ComplianceScoreBar,
  ComplianceStatusBadge,
  SeverityTag,
  useRuleLabel,
} from "@/presentation/components/compliance/compliance-badges";
import { CATEGORY_ICONS } from "@/presentation/components/compliance/compliance-kpis";
import {
  COMPLIANCE_CATEGORIES,
  COMPLIANCE_DEADLINE_CLASSES,
  COMPLIANCE_SEVERITY_WEIGHT,
} from "@/shared/constants/compliance";
import type { ComplianceVehicleDetail } from "@/domain/entities/compliance";

interface ComplianceVehicleSheetProps {
  vehicleId: number | null;
  /** Bumped by the page after an alert, so the history reloads. */
  refreshKey: number;
  onClose: () => void;
  onAlert: (vehicle: ComplianceVehicleDetail) => void;
}

function Section({ title, children, aside }: { title: string; children: React.ReactNode; aside?: React.ReactNode }) {
  return (
    <section className="space-y-2">
      <div className="flex items-center justify-between">
        <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{title}</h3>
        {aside}
      </div>
      {children}
    </section>
  );
}

function Field({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="rounded-lg bg-muted/40 px-3 py-2">
      <div className="text-[11px] text-muted-foreground">{label}</div>
      <div className="text-sm font-medium">{value ?? <span className="text-red-600">—</span>}</div>
    </div>
  );
}

export function ComplianceVehicleSheet({ vehicleId, refreshKey, onClose, onAlert }: ComplianceVehicleSheetProps) {
  const t = useT();
  const locale = useLocale();
  const ruleLabel = useRuleLabel();
  const { complianceRepository } = useRepositories();

  const { data, loading } = useApiQuery(
    () => complianceRepository.getVehicle(vehicleId as number),
    { enabled: vehicleId !== null, deps: [vehicleId, refreshKey] },
  );
  const vehicle = data && data.vehicle_id === vehicleId ? data : null;

  return (
    <Sheet open={vehicleId !== null} onOpenChange={(open) => !open && onClose()}>
      <SheetContent className="w-full sm:max-w-2xl overflow-y-auto p-0 gap-0">
        {!vehicle || loading ? (
          <div className="space-y-4 p-6">
            <SheetHeader className="p-0">
              <SheetTitle><Skeleton className="h-6 w-40" /></SheetTitle>
              <SheetDescription asChild><div><Skeleton className="h-4 w-64" /></div></SheetDescription>
            </SheetHeader>
            <Skeleton className="h-20 w-full" />
            <Skeleton className="h-64 w-full" />
          </div>
        ) : (
          <>
            <SheetHeader className="sticky top-0 z-10 shrink-0 border-b border-border bg-background/95 px-6 py-5 backdrop-blur">
              <div className="flex items-start justify-between gap-4 pr-6">
                <div className="min-w-0">
                  <SheetTitle className="flex items-center gap-2 font-mono text-xl tracking-wide">
                    {vehicle.numberplate}
                    <ComplianceStatusBadge status={vehicle.status} />
                  </SheetTitle>
                  <SheetDescription>
                    {vehicle.make_model} · {vehicle.company.name}
                    {vehicle.site ? ` · ${vehicle.site.name}` : ""}
                  </SheetDescription>
                  <div className="mt-1 font-mono text-[11px] text-muted-foreground">VIN {vehicle.vin ?? "—"}</div>
                </div>
                <div className="text-right">
                  <div className="font-mono text-3xl font-bold leading-none">{vehicle.score}%</div>
                  <div className="text-[11px] text-muted-foreground">{t.compliance.columns.score}</div>
                </div>
              </div>
              <ComplianceScoreBar score={vehicle.score} wide className="mt-3" />
              <div className="mt-3 flex flex-wrap gap-2">
                <Button size="sm" onClick={() => onAlert(vehicle)} disabled={vehicle.missing.length === 0}>
                  <Send className="mr-1.5 h-3.5 w-3.5" />
                  {t.compliance.actions.alert}
                </Button>
                <Button size="sm" variant="outline" asChild>
                  <a href={vehicle.fleet_url} target="_blank" rel="noreferrer">
                    <ExternalLink className="mr-1.5 h-3.5 w-3.5" />
                    {t.compliance.actions.openFleet}
                  </a>
                </Button>
              </div>
            </SheetHeader>

            <div className="shrink-0 space-y-6 px-6 py-5">
              {vehicle.warnings.length > 0 && (
                <div className="flex gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
                  <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
                  <div>
                    <div className="font-semibold">{t.compliance.sheet.warnings}</div>
                    {vehicle.warnings.map((w) => <div key={w}>{ruleLabel(w)}</div>)}
                  </div>
                </div>
              )}

              <Section title={t.compliance.sheet.checklist}>
                <div className="space-y-3">
                  {COMPLIANCE_CATEGORIES.map((category) => {
                    const checks = vehicle.checks
                      .filter((c) => c.category === category)
                      .sort((a, b) =>
                        Number(a.passed || !a.applicable) - Number(b.passed || !b.applicable) ||
                        COMPLIANCE_SEVERITY_WEIGHT[b.severity] - COMPLIANCE_SEVERITY_WEIGHT[a.severity],
                      );
                    if (checks.length === 0) return null;
                    const applicable = checks.filter((c) => c.applicable);
                    const passed = applicable.filter((c) => c.passed).length;
                    const Icon = CATEGORY_ICONS[category];
                    const score = vehicle.category_scores[category];
                    return (
                      <div key={category} className="rounded-xl border border-border">
                        <div className="flex items-center justify-between gap-2 border-b border-border bg-muted/30 px-3 py-2">
                          <span className="flex items-center gap-2 text-sm font-semibold">
                            <Icon className="h-4 w-4 text-blue-600" />
                            {t.compliance.categories[category]}
                          </span>
                          <span className="flex items-center gap-2 text-xs text-muted-foreground">
                            {t.compliance.sheet.passedCount(passed, applicable.length)}
                            {score !== undefined && <ComplianceScoreBar score={score} />}
                          </span>
                        </div>
                        <ul className="divide-y divide-border">
                          {checks.map((check) => (
                            <li key={check.key} className="flex items-center gap-3 px-3 py-2 text-sm">
                              {!check.applicable ? (
                                <CircleMinus className="h-4 w-4 shrink-0 text-muted-foreground/50" />
                              ) : check.passed ? (
                                <CircleCheck className="h-4 w-4 shrink-0 text-emerald-500" />
                              ) : (
                                <CircleX className="h-4 w-4 shrink-0 text-red-500" />
                              )}
                              <span className={cn("flex-1", !check.applicable && "text-muted-foreground")}>
                                {ruleLabel(check.key)}
                              </span>
                              <span className="text-xs text-muted-foreground text-right">
                                {!check.applicable
                                  ? t.compliance.sheet.notApplicable
                                  : check.value ?? (check.passed ? "" : t.compliance.sheet.missingValue)}
                              </span>
                              {check.applicable && !check.passed && <SeverityTag severity={check.severity} />}
                            </li>
                          ))}
                        </ul>
                      </div>
                    );
                  })}
                </div>
              </Section>

              <Section title={t.compliance.sheet.documents}>
                <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
                  {vehicle.documents.map((doc) => (
                    <div
                      key={doc.type}
                      className={cn(
                        "flex items-start gap-3 rounded-lg border px-3 py-2.5",
                        doc.present
                          ? "border-emerald-200 bg-emerald-50/50"
                          : doc.required
                            ? "border-red-200 bg-red-50/50"
                            : "border-border bg-muted/30",
                      )}
                    >
                      <FileText
                        className={cn(
                          "mt-0.5 h-4 w-4 shrink-0",
                          doc.present ? "text-emerald-600" : doc.required ? "text-red-500" : "text-muted-foreground",
                        )}
                      />
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center justify-between gap-2">
                          <span className="text-sm font-medium">{t.compliance.documents[doc.type]}</span>
                          <span className="text-[10px] font-semibold uppercase text-muted-foreground">
                            {doc.required ? t.compliance.sheet.required : t.compliance.sheet.notRequired}
                          </span>
                        </div>
                        <div className="truncate text-xs text-muted-foreground">
                          {doc.present ? doc.file_name ?? t.compliance.sheet.present : t.compliance.sheet.absent}
                        </div>
                        {doc.expiration_date && (
                          <div className={cn("text-[11px] font-medium", doc.expiration_status && COMPLIANCE_DEADLINE_CLASSES[doc.expiration_status])}>
                            {t.compliance.sheet.expires(formatDate(doc.expiration_date, locale))}
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </Section>

              <Section title={t.compliance.sheet.deadlines}>
                {vehicle.deadlines.length === 0 ? (
                  <p className="text-sm text-muted-foreground">{t.compliance.sheet.noDeadlines}</p>
                ) : (
                  <ol className="relative ml-2 space-y-3 border-l border-border pl-4">
                    {vehicle.deadlines.map((d) => (
                      <li key={`${d.type}-${d.date}`} className="relative">
                        <span
                          className={cn(
                            "absolute -left-[21px] top-1 h-2.5 w-2.5 rounded-full ring-2 ring-background",
                            d.status === "overdue" ? "bg-red-500" : d.status === "due_soon" ? "bg-amber-400" : "bg-slate-300",
                          )}
                        />
                        <div className="flex items-center justify-between gap-2 text-sm">
                          <span className="font-medium">{t.compliance.deadlineTypes[d.type]}</span>
                          <span className={cn("text-xs font-semibold", COMPLIANCE_DEADLINE_CLASSES[d.status])}>
                            {formatDate(d.date, locale)} · {t.compliance.deadlineStatus[d.status]}
                          </span>
                        </div>
                      </li>
                    ))}
                  </ol>
                )}
              </Section>

              <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                <Section title={t.compliance.sheet.financing}>
                  <div className="grid grid-cols-2 gap-2">
                    <Field
                      label={t.compliance.financingFields.mode}
                      value={vehicle.financing.mode ? t.compliance.financingModes[vehicle.financing.mode] : null}
                    />
                    {(vehicle.financing.mode === "lld" || vehicle.financing.mode === "loa") && (
                      <>
                        <Field label={t.compliance.financingFields.lessor} value={vehicle.financing.lessor} />
                        <Field label={t.compliance.financingFields.contractNumber} value={vehicle.financing.contract_number} />
                        <Field
                          label={t.compliance.financingFields.monthlyRent}
                          value={vehicle.financing.monthly_rent ? `${vehicle.financing.monthly_rent} €` : null}
                        />
                        <Field
                          label={t.compliance.financingFields.kmLimit}
                          value={vehicle.financing.km_limit ? `${vehicle.financing.km_limit.toLocaleString(locale)} km` : null}
                        />
                        <Field
                          label={t.compliance.financingFields.duration}
                          value={vehicle.financing.duration_months ? t.compliance.financingFields.months(vehicle.financing.duration_months) : null}
                        />
                        <div className="col-span-2">
                          <Field
                            label={t.compliance.financingFields.period}
                            value={
                              vehicle.financing.start_date && vehicle.financing.end_date
                                ? `${formatDate(vehicle.financing.start_date, locale)} → ${formatDate(vehicle.financing.end_date, locale)}`
                                : null
                            }
                          />
                        </div>
                      </>
                    )}
                  </div>
                </Section>

                <Section title={t.compliance.sheet.driver}>
                  {vehicle.driver.name ? (
                    <div className="grid grid-cols-1 gap-2">
                      <Field label={t.compliance.driverFields.name} value={vehicle.driver.name} />
                      <Field
                        label={t.compliance.driverFields.licence}
                        value={
                          <span
                            className={cn(
                              vehicle.driver.licence_status === "expired" || !vehicle.driver.licence_status
                                ? "text-red-600"
                                : vehicle.driver.licence_status === "expiring_soon"
                                  ? "text-amber-600"
                                  : "text-emerald-600",
                            )}
                          >
                            {t.compliance.licenceStatus[vehicle.driver.licence_status ?? "missing"]}
                            {vehicle.driver.licence_expiry && vehicle.driver.licence_status
                              ? ` · ${formatDate(vehicle.driver.licence_expiry, locale)}`
                              : ""}
                          </span>
                        }
                      />
                    </div>
                  ) : (
                    <p className="rounded-lg border border-dashed border-red-200 bg-red-50/40 px-3 py-4 text-center text-sm text-red-600">
                      {t.compliance.driverFields.none}
                    </p>
                  )}
                </Section>
              </div>

              <Section title={t.compliance.sheet.alerts}>
                {vehicle.alerts.length === 0 ? (
                  <p className="text-sm text-muted-foreground">{t.compliance.sheet.noAlerts}</p>
                ) : (
                  <ul className="space-y-2">
                    {vehicle.alerts.map((alert) => (
                      <li key={alert.id} className="flex items-center justify-between gap-3 rounded-lg border border-border px-3 py-2 text-xs">
                        <div>
                          <div className="font-medium">{formatDateTime(alert.sent_at, locale)}</div>
                          <div className="text-muted-foreground">
                            {alert.sent_by} · {alert.channels.map((c) => t.compliance.alertsTab.channels[c]).join(" + ")} ·{" "}
                            {t.compliance.alertsTab.missingCount(alert.missing.length)}
                          </div>
                        </div>
                        <span
                          className={cn(
                            "rounded-md border px-2 py-0.5 font-semibold",
                            alert.resolved_at
                              ? "border-emerald-200 bg-emerald-50 text-emerald-700"
                              : "border-amber-200 bg-amber-50 text-amber-700",
                          )}
                        >
                          {alert.resolved_at ? t.compliance.alertsTab.resolved : t.compliance.alertsTab.pending}
                        </span>
                      </li>
                    ))}
                  </ul>
                )}
              </Section>
            </div>
          </>
        )}
      </SheetContent>
    </Sheet>
  );
}
