"use client"

import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { AutomationBorderedFieldset } from "@/components/gmail/settings/automation/automation-bordered-fieldset"
import { useContactBooks } from "@/lib/api/hooks/use-contact-queries"
import type { WebhookContactsScope } from "@/lib/mail-automation/webhook-config"

export function WebhookContactsScopeEditor({
  scope,
  onChange,
  enabled,
  className,
}: {
  scope: WebhookContactsScope
  onChange: (scope: WebhookContactsScope) => void
  enabled: boolean
  className?: string
}) {
  const { data: booksRaw, isLoading } = useContactBooks()
  const books = Array.isArray(booksRaw)
    ? booksRaw
    : booksRaw && typeof booksRaw === "object" && "address_books" in booksRaw
      ? (booksRaw as { address_books: { id: string; name: string }[] }).address_books ?? []
      : []

  if (!enabled) return null

  function toggleBook(bookId: string) {
    const ids = scope.book_ids.includes(bookId)
      ? scope.book_ids.filter((id) => id !== bookId)
      : [...scope.book_ids, bookId]
    onChange({ all_books: false, book_ids: ids })
  }

  return (
    <AutomationBorderedFieldset
      className={className}
      legend="Périmètre contacts — carnets"
    >
      <label className="flex items-start gap-2">
        <Checkbox
          checked={scope.all_books}
          onCheckedChange={(checked) =>
            onChange({
              all_books: checked === true,
              book_ids: checked === true ? [] : scope.book_ids,
            })
          }
          className="mt-0.5"
        />
        <span className="text-sm">
          Tous les carnets
          <span className="mt-0.5 block text-xs text-muted-foreground">
            Le webhook ne se déclenchera que pour les événements contacts sélectionnés.
          </span>
        </span>
      </label>

      {!scope.all_books && (
        <div className="space-y-2 pl-1">
          <Label className="text-xs text-muted-foreground">Carnets autorisés</Label>
          {isLoading ? (
            <p className="text-sm text-muted-foreground">Chargement…</p>
          ) : books.length === 0 ? (
            <p className="text-sm text-muted-foreground">Aucun carnet configuré.</p>
          ) : (
            <ul className="space-y-1.5">
              {books.map((book) => (
                <li key={book.id}>
                  <label className="flex cursor-pointer items-center gap-2 rounded-md border border-border px-2.5 py-2 hover:bg-muted/40">
                    <Checkbox
                      checked={scope.book_ids.includes(book.id)}
                      onCheckedChange={() => toggleBook(book.id)}
                    />
                    <span className="text-sm">{book.name || book.id}</span>
                  </label>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </AutomationBorderedFieldset>
  )
}
