import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { departmentAPI } from '../services/api'

function DepartmentForm() {
  const { id } = useParams()
  const navigate = useNavigate()
  const isEdit = Boolean(id)
  const [name, setName] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (isEdit) {
      departmentAPI.getById(id).then(res => setName(res.data.DepartName)).catch(console.error)
    }
  }, [id, isEdit])

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      if (isEdit) await departmentAPI.update(id, { DepartName: name })
      else await departmentAPI.create({ DepartName: name })
      navigate('/departments')
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to save')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="max-w-md mx-auto space-y-4">
      <div>
        <h1 className="page-title">{isEdit ? 'Edit Department' : 'Add Department'}</h1>
        <p className="page-subtitle">{isEdit ? 'Update department name' : 'Create a new department'}</p>
      </div>

      {error && <div className="text-sm text-red-600 bg-red-50 border border-red-200 px-4 py-3 rounded">{error}</div>}

      <form onSubmit={handleSubmit} className="card p-4 space-y-4">
        <div>
          <label className="label">Department Name</label>
          <input type="text" className="input" value={name} onChange={(e) => setName(e.target.value)} required placeholder="e.g. Human Resources" />
        </div>
        <div className="flex justify-end gap-2">
          <button type="button" onClick={() => navigate('/departments')} className="btn btn-ghost">Cancel</button>
          <button type="submit" disabled={loading} className="btn btn-teal">{loading ? 'Saving...' : (isEdit ? 'Update' : 'Create')}</button>
        </div>
      </form>
    </div>
  )
}

export default DepartmentForm
