"use client";

import { useActionState, useEffect, useTransition } from "react";
import { Check, 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 {
  approveConnectionAction,
  rejectConnectionAction,
} 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 PendingInboundTable({ rows }: { rows: ConnectionWithCounterpart[] }) {
  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">
        Bekleyen talep yok.
      </p>
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Talep eden</TableHead>
          <TableHead>Tür</TableHead>
          <TableHead>Tarih</TableHead>
          <TableHead className="text-right">İşlem</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((r) => (
          <InboundRow key={r.$id} row={r} />
        ))}
      </TableBody>
    </Table>
  );
}

function InboundRow({ row }: { row: ConnectionWithCounterpart }) {
  const [approveState, approveAction, approvePending] = useActionState(
    approveConnectionAction,
    initialConnectionActionState,
  );
  const [rejectState, rejectAction, rejectPending] = useActionState(
    rejectConnectionAction,
    initialConnectionActionState,
  );
  const [, startTransition] = useTransition();

  useEffect(() => {
    if (approveState.ok) toast.success("Bağlantı onaylandı.");
    else if (approveState.error) toast.error(approveState.error);
  }, [approveState]);

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

  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">
        <div className="flex justify-end gap-2">
          <form
            action={(fd) => {
              startTransition(() => approveAction(fd));
            }}
          >
            <input type="hidden" name="connectionId" value={row.$id} />
            <Button type="submit" size="sm" disabled={approvePending || rejectPending}>
              {approvePending ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
              Onayla
            </Button>
          </form>
          <form
            action={(fd) => {
              startTransition(() => rejectAction(fd));
            }}
          >
            <input type="hidden" name="connectionId" value={row.$id} />
            <Button
              type="submit"
              size="sm"
              variant="outline"
              disabled={approvePending || rejectPending}
            >
              {rejectPending ? <Loader2 className="size-4 animate-spin" /> : <X className="size-4" />}
              Reddet
            </Button>
          </form>
        </div>
      </TableCell>
    </TableRow>
  );
}
