"use client";

import { useActionState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { FileText, Loader2, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { deletePaymentAction } from "@/lib/appwrite/payment-actions";
import {
  PAYMENT_METHOD_LABELS,
  initialPaymentActionState,
} from "@/lib/appwrite/payment-types";
import type { Payment } 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}`;
  }
}

export function MyPendingPaymentsCard({
  rows,
  counterpartNames,
}: {
  rows: Payment[];
  counterpartNames: Record<string, string>;
}) {
  if (rows.length === 0) return null;
  return (
    <Card>
      <CardHeader>
        <CardTitle>Gönderdiğim Ödemeler</CardTitle>
        <CardDescription>
          Laboratuvar onayı bekleyen veya reddedilen bildirimleriniz. Onaylanan
          ödemeler artık burada gözükmez — açık bakiyenize işlenir.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <ul className="divide-y rounded-md border">
          {rows.map((p) => (
            <Row
              key={p.$id}
              payment={p}
              counterpartName={counterpartNames[p.counterpartTenantId] ?? "—"}
            />
          ))}
        </ul>
      </CardContent>
    </Card>
  );
}

function Row({
  payment,
  counterpartName,
}: {
  payment: Payment;
  counterpartName: string;
}) {
  const router = useRouter();
  const [state, action, pending] = useActionState(
    deletePaymentAction,
    initialPaymentActionState,
  );

  useEffect(() => {
    if (state.ok) {
      toast.success("Bildirim silindi.");
      router.refresh();
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state, router]);

  const isPending = payment.status === "pending";
  const isRejected = payment.status === "rejected";

  return (
    <li className="flex flex-wrap items-center gap-3 px-3 py-3">
      <div className="min-w-0 flex-1">
        <p className="truncate font-medium">{counterpartName}</p>
        <p className="text-muted-foreground text-xs">
          {dateFormatter.format(new Date(payment.paymentDate))}
          {payment.method && (
            <> · {PAYMENT_METHOD_LABELS[payment.method] ?? payment.method}</>
          )}
          {payment.notes && <> · {payment.notes}</>}
        </p>
      </div>
      <div className="text-right">
        <p className="text-base font-semibold tabular-nums">
          {formatMoney(payment.amount, payment.currency)}
        </p>
        <Badge
          variant="outline"
          className={
            isPending
              ? "text-amber-600 dark:text-amber-400"
              : isRejected
                ? "text-destructive"
                : ""
          }
        >
          {isPending ? "Onay bekliyor" : isRejected ? "Reddedildi" : "Onaylandı"}
        </Badge>
      </div>
      <div className="flex gap-2">
        <Button asChild size="sm" variant="outline">
          <Link href={`/finance/payments/${payment.$id}/receipt`}>
            <FileText className="size-4" />
            Makbuz
          </Link>
        </Button>
        {isPending && (
          <form action={action}>
            <input type="hidden" name="id" value={payment.$id} />
            <Button type="submit" size="sm" variant="outline" disabled={pending}>
              {pending ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
              Geri al
            </Button>
          </form>
        )}
      </div>
    </li>
  );
}
