import { useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { partners } from '@/api/client'
import { PageHeader } from '@/components/PageHeader'
import { ErrorBox } from '@/components/ErrorBox'
import { DynamicExtFields } from '@/components/DynamicExtFields'
import { useT } from '@/i18n/LocaleContext'

const PARTNER_TYPES = ['CUSTOMER', 'SUPPLIER', 'BOTH'] as const

export function CreatePartnerPage() {
  const navigate = useNavigate()
  const t = useT()
  const [code, setCode] = useState('')
  const [name, setName] = useState('')
  const [type, setType] = useState<string>('CUSTOMER')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [ext, setExt] = useState<Record<string, unknown>>({})
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      const extPayload = Object.keys(ext).length > 0 ? ext : undefined
      await partners.create({
        code, name, type,
        email: email || null,
        phone: phone || null,
        ...(extPayload ? { ext: extPayload } : {}),
      } as Parameters<typeof partners.create>[0])
      navigate('/partners')
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <PageHeader
        title={t('page.createPartner.title')}
        subtitle={t('page.createPartner.subtitle')}
        actions={<button className="btn-secondary" onClick={() => navigate('/partners')}>{t('action.cancel')}</button>}
      />
      <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-2xl">
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-slate-700">{t('label.partnerCode')}</label>
            <input type="text" required value={code} onChange={(e) => setCode(e.target.value)}
              placeholder="CUST-NEWCO" className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">{t('label.name')}</label>
            <input type="text" required value={name} onChange={(e) => setName(e.target.value)}
              placeholder="New Company Ltd." className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">{t('label.type')}</label>
            <select value={type} onChange={(e) => setType(e.target.value)}
              className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm">
              {PARTNER_TYPES.map((pt) => <option key={pt} value={pt}>{pt}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">{t('label.emailOptional')}</label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
              className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">{t('label.phoneOptional')}</label>
            <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)}
              className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
          </div>
        </div>
        <DynamicExtFields
          entityName="Partner"
          values={ext}
          onChange={(k, v) => setExt((prev) => ({ ...prev, [k]: v }))}
        />
        {error && <ErrorBox error={error} />}
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? t('action.creating') : t('page.createPartner.submit')}
        </button>
      </form>
    </div>
  )
}
