import { useState } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { api } from "../lib/api"
import type { Webhook } from "@emberclone/shared"

export default function Webhooks() {
  const queryClient = useQueryClient()
  const [url, setUrl] = useState("")
  const [event, setEvent] = useState<string>("customer.created")

  const { data: webhooks, isLoading, isError } = useQuery({
    queryKey: ["webhooks"],
    queryFn: () => api.listWebhooks()
  })

  const createMutation = useMutation({
    mutationFn: (payload: { url: string; event: string }) => api.createWebhook(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["webhooks"] })
      setUrl("")
    }
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.deleteWebhook(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["webhooks"] })
    }
  })

  const testMutation = useMutation({
    mutationFn: (id: string) => api.testWebhook(id),
    onSuccess: () => {
      alert("Test webhook sent successfully")
    },
    onError: (error: any) => {
      alert(`Test failed: ${error.message || "Unknown error"}`)
    }
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!url.trim()) return
    createMutation.mutate({ url, event })
  }

  if (isLoading) return <div className="p-6 text-gray-500">Loading webhooks...</div>
  if (isError) return <div className="p-6 text-red-500">Error loading webhooks.</div>

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-8">
      <header>
        <h1 className="text-2xl font-bold text-gray-900">Webhooks</h1>
        <p className="text-gray-500">Configure external notifications for system events</p>
      </header>

      <section className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
        <h2 className="text-lg font-semibold mb-4">Create New Webhook</h2>
        <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
          <div className="flex-1">
            <label className="block text-sm font-medium text-gray-700 mb-1">Target URL</label>
            <input
              type="url"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder="https://your-api.com/webhook"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Event Type</label>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none bg-white"
              value={event}
              onChange={(e) => setEvent(e.target.value)}
            >
              <option value="customer.created">Customer Created</option>
              <option value="customer.updated">Customer Updated</option>
              <option value="customer.deleted">Customer Deleted</option>
              <option value="system.alert">System Alert</option>
            </select>
          </div>
          <div>
            <button
              type="submit"
              disabled={createMutation.isPending}
              className="w-full bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors disabled:bg-blue-300 font-medium"
            >
              {createMutation.isPending ? "Saving..." : "Add Webhook"}
            </button>
          </div>
        </form>
      </section>

      <section className="overflow-x-auto bg-white rounded-lg border border-gray-200 shadow-sm">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">Event</th>
              <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">URL</th>
              <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {webhooks?.length === 0 && (
              <tr>
                <td colSpan={3} className="px-6 py-8 text-center text-gray-500">No webhooks configured.</td>
              </tr>
            )}
            {webhooks?.map((webhook: Webhook) => (
              <tr key={webhook.id} className="hover:bg-gray-50 transition-colors">
                <td className="px-6 py-4">
                  <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-700 rounded-full border border-gray-200">
                    {webhook.event}
                  </span>
                </td>
                <td className="px-6 py-4 text-sm text-gray-600 truncate max-w-xs">
                  {webhook.url}
                </td>
                <td className="px-6 py-4 text-right space-x-2">
                  <button
                    onClick={() => testMutation.mutate(webhook.id)}
                    disabled={testMutation.isPending}
                    className="text-sm text-blue-600 hover:text-blue-800 font-medium disabled:text-gray-400"
                  >
                    Test
                  </button>
                  <button
                    onClick={() => {
                      if (confirm("Delete this webhook?")) deleteMutation.mutate(webhook.id)
                    }}
                    disabled={deleteMutation.isPending}
                    className="text-sm text-red-600 hover:text-red-800 font-medium disabled:text-gray-400"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </div>
  )
}