'use client';

import { useEffect, useState } from 'react';
import { 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 { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { usePermissions } from '@/hooks/use-permissions';

interface Delivery {
  id: string;
  eventType: string;
  status: string;
  responseStatus: number | null;
  attempt: number;
  deliveredAt: string | null;
  createdAt: string;
}

interface Props {
  webhookId: string;
}

const STATUS_VARIANTS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  success: 'default',
  pending: 'secondary',
  failed: 'destructive',
  dead_letter: 'destructive',
};

export function WebhookDeliveryLog({ webhookId }: Props) {
  const [deliveries, setDeliveries] = useState<Delivery[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [retrying, setRetrying] = useState<string | null>(null);
  const { can } = usePermissions();
  const canReplay = can('admin', 'manage_webhooks');

  async function retry(deliveryId: string) {
    setRetrying(deliveryId);
    try {
      await apiFetch(`/api/v1/admin/webhooks/${webhookId}/deliveries/${deliveryId}/redeliver`, {
        method: 'POST',
      });
      toast.success('Replay queued');
      await load(page);
    } catch (err) {
      toastError(err, 'Replay failed');
    } finally {
      setRetrying(null);
    }
  }

  async function load(p: number) {
    setLoading(true);
    setLoadError(null);
    try {
      const result = await apiFetch<{ data: Delivery[]; total: number }>(
        `/api/v1/admin/webhooks/${webhookId}/deliveries?page=${p}&limit=25`,
      );
      setDeliveries(result.data);
      setTotal(result.total);
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Failed to load deliveries';
      setLoadError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load(page);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [webhookId, page]);

  if (loading && deliveries.length === 0) {
    return <p className="text-sm text-muted-foreground">Loading deliveries...</p>;
  }

  if (loadError && deliveries.length === 0) {
    return (
      <div className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm space-y-2">
        <p className="text-destructive">Couldn&rsquo;t load deliveries: {loadError}</p>
        <Button size="sm" variant="outline" onClick={() => void load(page)}>
          Retry
        </Button>
      </div>
    );
  }

  if (!loading && deliveries.length === 0) {
    return <p className="text-sm text-muted-foreground">No deliveries yet.</p>;
  }

  const totalPages = Math.ceil(total / 25);

  return (
    <div className="space-y-4">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Event</TableHead>
            <TableHead>Status</TableHead>
            <TableHead>HTTP</TableHead>
            <TableHead>Attempt</TableHead>
            <TableHead>Time</TableHead>
            {canReplay && <TableHead className="w-16 text-right">Replay</TableHead>}
          </TableRow>
        </TableHeader>
        <TableBody>
          {deliveries.map((d) => (
            <TableRow key={d.id}>
              <TableCell className="font-mono text-xs">{d.eventType}</TableCell>
              <TableCell>
                <Badge variant={STATUS_VARIANTS[d.status] ?? 'outline'}>{d.status}</Badge>
              </TableCell>
              <TableCell className="text-sm">{d.responseStatus ?? '-'}</TableCell>
              <TableCell className="text-sm">{d.attempt}</TableCell>
              <TableCell className="text-xs text-muted-foreground">
                {d.deliveredAt
                  ? new Date(d.deliveredAt).toLocaleString()
                  : new Date(d.createdAt).toLocaleString()}
              </TableCell>
              {canReplay && (
                <TableCell className="text-right">
                  {(d.status === 'failed' || d.status === 'dead_letter') && (
                    <Button
                      variant="ghost"
                      size="sm"
                      disabled={retrying === d.id}
                      onClick={() => retry(d.id)}
                      title="Replay this delivery"
                      aria-label="Replay this delivery"
                    >
                      <RotateCcw
                        className={`h-3.5 w-3.5 ${retrying === d.id ? 'animate-spin' : ''}`}
                      />
                    </Button>
                  )}
                </TableCell>
              )}
            </TableRow>
          ))}
        </TableBody>
      </Table>

      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Page {page} of {totalPages} ({total} total)
          </p>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={page <= 1}
              onClick={() => setPage((p) => p - 1)}
            >
              Previous
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={page >= totalPages}
              onClick={() => setPage((p) => p + 1)}
            >
              Next
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
