"use client";

import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/modal";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useTranslations } from "@/i18n/provider";
import { formatRiskScore, riskToneClassName, toProviderLabel } from "./payments-workspace.data";
import type { ComplianceSnapshot } from "./payments-workspace.types";

interface ProviderRiskTableProps {
  title: string;
  snapshot: ComplianceSnapshot | null;
  onClose?: () => void;
}

export function ProviderRiskTable({ title, snapshot, onClose }: ProviderRiskTableProps) {
  const t = useTranslations();
  if (!snapshot || snapshot.providers.length === 0) {
    return null;
  }

  const providers = [...snapshot.providers].sort((left, right) =>
    toProviderLabel(left.provider).localeCompare(toProviderLabel(right.provider))
  );

  return (
    <Modal
      isOpen={true}
      onClose={onClose}
      ariaLabel={title}
      closeLabel={t("DashboardPayments.providerRisk.close", { title })}
      contentClassName="rounded-[24px] border-border-default p-6"
      size="xl"
    >
      <div className="mb-5 pr-14">
        <div className="space-y-1">
          <p className="text-[22px] font-medium text-primary">{title}</p>
          <p className="text-sm text-tertiary">{new Date(snapshot.checkedAt).toLocaleString()}</p>
          <p className="text-sm text-tertiary">{t("DashboardPayments.providerRisk.description")}</p>
        </div>
      </div>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>{t("DashboardPayments.providerRisk.provider")}</TableHead>
            <TableHead>{t("DashboardPayments.providerRisk.analysis")}</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {providers.map((provider) => (
            <TableRow key={provider.provider}>
              <TableCell className="font-medium text-primary">
                {toProviderLabel(provider.provider)}
              </TableCell>
              <TableCell className="text-primary">
                <span
                  className={`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium ${riskToneClassName(provider)}`}
                >
                  {formatRiskScore(provider, t)}
                </span>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {onClose ? (
        <div className="mt-6 flex justify-end">
          <Button type="button" variant="secondary" onClick={() => onClose()}>
            {t("DashboardPayments.providerRisk.dismiss")}
          </Button>
        </div>
      ) : null}
    </Modal>
  );
}
