'use client';

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { PageHeader } from '@/components/shared/page-header';
import { Badge } from '@/components/ui/badge';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { WebhookForm } from '@/components/admin/webhooks/webhook-form';
import { WebhookDeliveryLog } from '@/components/admin/webhooks/webhook-delivery-log';
import { WebhookSecretDisplay } from '@/components/admin/webhooks/webhook-secret-display';

interface Webhook {
  id: string;
  name: string;
  url: string;
  events: string[];
  isActive: boolean;
  secretMasked: string;
  createdAt: string;
}

const WEBHOOKS_QUERY_KEY = ['admin', 'webhooks'] as const;

export default function WebhooksPage() {
  const queryClient = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editTarget, setEditTarget] = useState<Webhook | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Webhook | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [regenerating, setRegenerating] = useState<string | null>(null);
  const [newSecret, setNewSecret] = useState<{
    webhookId: string;
    secret: string;
    masked: string;
  } | null>(null);

  const { data: webhooks = [], isLoading: loading } = useQuery<Webhook[]>({
    queryKey: WEBHOOKS_QUERY_KEY,
    queryFn: () => apiFetch<{ data: Webhook[] }>('/api/v1/admin/webhooks').then((r) => r.data),
  });

  const loadWebhooks = () => queryClient.invalidateQueries({ queryKey: WEBHOOKS_QUERY_KEY });

  async function handleDelete() {
    if (!deleteTarget) return;
    try {
      await apiFetch(`/api/v1/admin/webhooks/${deleteTarget.id}`, { method: 'DELETE' });
      setDeleteTarget(null);
      toast.success('Webhook deleted');
      void loadWebhooks();
    } catch (err) {
      toastError(err, 'Failed to delete webhook');
    }
  }

  async function handleRegenerate(webhookId: string) {
    setRegenerating(webhookId);
    try {
      const result = await apiFetch<{ data: { secret: string; secretMasked: string } }>(
        `/api/v1/admin/webhooks/${webhookId}/regenerate-secret`,
        { method: 'POST' },
      );
      setNewSecret({ webhookId, secret: result.data.secret, masked: result.data.secretMasked });
      void loadWebhooks();
    } catch (err) {
      toastError(err, 'Failed to regenerate secret');
    } finally {
      setRegenerating(null);
    }
  }

  async function handleToggleActive(webhook: Webhook) {
    try {
      await apiFetch(`/api/v1/admin/webhooks/${webhook.id}`, {
        method: 'PATCH',
        body: { isActive: !webhook.isActive },
      });
      toast.success(webhook.isActive ? 'Webhook disabled' : 'Webhook enabled');
      void loadWebhooks();
    } catch (err) {
      toastError(err, 'Failed to toggle webhook');
    }
  }

  function toggleExpand(id: string) {
    setExpandedId((prev) => (prev === id ? null : id));
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Webhooks"
        description="Configure outgoing webhook integrations"
        actions={
          <Button
            onClick={() => {
              setEditTarget(null);
              setFormOpen(true);
            }}
          >
            Add Webhook
          </Button>
        }
      />

      {loading ? (
        <p className="text-sm text-muted-foreground">Loading...</p>
      ) : webhooks.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12">
          <p className="text-lg font-medium text-muted-foreground">No webhooks configured</p>
          <p className="text-sm text-muted-foreground mt-1">
            Add a webhook to receive real-time notifications of CRM events.
          </p>
          <Button
            className="mt-4"
            onClick={() => {
              setEditTarget(null);
              setFormOpen(true);
            }}
          >
            Add Webhook
          </Button>
        </div>
      ) : (
        <div className="space-y-2">
          {webhooks.map((webhook) => (
            <div key={webhook.id} className="rounded-lg border bg-card">
              <div className="flex items-center gap-4 p-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium truncate">{webhook.name}</span>
                    <Badge variant={webhook.isActive ? 'default' : 'secondary'}>
                      {webhook.isActive ? 'Active' : 'Inactive'}
                    </Badge>
                  </div>
                  <p className="text-xs text-muted-foreground font-mono truncate mt-0.5">
                    {webhook.url}
                  </p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {webhook.events.length} event{webhook.events.length !== 1 ? 's' : ''}
                  </p>
                </div>

                <div className="flex items-center gap-2 shrink-0">
                  <Button variant="ghost" size="sm" onClick={() => handleToggleActive(webhook)}>
                    {webhook.isActive ? 'Disable' : 'Enable'}
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setEditTarget(webhook);
                      setFormOpen(true);
                    }}
                  >
                    Edit
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-destructive"
                    onClick={() => setDeleteTarget(webhook)}
                  >
                    Delete
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => toggleExpand(webhook.id)}>
                    {expandedId === webhook.id ? 'Collapse' : 'Details'}
                  </Button>
                </div>
              </div>

              {expandedId === webhook.id && (
                <div className="border-t px-4 py-4 space-y-6">
                  {/* Events */}
                  <div>
                    <h3 className="text-sm font-medium mb-2">Subscribed Events</h3>
                    <div className="flex flex-wrap gap-1">
                      {webhook.events.map((e) => (
                        <Badge key={e} variant="outline" className="font-mono text-xs">
                          {e}
                        </Badge>
                      ))}
                    </div>
                  </div>

                  {/* Secret */}
                  <div>
                    <h3 className="text-sm font-medium mb-2">Signing Secret</h3>
                    {newSecret?.webhookId === webhook.id ? (
                      <WebhookSecretDisplay
                        plaintext={newSecret.secret}
                        masked={newSecret.masked}
                      />
                    ) : (
                      <WebhookSecretDisplay masked={webhook.secretMasked} />
                    )}
                    <Button
                      variant="outline"
                      size="sm"
                      className="mt-2"
                      disabled={regenerating === webhook.id}
                      onClick={() => handleRegenerate(webhook.id)}
                    >
                      {regenerating === webhook.id ? 'Regenerating...' : 'Regenerate Secret'}
                    </Button>
                  </div>

                  {/* Delivery Log */}
                  <div>
                    <h3 className="text-sm font-medium mb-2">Delivery Log</h3>
                    <WebhookDeliveryLog webhookId={webhook.id} />
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      <WebhookForm
        open={formOpen}
        onOpenChange={setFormOpen}
        webhook={editTarget}
        onSuccess={loadWebhooks}
      />

      <AlertDialog
        open={!!deleteTarget}
        onOpenChange={(open) => {
          if (!open) setDeleteTarget(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Webhook</AlertDialogTitle>
            <AlertDialogDescription>
              Delete &quot;{deleteTarget?.name}&quot;? This will also delete all delivery history.
              This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-destructive-foreground"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
