"use client";

import Link from "next/link";
import { useActionState, useEffect, useTransition } from "react";
import { CheckCircle2, Loader2, RotateCcw } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  markFinancePaidAction,
  reopenFinanceAction,
} from "@/lib/appwrite/finance-actions";
import {
  FINANCE_STATUS_LABELS,
  FINANCE_TYPE_LABELS,
  initialFinanceActionState,
} from "@/lib/appwrite/finance-types";
import type { FinanceEntryWithCounterpart } from "@/lib/appwrite/finance-queries";
import type { FinanceStatus, FinanceType } from "@/lib/appwrite/schema";

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

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}`;
  }
}

function typeVariant(t: FinanceType): "default" | "secondary" | "outline" | "destructive" {
  if (t === "income" || t === "receivable") return "secondary";
  return "outline";
}

function statusVariant(s: FinanceStatus): "default" | "secondary" | "outline" | "destructive" {
  if (s === "paid") return "default";
  if (s === "cancelled") return "destructive";
  return "outline";
}

export function FinanceTable({ rows }: { rows: FinanceEntryWithCounterpart[] }) {
  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">
        Henüz finansal hareket yok. İşler gönderildiğinde otomatik kayıt oluşur.
      </p>
    );
  }
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Tarih</TableHead>
          <TableHead>Tür</TableHead>
          <TableHead>Karşı Taraf</TableHead>
          <TableHead>Açıklama</TableHead>
          <TableHead className="text-right">Tutar</TableHead>
          <TableHead>Durum</TableHead>
          <TableHead className="text-right">İşlem</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((r) => (
          <FinanceRow key={r.$id} row={r} />
        ))}
      </TableBody>
    </Table>
  );
}

function FinanceRow({ row }: { row: FinanceEntryWithCounterpart }) {
  const [paidState, paidAction, paidPending] = useActionState(
    markFinancePaidAction,
    initialFinanceActionState,
  );
  const [reopenState, reopenAction, reopenPending] = useActionState(
    reopenFinanceAction,
    initialFinanceActionState,
  );
  const [, startTransition] = useTransition();

  useEffect(() => {
    if (paidState.ok) toast.success("Ödendi olarak işaretlendi.");
    else if (paidState.error) toast.error(paidState.error);
  }, [paidState]);

  useEffect(() => {
    if (reopenState.ok) toast.success("Tekrar bekleyene alındı.");
    else if (reopenState.error) toast.error(reopenState.error);
  }, [reopenState]);

  return (
    <TableRow>
      <TableCell className="text-muted-foreground">
        {dateFormatter.format(new Date(row.date))}
      </TableCell>
      <TableCell>
        <Badge variant={typeVariant(row.type)}>{FINANCE_TYPE_LABELS[row.type]}</Badge>
      </TableCell>
      <TableCell className="text-muted-foreground">
        {row.counterpart?.companyName ?? "—"}
      </TableCell>
      <TableCell className="max-w-[280px] truncate text-sm">
        {row.jobId ? (
          <Link href={`/jobs/${row.jobId}`} className="hover:underline">
            {row.description ?? "—"}
          </Link>
        ) : (
          row.description ?? "—"
        )}
      </TableCell>
      <TableCell className="text-right tabular-nums">
        {formatMoney(row.amount, row.currency || "TRY")}
      </TableCell>
      <TableCell>
        <Badge variant={statusVariant(row.status)}>{FINANCE_STATUS_LABELS[row.status]}</Badge>
      </TableCell>
      <TableCell className="text-right">
        {row.status === "pending" ? (
          <form
            action={(fd) => {
              startTransition(() => paidAction(fd));
            }}
          >
            <input type="hidden" name="id" value={row.$id} />
            <Button type="submit" size="sm" disabled={paidPending}>
              {paidPending ? (
                <Loader2 className="size-4 animate-spin" />
              ) : (
                <CheckCircle2 className="size-4" />
              )}
              Ödendi
            </Button>
          </form>
        ) : row.status === "paid" ? (
          <form
            action={(fd) => {
              startTransition(() => reopenAction(fd));
            }}
          >
            <input type="hidden" name="id" value={row.$id} />
            <Button type="submit" size="sm" variant="outline" disabled={reopenPending}>
              {reopenPending ? (
                <Loader2 className="size-4 animate-spin" />
              ) : (
                <RotateCcw className="size-4" />
              )}
              Geri al
            </Button>
          </form>
        ) : (
          <span className="text-muted-foreground text-xs">—</span>
        )}
      </TableCell>
    </TableRow>
  );
}
