'use client'

import type { WebhookEndpointListItem } from '@admin/actions/webhooks'
import { deleteWebhook } from '@admin/actions/webhooks'
import { Button } from '@admin/components/ui/button'
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@admin/components/ui/dialog'
import { Spinner } from '@admin/components/ui/spinner'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'

interface DeleteWebhookDialogProps {
  webhook: WebhookEndpointListItem | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function DeleteWebhookDialog({ webhook, open, onOpenChange }: DeleteWebhookDialogProps) {
  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn: async () => {
      if (!webhook) throw new Error('No webhook selected')
      const result = await deleteWebhook(webhook.id)
      if (!result.success) {
        throw new Error(result.error || 'Failed to delete this webhook')
      }

      return result
    },
    onSuccess: async () => {
      toast.success('Webhook deleted')
      await queryClient.invalidateQueries({ queryKey: ['webhooks'] })
      await queryClient.invalidateQueries({
        queryKey: ['webhook-subscriptions']
      })
      await queryClient.invalidateQueries({ queryKey: ['webhook-deliveries'] })
      onOpenChange(false)
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to delete this webhook')
    }
  })

  const isPending = mutation.isPending

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-105">
        <DialogHeader>
          <DialogTitle>Delete webhook?</DialogTitle>
          <DialogDescription>
            {webhook
              ? `"${webhook.name}" stops receiving events. Its subscriptions and delivery history are deleted too.`
              : 'This webhook stops receiving events.'}
          </DialogDescription>
        </DialogHeader>
        <DialogBody>
          <p className="text-sm text-muted-foreground">This action cannot be undone.</p>
        </DialogBody>
        <DialogFooter showCloseButton={true}>
          <Button
            variant="secondary"
            size="lg"
            disabled={isPending}
            onClick={() => onOpenChange(false)}
          >
            Cancel
          </Button>
          <Button
            variant="destructive"
            size="lg"
            disabled={isPending}
            aria-busy={isPending}
            onClick={() => mutation.mutate()}
          >
            {isPending && <Spinner />}
            {isPending ? 'Deleting…' : 'Delete webhook'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
