"use client";

import { useTransition, useState } from "react";
import { Check, Copy, CircleNotch, X } from '@/lib/icons';

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cancelInviteAction } from "@/lib/appwrite/team-actions";

type Invite = {
  id: string;
  code: string;
  email: string;
  role: string;
  expiresAt?: string;
  createdAt: string;
};

export function PendingInvitesTable({
  invites,
  canManage,
}: {
  invites: Invite[];
  canManage: boolean;
}) {
  const [busy, setBusy] = useState<string | null>(null);
  const [, startTransition] = useTransition();
  const [copiedId, setCopiedId] = useState<string | null>(null);

  const baseUrl =
    typeof window !== "undefined" ? window.location.origin : "";

  const copy = async (code: string, id: string) => {
    try {
      await navigator.clipboard.writeText(`${baseUrl}/d/${code}`);
      setCopiedId(id);
      setTimeout(() => setCopiedId(null), 2000);
    } catch {
      /* ignore */
    }
  };

  const cancel = (id: string) => {
    setBusy(id);
    startTransition(async () => {
      const fd = new FormData();
      fd.set("inviteId", id);
      await cancelInviteAction({ ok: false }, fd);
      setBusy(null);
    });
  };

  const formatDate = (iso?: string) => {
    if (!iso) return "—";
    return new Date(iso).toLocaleDateString("tr-TR", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    });
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Bekleyen davetler ({invites.length})</CardTitle>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Email</TableHead>
              <TableHead>Rol</TableHead>
              <TableHead>Geçerlilik</TableHead>
              <TableHead className="text-right">İşlem</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {invites.map((inv) => (
              <TableRow key={inv.id}>
                <TableCell className="font-medium">{inv.email}</TableCell>
                <TableCell>
                  <Badge variant="outline">
                    {inv.role === "admin" ? "Yönetici" : "Üye"}
                  </Badge>
                </TableCell>
                <TableCell className="text-muted-foreground">
                  {formatDate(inv.expiresAt)}
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-2">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => copy(inv.code, inv.id)}
                    >
                      {copiedId === inv.id ? (
                        <Check className="size-3.5" />
                      ) : (
                        <Copy className="size-3.5" />
                      )}
                      Linki kopyala
                    </Button>
                    {canManage && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        disabled={busy === inv.id}
                        onClick={() => cancel(inv.id)}
                      >
                        {busy === inv.id ? (
                          <CircleNotch className="size-3.5 animate-spin" />
                        ) : (
                          <X className="size-3.5" />
                        )}
                        İptal
                      </Button>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}
