"use client"

import { useState } from "react"
import { Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  useMailWebhooks,
  useCreateMailWebhook,
  useDeleteMailWebhook,
} from "@/lib/api/hooks/use-mail-automation-queries"
import { useAuthReady } from "@/lib/api/use-auth-ready"
import { SettingsSyncBanner } from "@/components/gmail/settings/settings-sync-banner"

export function WebhooksPanel() {
  const { ready, authenticated } = useAuthReady()
  const { data: webhooks = [], isFetching, isError, refetch, isPending } = useMailWebhooks()
  const createWebhook = useCreateMailWebhook()
  const deleteWebhook = useDeleteMailWebhook()
  const [name, setName] = useState("")
  const [url, setUrl] = useState("")
  const [template, setTemplate] = useState(
    '{"text":"Nouveau mail de $sender.name : $subject"}'
  )
  const showInitialLoad = ready && authenticated && isPending && webhooks.length === 0

  return (
    <div className="space-y-4">
      <SettingsSyncBanner isFetching={isFetching} isError={isError} onRetry={() => refetch()} />
      <div className="space-y-2 rounded-lg border border-border p-4">
        <Label className="text-xs">Nouveau webhook</Label>
        <Input placeholder="Nom" value={name} onChange={(e) => setName(e.target.value)} />
        <Input placeholder="URL HTTPS" value={url} onChange={(e) => setUrl(e.target.value)} />
        <textarea
          className="min-h-20 w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-xs"
          value={template}
          onChange={(e) => setTemplate(e.target.value)}
          placeholder="body_template JSON"
        />
        <Button
          type="button"
          disabled={!name.trim() || !url.trim() || createWebhook.isPending}
          onClick={() =>
            createWebhook.mutate({
              name: name.trim(),
              url: url.trim(),
              method: "POST",
              body_template: template,
            })
          }
        >
          Créer le webhook
        </Button>
      </div>

      {showInitialLoad ? null : webhooks.length === 0 ? (
        <p className="text-sm text-muted-foreground">Aucun webhook.</p>
      ) : (
        <ul className="divide-y divide-border rounded-lg border border-border">
          {webhooks.map((hook) => (
            <li
              key={hook.id}
              className="flex items-start justify-between gap-2 px-3 py-3"
            >
              <div className="min-w-0">
                <p className="text-sm font-medium">{hook.name}</p>
                <p className="truncate text-xs text-muted-foreground">{hook.url}</p>
              </div>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                onClick={() => deleteWebhook.mutate(hook.id)}
              >
                <Trash2 className="size-4" />
              </Button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
