"use client"

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

const initialState: SettingsState = {}

export function AnthropicKeyForm({ hasStoredKey }: { hasStoredKey: boolean }) {
  const [state, formAction, pending] = useActionState(saveAnthropicKey, 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é API"}
        name="apiKey"
        type="password"
        placeholder="sk-ant-…"
        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">Clé enregistrée.</p>
      )}
      <Button type="submit" size="sm" disabled={pending}>
        {pending ? "Enregistrement…" : "Enregistrer"}
      </Button>
    </form>
  )
}
