"use client"

import { useEffect, useState } from "react"
import { Button } from "@/components/ui/button"
import {
  useSearchSettings,
  useUpdateSearchSettings,
} from "@/lib/api/hooks/use-contact-discovery"
import type { ApiSearchSettings } from "@/lib/contacts/discovery-types"
import { WebSearchProvidersEditor } from "@/components/web-search/web-search-providers-editor"
import {
  CONTACTS_MUTED_TEXT,
  CONTACTS_PRIMARY_BTN_CLASS,
} from "@/lib/contacts-chrome-classes"
import { normalizeSearchProviders } from "@/lib/web-search/search-provider-catalog"
import { cn } from "@/lib/utils"

export function SearchProvidersPanel() {
  const { data: remote, isLoading } = useSearchSettings()
  const updateSettings = useUpdateSearchSettings()
  const [draft, setDraft] = useState<ApiSearchSettings>(normalizeSearchProviders(undefined))
  const [saved, setSaved] = useState(false)

  useEffect(() => {
    if (remote) {
      setDraft(normalizeSearchProviders(remote))
    }
  }, [remote])

  async function handleSave() {
    const saved = await updateSettings.mutateAsync(draft)
    setDraft(normalizeSearchProviders(saved))
    setSaved(true)
    setTimeout(() => setSaved(false), 2000)
  }

  if (isLoading) {
    return <p className={cn("text-sm", CONTACTS_MUTED_TEXT)}>Chargement…</p>
  }

  return (
    <div className="w-full space-y-6">
      <div>
        <h3 className="text-base font-medium">Fournisseurs de recherche web</h3>
        <p className={cn("mt-1 text-sm", CONTACTS_MUTED_TEXT)}>
          Brave, Bing, DuckDuckGo, SearXNG ou API JSON custom — pour l&apos;enrichissement IA des
          contacts et le tool UltiAI <code className="rounded bg-muted px-1 text-xs">web_search</code>.
        </p>
      </div>

      <WebSearchProvidersEditor value={draft} onChange={setDraft} />

      <Button
        onClick={handleSave}
        disabled={updateSettings.isPending}
        className={CONTACTS_PRIMARY_BTN_CLASS}
      >
        {updateSettings.isPending ? "Enregistrement…" : saved ? "Enregistré ✓" : "Enregistrer"}
      </Button>
    </div>
  )
}
