import Link from "next/link";
import type { ReactNode } from "react";
import { ArrowLeft, ExternalLink, Pencil } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { formatApiDate } from "@/lib/format/dates";
import { cn } from "@/lib/utils";

import { RecordViewDeleteButton } from "./record-view-delete-button";
import { displayValue } from "./record-view-primitives";

const HERO_TONE_CLASS = {
  sky: "from-sky-50/80 via-white to-slate-50 dark:from-sky-950/20 dark:via-background dark:to-slate-950",
  violet:
    "from-violet-50/80 via-white to-slate-50 dark:from-violet-950/20 dark:via-background dark:to-slate-950",
  orange:
    "from-orange-50/80 via-white to-slate-50 dark:from-orange-950/20 dark:via-background dark:to-slate-950",
  rose: "from-slate-50 via-white to-rose-50/40 dark:from-slate-950 dark:via-background dark:to-rose-950/20",
  teal: "from-teal-50/80 via-white to-slate-50 dark:from-teal-950/20 dark:via-background dark:to-slate-950",
} as const;

const BADGE_TONE_CLASS = {
  sky: "bg-sky-800/90 text-white hover:bg-sky-800",
  violet: "bg-violet-800/90 text-white hover:bg-violet-800",
  orange: "bg-orange-700/90 text-white hover:bg-orange-700",
  rose: "bg-rose-800/90 text-white hover:bg-rose-800",
  teal: "bg-teal-800/90 text-white hover:bg-teal-800",
} as const;

export type RecordViewTone = keyof typeof HERO_TONE_CLASS;

export function RecordViewShell({ children }: { children: ReactNode }) {
  return <div className="mx-auto flex w-full max-w-5xl flex-col gap-5">{children}</div>;
}

export function RecordViewActions({
  backHref,
  cashflowHref,
  editHref,
  reportHref,
  reportLabel,
  onDelete,
  canDelete = true,
  deleteLabel = "transaction",
  deleteDescription,
}: {
  backHref: string;
  cashflowHref: string;
  editHref: string;
  reportHref?: string | null;
  reportLabel?: string;
  onDelete?: () => Promise<void>;
  canDelete?: boolean;
  deleteLabel?: string;
  deleteDescription?: ReactNode;
}) {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Button type="button" variant="ghost" size="sm" asChild>
        <Link href={backHref}>
          <ArrowLeft className="size-4" />
          Back
        </Link>
      </Button>
      <Button type="button" variant="outline" size="sm" asChild>
        <Link href={cashflowHref}>Cashflow</Link>
      </Button>
      {reportHref ? (
        <Button type="button" variant="outline" size="sm" asChild>
          <a href={reportHref} target="_blank" rel="noreferrer">
            {reportLabel ?? "Report"}
            <ExternalLink className="size-3.5" />
          </a>
        </Button>
      ) : null}
      <Button type="button" size="sm" asChild>
        <Link href={editHref}>
          <Pencil className="size-4" />
          Edit
        </Link>
      </Button>
      {onDelete && canDelete !== false ? (
        <RecordViewDeleteButton
          onDelete={onDelete}
          entityLabel={deleteLabel}
          description={deleteDescription}
        />
      ) : null}
    </div>
  );
}

export function RecordViewHeader({
  tone,
  badgeLabel,
  extraBadges,
  title,
  refId,
  isin,
  actions,
}: {
  tone: RecordViewTone;
  badgeLabel: string;
  extraBadges?: ReactNode;
  title: string;
  refId: string;
  isin?: string | null;
  actions: ReactNode;
}) {
  const isinTrimmed = (isin ?? "").trim();

  return (
    <div className="flex flex-col gap-4 border-b border-border/60 pb-4 sm:flex-row sm:items-start sm:justify-between">
      <div className="min-w-0 space-y-2">
        <div className="flex flex-wrap items-center gap-2">
          <Badge className={cn("rounded-full", BADGE_TONE_CLASS[tone])}>{badgeLabel}</Badge>
          {extraBadges}
        </div>
        <h1 className="font-semibold text-2xl tracking-tight">{title}</h1>
        <p className="text-muted-foreground text-sm">
          Ref. ID {refId}
          {isinTrimmed ? (
            <>
              {" · "}
              <span className="font-mono tracking-tight">{isinTrimmed}</span>
            </>
          ) : null}
        </p>
      </div>
      {actions}
    </div>
  );
}

export function RecordViewHero({
  tone,
  amountLabel = "Amount",
  amount,
  subtitle,
  leftDateLabel = "Trade date",
  leftDate,
  rightDateLabel,
  rightDate,
}: {
  tone: RecordViewTone;
  amountLabel?: string;
  amount: string;
  subtitle?: string;
  leftDateLabel?: string;
  leftDate?: string | null;
  rightDateLabel?: string;
  rightDate?: string | null;
}) {
  const showRightDate = Boolean((rightDateLabel ?? "").trim());

  return (
    <div
      className={cn(
        "overflow-hidden rounded-2xl border border-border/60 bg-gradient-to-br",
        HERO_TONE_CLASS[tone],
      )}
    >
      <div className="grid gap-4 p-5 sm:grid-cols-[1.2fr_0.8fr] sm:items-end">
        <div>
          <p className="text-muted-foreground text-xs font-medium uppercase tracking-[0.14em]">
            {amountLabel}
          </p>
          <p className="mt-2 font-semibold text-3xl tabular-nums tracking-tight">{amount}</p>
          {subtitle ? <p className="mt-2 text-muted-foreground text-sm">{subtitle}</p> : null}
        </div>
        <div className={cn("grid gap-3", showRightDate ? "grid-cols-2" : "grid-cols-1")}>
          <HeroDateCard
            label={leftDateLabel}
            value={formatApiDate(leftDate ?? "", "dd MMM yyyy", leftDate ?? "") || "—"}
          />
          {showRightDate ? (
            <HeroDateCard
              label={rightDateLabel!}
              value={formatApiDate(rightDate ?? "", "dd MMM yyyy", rightDate ?? "") || "—"}
            />
          ) : null}
        </div>
      </div>
    </div>
  );
}

function HeroDateCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-xl border border-border/50 bg-background/70 px-3 py-2.5">
      <p className="text-muted-foreground text-[11px]">{label}</p>
      <p className="mt-1 font-medium text-sm">{displayValue(value)}</p>
    </div>
  );
}
