import { Plus, Radio, RefreshCw, Trash2 } from 'lucide-react';
import { toast } from 'sonner';

import { useCallback, useEffect, useRef } from 'react';

import { Head } from '@inertiajs/react';

import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { CreateEndpointDialog } from '@/Components/settings/CreateEndpointDialog';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { ConfirmDialog } from '@/Components/ui/confirm-dialog';
import { EmptyState } from '@/Components/ui/empty-state';
import { ErrorWithRetry } from '@/Components/ui/error-with-retry';
import { Skeleton } from '@/Components/ui/skeleton';
import { useWebhooksState } from '@/hooks/useWebhooksState';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { EMPTY_TITLE } from '@/lib/emptyStateMessages';
import { FEATURE_USED, SETTINGS_WEBHOOKS_VIEWED } from '@/lib/event-catalog';
import { couldnt } from '@/lib/messages';
import { getCsrfToken } from '@/lib/utils';
import type { WebhookEndpoint } from '@/types';

interface WebhooksProps {
  available_events: string[];
}

export default function Webhooks({ available_events }: WebhooksProps) {
  const [state, dispatch] = useWebhooksState();

  // R3FE-011: track the endpoint whose deliveries we most recently requested,
  // so an out-of-order response for an earlier endpoint is silently dropped.
  const deliveriesRequestRef = useRef<number | null>(null);

  const fetchEndpoints = useCallback(async () => {
    dispatch({ type: 'SET_FETCH_ERROR', payload: false });
    try {
      const res = await fetch('/api/webhooks', {
        headers: { Accept: 'application/json' },
      });
      if (!res.ok) throw new Error('fetch failed');
      const data = await res.json();
      dispatch({ type: 'SET_ENDPOINTS', payload: data });
    } catch {
      dispatch({ type: 'SET_FETCH_ERROR', payload: true });
    } finally {
      dispatch({ type: 'SET_LOADING', payload: false });
    }
  }, [dispatch]);

  useEffect(() => {
    trackProductEvent(SETTINGS_WEBHOOKS_VIEWED);
    trackProductEvent(FEATURE_USED, { feature: 'settings_webhooks' });
    fetchEndpoints();
  }, [fetchEndpoints]);

  const handleDelete = async () => {
    if (!state.deleteTarget) return;
    const res = await fetch(`/api/webhooks/${state.deleteTarget.id}`, {
      method: 'DELETE',
      headers: { Accept: 'application/json', 'X-XSRF-TOKEN': getCsrfToken() },
    });
    dispatch({ type: 'SET_DELETE_TARGET', payload: null });
    if (!res.ok) {
      toast.error(couldnt('delete', 'endpoint'));
      return;
    }
    fetchEndpoints();
    toast.success('Webhook endpoint deleted.');
  };

  const handleTest = async (id: number) => {
    const res = await fetch(`/api/webhooks/${id}/test`, {
      method: 'POST',
      headers: { Accept: 'application/json', 'X-XSRF-TOKEN': getCsrfToken() },
    });
    if (res.ok) {
      toast.success('Test webhook queued.');
    } else {
      toast.error(couldnt('send', 'test webhook'));
    }
  };

  // R3UXA-005 / R3FE-011: show the deliveries panel for ANY selected endpoint
  // (including zero-delivery empty state). Check res.ok; ignore stale responses.
  const loadDeliveries = async (endpoint: WebhookEndpoint) => {
    dispatch({ type: 'SELECT_ENDPOINT', payload: endpoint });
    dispatch({ type: 'SET_DELIVERIES_LOADING', payload: true });
    deliveriesRequestRef.current = endpoint.id;

    try {
      const res = await fetch(`/api/webhooks/${endpoint.id}/deliveries`, {
        headers: { Accept: 'application/json' },
      });

      // Ignore stale out-of-order responses
      if (deliveriesRequestRef.current !== endpoint.id) return;

      if (!res.ok) {
        toast.error(couldnt('load', 'deliveries'));
        return;
      }
      const data = await res.json();
      dispatch({ type: 'SET_DELIVERIES', payload: data });
    } catch {
      if (deliveriesRequestRef.current === endpoint.id) {
        toast.error(couldnt('load', 'deliveries'));
      }
    } finally {
      if (deliveriesRequestRef.current === endpoint.id) {
        dispatch({ type: 'SET_DELIVERIES_LOADING', payload: false });
      }
    }
  };

  return (
    <DashboardLayout>
      <Head title="Webhooks" />
      <EditorialPageHeader
        title="Webhooks"
        subtitle="Webhooks fire when an analysis finishes or a draft publishes. Wire them into Slack, Linear, or your CI."
        actions={
          <Button onClick={() => dispatch({ type: 'TOGGLE_CREATE' })}>
            <Plus className="mr-2 size-4" />
            Add endpoint
          </Button>
        }
      />
      <div className="container py-8">
        <div className="max-w-4xl mx-auto space-y-6">
          {state.loading ? (
            <Card>
              <CardContent className="py-6">
                <div className="space-y-3">
                  {[...Array(3)].map((_, i) => (
                    <div key={i} className="flex items-center gap-3 p-4 border rounded-lg">
                      <Skeleton className="h-5 w-1/3" />
                      <Skeleton className="h-4 w-1/4 ml-auto" />
                      <Skeleton className="h-8 w-16" />
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          ) : state.fetchError ? (
            <Card>
              <CardContent>
                <ErrorWithRetry
                  title="Couldn't load webhooks"
                  message="We hit an error fetching your webhook endpoints."
                  onRetry={fetchEndpoints}
                  retrying={state.loading}
                />
              </CardContent>
            </Card>
          ) : state.endpoints.length === 0 ? (
            <Card>
              <CardContent>
                <EmptyState
                  variant="zero"
                  icon={Radio}
                  title={EMPTY_TITLE.webhookEndpoints}
                  description="Create an endpoint to receive event notifications when analyses complete, recommendations are applied, or AI drafts are published."
                  primaryAction={{
                    label: 'Add endpoint',
                    onClick: () => dispatch({ type: 'TOGGLE_CREATE' }),
                  }}
                />
              </CardContent>
            </Card>
          ) : (
            state.endpoints.map((endpoint) => (
              <Card key={endpoint.id}>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="space-y-1 min-w-0 flex-1">
                      <CardTitle className="text-base font-data truncate">{endpoint.url}</CardTitle>
                      {endpoint.description && (
                        <CardDescription>{endpoint.description}</CardDescription>
                      )}
                    </div>
                    <Badge variant={endpoint.active ? 'default' : 'secondary'}>
                      {endpoint.active ? 'Active' : 'Inactive'}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="flex flex-wrap gap-1.5">
                      {endpoint.events.map((event) => (
                        <Badge key={event} variant="outline" className="text-xs">
                          {event}
                        </Badge>
                      ))}
                    </div>

                    <div className="flex flex-wrap gap-2">
                      <Button variant="outline" size="sm" onClick={() => loadDeliveries(endpoint)}>
                        <RefreshCw className="mr-1.5 size-3" /> Deliveries
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => handleTest(endpoint.id)}>
                        Test
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => dispatch({ type: 'SET_DELETE_TARGET', payload: endpoint })}
                      >
                        <Trash2 className="mr-1.5 size-3" /> Delete
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))
          )}

          {/* R3UXA-005 / R3FE-011: deliveries panel shows for ANY selected endpoint,
              including zero-delivery case (empty state). */}
          {state.selectedEndpoint && (
            <Card>
              <CardHeader>
                <CardTitle className="text-base">
                  Recent Deliveries — {state.selectedEndpoint.url}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {state.deliveriesLoading ? (
                  <div className="space-y-2">
                    {[...Array(3)].map((_, i) => (
                      <Skeleton key={i} className="h-8 w-full rounded-md" />
                    ))}
                  </div>
                ) : state.deliveries.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-2">
                    No deliveries yet — click <span className="font-medium">Test</span> to send one.
                  </p>
                ) : (
                  <div className="space-y-2">
                    {state.deliveries.map((delivery) => (
                      <div
                        key={delivery.id}
                        className="flex items-center justify-between rounded-md border px-3 py-2 text-sm"
                      >
                        <div className="flex items-center gap-3">
                          <Badge
                            variant={
                              delivery.status === 'success'
                                ? 'default'
                                : delivery.status === 'failed'
                                  ? 'destructive'
                                  : 'secondary'
                            }
                            className="text-xs"
                          >
                            {delivery.status}
                          </Badge>
                          <span className="font-data text-xs">{delivery.event_type}</span>
                        </div>
                        <div className="flex items-center gap-3 text-muted-foreground text-xs">
                          {delivery.response_code && <span>HTTP {delivery.response_code}</span>}
                          <span>
                            {delivery.attempts} attempt{delivery.attempts !== 1 ? 's' : ''}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {state.showCreate && (
        <CreateEndpointDialog
          availableEvents={available_events}
          onClose={() => dispatch({ type: 'TOGGLE_CREATE' })}
          onCreated={() => {
            dispatch({ type: 'TOGGLE_CREATE' });
            fetchEndpoints();
          }}
        />
      )}

      <ConfirmDialog
        open={!!state.deleteTarget}
        onOpenChange={(open) => !open && dispatch({ type: 'SET_DELETE_TARGET', payload: null })}
        title="Delete Webhook Endpoint"
        description="This will permanently delete this endpoint and all its delivery history. This cannot be undone."
        resourceName={state.deleteTarget?.url}
        resourceType="Endpoint"
        confirmLabel="Delete"
        variant="destructive"
        onConfirm={handleDelete}
      />
    </DashboardLayout>
  );
}
