"use client"

import { useActionState, useEffect, useRef } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { saveAicosSettings, type SettingsState } from "@/app/admin/settings/actions"

const initialState: SettingsState = {}

export function AicosSettingsForm({
  hasStoredKey,
  storedBaseUrl,
  storedModel,
}: {
  hasStoredKey: boolean
  storedBaseUrl: string
  storedModel: string
}) {
  const [state, formAction, pending] = useActionState(saveAicosSettings, initialState)
  const formRef = useRef<HTMLFormElement>(null)

  useEffect(() => {
    if (state.success) formRef.current?.reset()
  }, [state.success])

  return (
    <form ref={formRef} action={formAction} className="space-y-3">
      <Input
        label={hasStoredKey ? "Remplacer la clé" : "Clé (Token Provider)"}
        name="apiKey"
        type="password"
        placeholder="aicos_tp_…"
        autoComplete="off"
      />
      <Input
        label="URL de base"
        name="baseUrl"
        type="text"
        placeholder="https://…"
        defaultValue={storedBaseUrl}
        autoComplete="off"
      />
      <Input
        label="Modèle"
        name="model"
        type="text"
        placeholder="identifiant fourni par AICOS"
        defaultValue={storedModel}
        autoComplete="off"
      />
      {state.error && <p className="text-xs text-red-500 font-mono">{state.error}</p>}
      {state.success && <p className="text-xs text-[var(--accent)] font-mono">Enregistré.</p>}
      <Button type="submit" size="sm" disabled={pending}>
        {pending ? "Enregistrement…" : "Enregistrer"}
      </Button>
    </form>
  )
}
