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

const LOCATION_TYPES = ['WAREHOUSE', 'BIN', 'VIRTUAL'] as const

export function CreateLocationPage() {
  const navigate = useNavigate()
  const [code, setCode] = useState('')
  const [name, setName] = useState('')
  const [type, setType] = useState<string>('WAREHOUSE')
  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 inventory.createLocation({ code, name, type, ...(extPayload ? { ext: extPayload } : {}) })
      navigate('/locations')
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <PageHeader
        title="New Location"
        subtitle="Add a warehouse, bin, or virtual location for inventory tracking."
        actions={<button className="btn-secondary" onClick={() => navigate('/locations')}>Cancel</button>}
      />
      <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-lg">
        <div>
          <label className="block text-sm font-medium text-slate-700">Location code</label>
          <input type="text" required value={code} onChange={(e) => setCode(e.target.value)}
            placeholder="WH-NEW" 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">Name</label>
          <input type="text" required value={name} onChange={(e) => setName(e.target.value)}
            placeholder="New Warehouse" 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">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">
            {LOCATION_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
        </div>
        <DynamicExtFields
          entityName="Location"
          values={ext}
          onChange={(k, v) => setExt((prev) => ({ ...prev, [k]: v }))}
        />
        {error && <ErrorBox error={error} />}
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? 'Creating...' : 'Create Location'}
        </button>
      </form>
    </div>
  )
}
