"use client";

import type { TokenTransaction } from "@sdp/types";
import { Loader2 } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useLocale, useTranslations } from "@/i18n/provider";
import { formatDisplayLabel } from "@/lib/utils";
import { auditActionIcon, auditActionLabel } from "./asset-profile/asset-audit-presentation";
import { formatDateTime } from "./token-management-workspace.utils";

interface TokenTransactionsSectionProps {
  transactions: TokenTransaction[];
  transactionsError: string | null;
  transactionsTotal: number | null;
  transactionsHasMore: boolean;
  isLoading?: boolean;
}

// Transaction status → SDP design-system badge token (borderless tinted pill):
// settled = .badge-green, in-flight = .badge-amber, failed = .badge-red.
export function transactionStatusBadgeClass(status: string): string {
  switch (status) {
    case "confirmed":
    case "finalized":
      return "bg-success-bg text-success";
    case "pending":
    case "processing":
      return "bg-warning-bg text-warning";
    case "failed":
      return "bg-error-bg text-error";
    default:
      return "bg-fill text-secondary";
  }
}

export function TokenTransactionsSection({
  transactions,
  transactionsError,
  transactionsTotal,
  transactionsHasMore,
  isLoading = false,
}: TokenTransactionsSectionProps) {
  const t = useTranslations();
  const locale = useLocale();
  return (
    <Card className="gap-4">
      <CardHeader>
        <CardTitle>{t("DashboardIssuance.transactions.title")}</CardTitle>
        <CardDescription>{t("DashboardIssuance.transactions.description")}</CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="flex min-h-[180px] items-center justify-center rounded-2xl border border-border-subtle bg-fill-subtle px-6 py-10">
            <div className="flex items-center gap-3 text-sm text-secondary">
              <Loader2 className="size-4 animate-spin" />
              <span>{t("DashboardIssuance.transactions.loading")}</span>
            </div>
          </div>
        ) : transactionsError ? (
          <p className="text-sm text-error">{transactionsError}</p>
        ) : transactions.length === 0 ? (
          <p className="text-sm text-secondary">{t("DashboardIssuance.transactions.empty")}</p>
        ) : (
          <div className="space-y-3">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t("DashboardIssuance.transactions.type")}</TableHead>
                  <TableHead>{t("DashboardIssuance.transactions.status")}</TableHead>
                  <TableHead>{t("DashboardIssuance.transactions.signature")}</TableHead>
                  <TableHead className="text-right">
                    {t("DashboardIssuance.transactions.created")}
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {transactions.slice(0, 12).map((transaction) => {
                  const ActionIcon = auditActionIcon(transaction.type);
                  return (
                    <TableRow
                      key={transaction.id}
                      data-testid={`transaction-row-${transaction.id}`}
                    >
                      <TableCell>
                        <span className="inline-flex items-center gap-1.5 rounded-md bg-fill-subtle px-2 py-1 text-xs font-medium text-secondary">
                          <ActionIcon className="h-3.5 w-3.5 shrink-0" />
                          {auditActionLabel(transaction.type)}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span
                          className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${transactionStatusBadgeClass(
                            transaction.status
                          )}`}
                        >
                          {formatDisplayLabel(transaction.status)}
                        </span>
                      </TableCell>
                      <TableCell className="max-w-[220px] truncate font-mono text-xs">
                        {transaction.signature ?? "—"}
                      </TableCell>
                      <TableCell className="text-right whitespace-nowrap">
                        {formatDateTime(transaction.createdAt, locale)}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
            {transactionsHasMore ? (
              <p className="text-xs text-secondary">
                {t("DashboardIssuance.transactions.showing", {
                  count: transactions.length,
                  total: transactionsTotal ? ` of ${transactionsTotal}` : "",
                })}
              </p>
            ) : null}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
