'use client'

import { useActionState } from 'react'
import type { FormState } from '@/app/actions/auth'

type Field = { name: string; label: string; type?: string; placeholder?: string; autoComplete?: string }

export default function AuthForm({ action, fields, submit }: {
  action: (s: FormState, f: FormData) => Promise<FormState>
  fields: Field[]
  submit: string
}) {
  const [state, formAction, pending] = useActionState(action, undefined)
  return (
    <form action={formAction} className="card space-y-4 p-6">
      {fields.map(f => (
        <div key={f.name}>
          <label className="label" htmlFor={f.name}>{f.label}</label>
          <input id={f.name} name={f.name} type={f.type ?? 'text'} required className="input"
            placeholder={f.placeholder} autoComplete={f.autoComplete} />
        </div>
      ))}
      {state?.error && <p className="rounded-control bg-red-50 px-4 py-3 text-sm text-red-700">{state.error}</p>}
      <button className="btn-primary w-full" disabled={pending}>{pending ? 'Un momento…' : submit}</button>
    </form>
  )
}
