"use client";

import type { ReactNode } from "react";
import { useState } from "react";
import { formatApiDate } from "@/lib/format/dates";
import {
  ArrowLeftRight,
  Building2,
  Calendar,
  Landmark,
  Tag,
  Pencil,
  Trash2,
} from "lucide-react";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
import type {
  TransactionDetailSheetConfig,
  TransactionRowBase,
} from "@/components/customer/transaction-detail-types";
import {
  formatAmount,
  formatPrice,
  formatQuantity,
  getTickerSymbol,
} from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

type TransactionDetailSheetProps<TRow extends TransactionRowBase> = {
  row: TRow | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onEdit?: (row: TRow) => void;
  onDelete?: (row: TRow) => void;
  /** Extra footer content (e.g. schedule link). Shown above or instead of edit/delete when provided. */
  footer?: ReactNode;
  config: TransactionDetailSheetConfig;
};

function MetricsOverview<TRow extends TransactionRowBase>({ row }: { row: TRow }) {
  const items = [
    { label: "Price", value: formatPrice(row.price), sub: row.currency },
    { label: "Quantity", value: formatQuantity(row.quantity), sub: null },
    { label: "Notional", value: formatAmount(row.price * row.quantity), sub: row.currency },
  ] as const;

  return (
    <div className="grid grid-cols-3 border-t border-border/60 bg-muted/50">
      {items.map((item, index) => (
        <div
          key={item.label}
          className={cn(
            "flex min-w-0 flex-col justify-center px-6 py-5",
            index > 0 && "border-l border-border/60",
          )}
        >
          <span className="text-muted-foreground text-xs font-medium">{item.label}</span>
          <span
            className="mt-2 truncate text-lg font-semibold tabular-nums leading-none tracking-tight"
            title={item.value}
          >
            {item.value}
          </span>
          <span className={cn("mt-1.5 text-muted-foreground text-xs", !item.sub && "invisible")}>
            {item.sub ?? "—"}
          </span>
        </div>
      ))}
    </div>
  );
}

function DetailItem({ label, value }: { label: string; value: ReactNode }) {
  return (
    <div className="group rounded-lg border border-transparent px-3 py-2.5 transition-colors hover:border-border/60 hover:bg-muted/40">
      <dt className="text-muted-foreground text-xs">{label}</dt>
      <dd className="mt-1 text-sm font-medium">{value}</dd>
    </div>
  );
}

export function TransactionDetailSheet<TRow extends TransactionRowBase>({
  row,
  open,
  onOpenChange,
  onEdit,
  onDelete,
  footer,
  config,
}: TransactionDetailSheetProps<TRow>) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const showActions = config.showActions !== false;
  const showFooter = Boolean(footer) || showActions;
  const accentClassName =
    config.accentClassName ?? "from-teal-500/10 via-transparent to-transparent";
  const badgeClassName =
    config.badgeClassName ?? "border-0 bg-teal-500/15 font-mono text-teal-700 dark:text-teal-300";
  const iconClassName =
    config.accentClassName?.includes("teal")
      ? "from-teal-500 to-teal-600 shadow-teal-500/25"
      : "from-primary to-primary/80 shadow-primary/25";

  const handleConfirmDelete = () => {
    if (!row || !onDelete) return;
    onDelete(row);
    setDeleteDialogOpen(false);
  };

  const handleSheetOpenChange = (nextOpen: boolean) => {
    if (!nextOpen) setDeleteDialogOpen(false);
    onOpenChange(nextOpen);
  };

  const isNegative = row ? row.amount < 0 : false;
  const isPositive = row ? row.amount > 0 : false;

  return (
    <>
      <Sheet open={open} onOpenChange={handleSheetOpenChange}>
        <SheetContent
          side="right"
          className="flex h-full w-full flex-col gap-0 overflow-hidden bg-muted/30 p-0 data-[side=right]:sm:max-w-2xl"
        >
          <SheetTitle className="sr-only">
            {row ? `${row.name} — ${row.refId}` : `${config.entityLabel} details`}
          </SheetTitle>
          <SheetDescription className="sr-only">
            {row
              ? `View ${row.type} ${row.transaction} for ${row.ticker} at ${row.bank}.`
              : `View ${config.entityLabel.toLowerCase()} details.`}
          </SheetDescription>

          {row ? (
            <>
              <div className="shrink-0 px-6 pt-6 pr-14">
                <p className="text-muted-foreground text-[11px] font-semibold tracking-widest uppercase">
                  {config.entityLabel}
                </p>
              </div>

              <ScrollArea className="min-h-0 flex-1">
                <div className="space-y-6 px-6 pb-8">
                  <div className="overflow-hidden rounded-2xl border border-border/60 bg-card shadow-sm">
                    <div className={cn("bg-gradient-to-r px-6 py-6", accentClassName)}>
                      <div className="flex items-start gap-4">
                        <div
                          className={cn(
                            "flex size-14 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br font-bold text-sm text-white shadow-md",
                            iconClassName,
                          )}
                        >
                          {getTickerSymbol(row.ticker)}
                        </div>
                        <div className="min-w-0 flex-1">
                          <h2 className="font-semibold text-xl tracking-tight">{row.name}</h2>
                          <p className="mt-0.5 font-mono text-muted-foreground text-xs">{row.refId}</p>
                          <div className="mt-3 flex flex-wrap gap-1.5">
                            <Badge className={badgeClassName}>{row.ticker}</Badge>
                            <Badge variant="secondary">{row.type}</Badge>
                            <Badge variant="outline">{row.transaction}</Badge>
                          </div>
                        </div>
                      </div>
                    </div>

                    <Separator />

                    <div className="px-6 py-6">
                      <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                        Total amount
                      </p>
                      <p
                        className={cn(
                          "mt-2 font-semibold text-3xl tabular-nums tracking-tight sm:text-4xl",
                          isNegative && "text-red-600 dark:text-red-400",
                          isPositive && "text-emerald-600 dark:text-emerald-400",
                        )}
                      >
                        {formatAmount(row.amount)}
                        <span className="ml-2 text-xl font-medium text-muted-foreground">
                          {row.currency}
                        </span>
                      </p>
                      <div className="mt-4 flex flex-wrap gap-2">
                        <span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-3 py-1.5 text-xs font-medium">
                          <Calendar className="size-3.5 shrink-0 text-muted-foreground" />
                          {formatApiDate(row.placementDate, "dd MMM yyyy")}
                        </span>
                        <span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-3 py-1.5 text-xs font-medium">
                          <Landmark className="size-3.5 shrink-0 text-muted-foreground" />
                          {row.bank}
                        </span>
                        <span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-3 py-1.5 text-xs font-medium">
                          <ArrowLeftRight className="size-3.5 shrink-0 text-muted-foreground" />
                          {row.transaction}
                        </span>
                      </div>
                    </div>

                    <MetricsOverview row={row} />
                  </div>

                  <div className="rounded-2xl border border-border/60 bg-card p-6 shadow-sm">
                    <h3 className="font-semibold text-sm">Transaction details</h3>
                    <p className="mt-0.5 text-muted-foreground text-xs">Full record information</p>

                    <div className="mt-5 space-y-6">
                      <div>
                        <p className="mb-3 flex items-center gap-2 text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                          <Tag className="size-3.5" />
                          Identification
                        </p>
                        <dl className="grid grid-cols-2 gap-2 md:grid-cols-3">
                          <DetailItem
                            label="Reference ID"
                            value={<span className="font-mono text-xs">{row.refId}</span>}
                          />
                          <DetailItem
                            label="Record ID"
                            value={
                              <span className="font-mono text-xs text-muted-foreground">{row.id}</span>
                            }
                          />
                          <DetailItem
                            label="Ticker"
                            value={<span className="font-mono text-xs">{row.ticker}</span>}
                          />
                          <DetailItem label="Asset" value={row.name} />
                        </dl>
                      </div>

                      <div>
                        <p className="mb-3 flex items-center gap-2 text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                          <Building2 className="size-3.5" />
                          Settlement
                        </p>
                        <dl className="grid grid-cols-2 gap-2 md:grid-cols-3">
                          <DetailItem
                            label="Placement date"
                            value={formatApiDate(row.placementDate, "dd MMM yyyy")}
                          />
                          <DetailItem label="Currency" value={row.currency} />
                          <DetailItem label="Bank" value={row.bank} />
                        </dl>
                      </div>

                      <div>
                        <p className="mb-3 flex items-center gap-2 text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                          <ArrowLeftRight className="size-3.5" />
                          Classification
                        </p>
                        <dl className="grid grid-cols-2 gap-2 md:grid-cols-3">
                          <DetailItem label="Type" value={row.type} />
                          <DetailItem label="Execution" value={row.executionType} />
                          <DetailItem label="Transaction" value={row.transaction} />
                        </dl>
                      </div>
                    </div>
                  </div>
                </div>
              </ScrollArea>

              {showFooter ? (
                <div className="shrink-0 border-t border-border/60 bg-card/80 px-6 py-5 backdrop-blur-md">
                  <div className="flex flex-col gap-3">
                    {footer}
                    {showActions ? (
                      <div className="flex gap-3">
                        <Button
                          variant="outline"
                          className="h-11 flex-1 gap-2 rounded-xl shadow-sm"
                          onClick={() => onEdit?.(row)}
                        >
                          <Pencil className="size-4" />
                          Edit transaction
                        </Button>
                        <Button
                          variant="outline"
                          className="h-11 flex-1 gap-2 rounded-xl border-destructive/25 bg-background text-destructive shadow-sm hover:border-destructive/40 hover:bg-destructive/5"
                          onClick={() => setDeleteDialogOpen(true)}
                        >
                          <Trash2 className="size-4" />
                          Delete transaction
                        </Button>
                      </div>
                    ) : null}
                  </div>
                </div>
              ) : null}
            </>
          ) : null}
        </SheetContent>
      </Sheet>

      {showActions ? (
        <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent className="sm:max-w-md">
          <AlertDialogHeader>
            <AlertDialogTitle>Delete this transaction?</AlertDialogTitle>
            <AlertDialogDescription className="text-pretty">
              {row ? (
                <>
                  <span className="font-medium text-foreground">{row.name}</span> ({row.refId}) will be
                  permanently removed. This cannot be undone.
                </>
              ) : (
                "This action cannot be undone."
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction variant="destructive" onClick={handleConfirmDelete}>
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      ) : null}
    </>
  );
}
