"use client";

import { useActionState, useEffect, useTransition } from "react";
import { Loader2, X } 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 { cancelConnectionAction } from "@/lib/appwrite/connection-actions";
import { initialConnectionActionState } from "@/lib/appwrite/connection-types";
import type { ConnectionWithCounterpart } from "@/lib/appwrite/connection-queries";

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

export function PendingOutboundTable({ rows }: { rows: ConnectionWithCounterpart[] }) {
  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">
        Gönderilmiş talebiniz yok.
      </p>
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Karşı taraf</TableHead>
          <TableHead>Tür</TableHead>
          <TableHead>Gönderim</TableHead>
          <TableHead className="text-right">İşlem</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((r) => (
          <OutboundRow key={r.$id} row={r} />
        ))}
      </TableBody>
    </Table>
  );
}

function OutboundRow({ row }: { row: ConnectionWithCounterpart }) {
  const [state, action, pending] = useActionState(
    cancelConnectionAction,
    initialConnectionActionState,
  );
  const [, startTransition] = useTransition();

  useEffect(() => {
    if (state.ok) toast.success("Talep iptal edildi.");
    else if (state.error) toast.error(state.error);
  }, [state]);

  const kindLabel =
    row.counterpart?.kind === "lab"
      ? "Laboratuvar"
      : row.counterpart?.kind === "clinic"
        ? "Klinik"
        : "—";

  return (
    <TableRow>
      <TableCell className="font-medium">{row.counterpart?.companyName ?? "—"}</TableCell>
      <TableCell>
        <Badge variant="secondary">{kindLabel}</Badge>
      </TableCell>
      <TableCell className="text-muted-foreground">
        {dateFormatter.format(new Date(row.requestedAt))}
      </TableCell>
      <TableCell className="text-right">
        <form
          action={(fd) => {
            startTransition(() => action(fd));
          }}
        >
          <input type="hidden" name="connectionId" value={row.$id} />
          <Button type="submit" size="sm" variant="outline" disabled={pending}>
            {pending ? <Loader2 className="size-4 animate-spin" /> : <X className="size-4" />}
            İptal et
          </Button>
        </form>
      </TableCell>
    </TableRow>
  );
}
