"use client";

import { ExternalLink, Trash2, Pencil } from "lucide-react";
import type { ReactNode } from "react";
import { resolveFileUrl } from "@/components/datatable/liststock/columns";
import { formatDisplay, formatNumeric } from "@/lib/common/format-utils";
import { ModalShell } from "@/components/ui/ModalShell";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { cn } from "@/lib/utils";

/**
 * Shared record-detail dialog — backs 14 transaction detail modals.
 *
 * Rebuilt on `ModalShell` (shadcn `Dialog`), which brings the focus trap,
 * focus restore, Escape handling, background scroll lock and `aria-modal` this
 * previously had none of: it was a bare fixed div whose only dismissal was a
 * click on the backdrop.
 *
 * Visually it also drops two blurred decorative blobs and a gradient header
 * wash that sat behind the record's own figures. Metrics and detail pairs are
 * `Card`s now, so the numbers are the loudest thing in the dialog.
 */

export interface RecordModalProps<T> {
  record: T;
  onClose: () => void;
  onEdit: () => void;
  onDelete?: () => void;
  title: string;
  subtitle?: string;
  metrics: Array<{
    label: string;
    value: string;
    colorClass?: string;
  }>;
  detailItems: Array<{
    label: string;
    value: string;
  }>;
  lastUpdated?: string;
  extraContent?: ReactNode;
}

export function RecordModal<T extends { uid?: string; t_date?: string }>({
  record,
  onClose,
  onEdit,
  onDelete,
  title,
  subtitle,
  metrics,
  detailItems,
  lastUpdated,
  extraContent,
}: RecordModalProps<T>) {
  const fileUrl = resolveFileUrl(record as any);
  const anyRecord = record as any;
  const reference = record.uid || anyRecord.uid1;

  // Reference line: id · bank · bank ref, skipping whatever is absent.
  const referenceParts = [
    reference ? `Ref #${reference}` : null,
    anyRecord.bank_id || null,
    anyRecord.r_no ? `Bank ref ${anyRecord.r_no}` : null,
    !anyRecord.bank_id && anyRecord.f_type ? anyRecord.f_type : null,
  ].filter(Boolean);

  return (
    <ModalShell
      isOpen
      onClose={onClose}
      size="xl"
      eyebrow={title}
      title={subtitle || "—"}
      description={referenceParts.length ? referenceParts.join(" · ") : undefined}
      footer={
        <div className="flex w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-xs text-muted-foreground">
            Last updated: {lastUpdated || formatDisplay(record.t_date)}
          </p>

          <div className="flex flex-wrap items-center gap-2">
            {fileUrl && (
              <Button variant="outline" size="sm" asChild>
                <a href={fileUrl} target="_blank" rel="noopener noreferrer">
                  <ExternalLink className="size-4" aria-hidden />
                  View document
                </a>
              </Button>
            )}
            <Button variant="outline" size="sm" onClick={onEdit}>
              <Pencil className="size-4" aria-hidden />
              Edit record
            </Button>
            {onDelete && (
              <Button variant="destructive" size="sm" onClick={onDelete}>
                <Trash2 className="size-4" aria-hidden />
                Delete
              </Button>
            )}
          </div>
        </div>
      }
    >
      {metrics.length > 0 && (
        <dl className="grid gap-3 sm:grid-cols-3">
          {metrics.map((metric) => (
            <Card key={metric.label} className="gap-0 bg-muted/40 py-3 shadow-none">
              <CardContent className="px-4">
                <dt className="oxy-eyebrow">{metric.label}</dt>
                <dd
                  className={cn(
                    "mt-1 text-lg font-semibold tabular-nums",
                    metric.colorClass || "text-foreground"
                  )}
                >
                  {metric.value}
                </dd>
              </CardContent>
            </Card>
          ))}
        </dl>
      )}

      {detailItems.length > 0 && (
        <dl
          className={cn(
            "grid gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-3",
            metrics.length > 0 && "mt-6 border-t border-border pt-5"
          )}
        >
          {detailItems.map((item) => (
            <div key={item.label} className="min-w-0">
              <dt className="oxy-eyebrow">{item.label}</dt>
              <dd className="mt-1 truncate text-sm font-medium text-foreground">
                {item.value}
              </dd>
            </div>
          ))}
        </dl>
      )}

      {extraContent ? <div className="mt-6">{extraContent}</div> : null}
    </ModalShell>
  );
}

// Export formatting utilities for convenience
export { formatDisplay, formatNumeric };
