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

export function EditLocationPage() {
  const { id = '' } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [location, setLocation] = useState<Location | null>(null)
  const [name, setName] = useState('')
  const [active, setActive] = useState(true)
  const [loading, setLoading] = useState(true)
  const [ext, setExt] = useState<Record<string, unknown>>({})
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    inventory.getLocation(id)
      .then((loc) => {
        setLocation(loc)
        setName(loc.name)
        setActive(loc.active)
        setExt(loc.ext || {})
      })
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }, [id])

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      await inventory.updateLocation(id, {
        name, active,
        ...(Object.keys(ext).length > 0 ? { ext } : {}),
      })
      navigate('/locations')
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) return <Loading />
  if (!location) return <ErrorBox error={error ?? 'Location not found'} />

  return (
    <div>
      <PageHeader
        title={`Edit ${location.code}`}
        subtitle={`Type: ${location.type} (read-only after creation)`}
        actions={<button className="btn-secondary" onClick={() => navigate('/locations')}>Cancel</button>}
      />
      <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-2xl">
        <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)}
            className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
        </div>
        <div className="flex items-center gap-2">
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)}
            className="rounded border-slate-300" id="active" />
          <label htmlFor="active" className="text-sm text-slate-700">Active</label>
        </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 ? 'Saving\u2026' : 'Save Changes'}
        </button>
      </form>
    </div>
  )
}
