import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import type { CounterpartBalance } from "@/lib/appwrite/payment-queries";
import { RecordPaymentDialog } from "./record-payment-dialog";

function formatMoney(amount: number, currency: string): string {
  try {
    return new Intl.NumberFormat("tr-TR", { style: "currency", currency }).format(amount);
  } catch {
    return `${amount.toFixed(2)} ${currency}`;
  }
}

const dateFormatter = new Intl.DateTimeFormat("tr-TR", {
  day: "2-digit",
  month: "2-digit",
  year: "numeric",
});

export function BalancesCard({
  balances,
  counterpartNames,
  selfKind,
  defaultCurrency,
}: {
  balances: CounterpartBalance[];
  counterpartNames: Record<string, string>;
  selfKind: "lab" | "clinic";
  defaultCurrency: string;
}) {
  const isLab = selfKind === "lab";
  return (
    <Card>
      <CardHeader>
        <CardTitle>{isLab ? "Klinik Bakiyeleri" : "Laboratuvar Bakiyeleri"}</CardTitle>
        <CardDescription>
          {isLab
            ? "Her klinik için açık bakiye ve son tahsilatlar. Toplu ödemeleri buradan girebilirsiniz."
            : "Çalıştığınız her laboratuvar için açık bakiye ve son ödemeleriniz."}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {balances.length === 0 ? (
          <p className="text-muted-foreground py-6 text-center text-sm">
            Bağlantılarınız için henüz finansal hareket yok.
          </p>
        ) : (
          <ul className="divide-y rounded-md border">
            {balances.map((b) => {
              const name = counterpartNames[b.counterpartTenantId] ?? "—";
              const settled = b.open <= 0.01;
              return (
                <li
                  key={b.counterpartTenantId}
                  className="flex flex-wrap items-center gap-3 px-3 py-3"
                >
                  <div className="min-w-0 flex-1">
                    <p className="truncate font-medium">{name}</p>
                    <p className="text-muted-foreground text-xs">
                      Fatura: {formatMoney(b.invoiced, b.currency)} · Ödenen:{" "}
                      {formatMoney(b.paid, b.currency)}
                      {b.lastPaymentAt && (
                        <>
                          {" "}· Son ödeme:{" "}
                          {dateFormatter.format(new Date(b.lastPaymentAt))}
                        </>
                      )}
                    </p>
                  </div>
                  <div className="text-right">
                    <p
                      className={`text-base font-semibold tabular-nums ${
                        settled
                          ? "text-muted-foreground"
                          : isLab
                            ? "text-emerald-600 dark:text-emerald-400"
                            : "text-rose-600 dark:text-rose-400"
                      }`}
                    >
                      {formatMoney(b.open, b.currency)}
                    </p>
                    <p className="text-muted-foreground text-xs">
                      {settled ? "Kapalı" : isLab ? "Açık alacak" : "Açık borç"}
                    </p>
                  </div>
                  <RecordPaymentDialog
                    counterpartTenantId={b.counterpartTenantId}
                    counterpartName={name}
                    selfKind={selfKind}
                    defaultCurrency={b.currency || defaultCurrency}
                    openAmount={b.open > 0 ? b.open : undefined}
                  />
                </li>
              );
            })}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
