"use client";

import * as React from "react";
import { TrendingDown, X } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetTitle,
} from "@/components/ui/sheet";
import { cn } from "@/lib/utils";
import { FiguresMaskedContext } from "@/app/customer/_components/dashboard-overview-layout";
import type { PerformanceSummaryLoan } from "@/app/customer/[tenant]/reports/performance-summary/_lib/performance-summary-types";

function InfoChip({ label, value }: { label: string; value: string }) {
  return (
    <div className="min-w-0 rounded-xl bg-muted/40 px-3 py-2">
      <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
      <p className="mt-0.5 truncate text-sm font-medium text-foreground" title={value}>
        {value}
      </p>
    </div>
  );
}

export function LoanDetailSheet({
  loan,
  reportingCurrency,
  asOf,
  onClose,
}: {
  loan: PerformanceSummaryLoan | null;
  reportingCurrency: string;
  asOf?: string;
  onClose: () => void;
}) {
  const figuresMasked = React.useContext(FiguresMaskedContext);
  const open = loan != null;
  const details = loan?.details ?? [];
  const showCustomer = details.some((row) => row.customer.trim() !== "");
  const money = (formatted: string) => (figuresMasked ? "*******" : `${reportingCurrency} ${formatted}`);
  return (
    <Sheet open={open} onOpenChange={(next) => !next && onClose()}>
      <SheetContent
        side="right"
        showCloseButton={false}
        className={cn(
          "flex h-dvh w-full flex-col gap-0 overflow-hidden bg-muted/30 p-0",
          "data-[side=right]:w-full data-[side=right]:sm:max-w-none",
          "data-[side=right]:sm:!w-[min(56rem,calc(100vw-1.5rem))]",
        )}
      >
        <div className="shrink-0 space-y-2 border-b border-border/60 bg-card/80 px-4 pt-4 pb-3 backdrop-blur-md">
          <p className="text-muted-foreground text-[10px] font-semibold tracking-widest uppercase">
            Loan details
          </p>
          <div className="flex items-center justify-between gap-2">
            <SheetTitle className="flex min-w-0 items-center gap-2 text-left text-base font-semibold tracking-tight">
              <span className="flex size-8 shrink-0 items-center justify-center rounded-xl bg-primary text-primary-foreground">
                <TrendingDown className="size-3.5" />
              </span>
              <span className="truncate">Loan ({loan?.currency ?? ""})</span>
            </SheetTitle>
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              className="rounded-lg"
              onClick={onClose}
              aria-label="Close"
            >
              <X className="size-4" />
            </Button>
          </div>
          <SheetDescription className="sr-only">
            Loan lines by bank for the selected currency.
          </SheetDescription>
        </div>

        <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-4">
          <section className="grid gap-2 rounded-2xl bg-muted/40 p-3 sm:grid-cols-3">
            <InfoChip label="Loan Currency" value={loan?.currency ?? "—"} />
            <InfoChip label="As of" value={asOf || "—"} />
            <InfoChip label="Total Loan" value={loan ? money(loan.formatted) : "—"} />
          </section>

          {details.length === 0 ? (
            <p className="rounded-xl border border-dashed border-border/60 px-3 py-6 text-center text-sm text-muted-foreground">
              No loan lines.
            </p>
          ) : (
            <div className="overflow-x-auto rounded-xl bg-muted/20">
              <table className="w-full border-collapse text-sm">
                <thead>
                  <tr className="bg-sky-950 text-white">
                    <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
                      Bank Name
                    </th>
                    {showCustomer ? (
                      <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
                        Customer
                      </th>
                    ) : null}
                    <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
                      Loan ({reportingCurrency})
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {details.map((row, index) => (
                    <tr
                      key={`${row.bank}-${row.customer}-${index}`}
                      className={cn("border-t border-border/60", index % 2 === 1 && "bg-muted/20")}
                    >
                      <td className="px-3 py-2">{row.bank}</td>
                      {showCustomer ? <td className="px-3 py-2">{row.customer || "—"}</td> : null}
                      <td className="px-3 py-2 text-right tabular-nums text-red-600 dark:text-red-400">
                        {money(row.formatted)}
                      </td>
                    </tr>
                  ))}
                  <tr className="border-t border-border bg-muted/50 font-semibold">
                    <td className="px-3 py-2.5 text-right" colSpan={showCustomer ? 2 : 1}>
                      Total
                    </td>
                    <td className="px-3 py-2.5 text-right tabular-nums text-red-600 dark:text-red-400">
                      {loan ? money(loan.formatted) : "—"}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          )}
        </div>
      </SheetContent>
    </Sheet>
  );
}
