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

const statusOptions = ['Active', 'On Leave', 'Left', 'Blacklisted', 'Deceased', 'On Mission']

function EmployeeForm() {
  const { id } = useParams()
  const navigate = useNavigate()
  const isEdit = Boolean(id)

  const [formData, setFormData] = useState({
    EmpFirstName: '', EmpLastName: '', EmpGender: 'Male',
    EmpDateOfBirth: '', EmpEmail: '', EmpTelephone: '',
    EmpAddress: '', EmpHireDate: '', EmpStatus: 'Active',
    Department: '', Position: ''
  })
  const [departments, setDepartments] = useState([])
  const [positions, setPositions] = useState([])
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [depRes, posRes] = await Promise.all([departmentAPI.getAll(), positionAPI.getAll()])
        setDepartments(depRes.data)
        setPositions(posRes.data)
        if (isEdit) {
          const empRes = await employeeAPI.getById(id)
          const emp = empRes.data
          setFormData({
            EmpFirstName: emp.EmpFirstName, EmpLastName: emp.EmpLastName,
            EmpGender: emp.EmpGender,
            EmpDateOfBirth: emp.EmpDateOfBirth ? emp.EmpDateOfBirth.split('T')[0] : '',
            EmpEmail: emp.EmpEmail, EmpTelephone: emp.EmpTelephone,
            EmpAddress: emp.EmpAddress,
            EmpHireDate: emp.EmpHireDate ? emp.EmpHireDate.split('T')[0] : '',
            EmpStatus: emp.EmpStatus,
            Department: emp.Department?._id || '',
            Position: emp.Position?._id || ''
          })
        }
      } catch (error) {
        console.error('Failed to load data:', error)
      }
    }
    fetchData()
  }, [id, isEdit])

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value })
  }

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

  const fieldClass = "input"
  const groupClass = "grid grid-cols-1 md:grid-cols-2 gap-4"

  return (
    <div className="max-w-3xl mx-auto space-y-4">
      <div>
        <h1 className="page-title">{isEdit ? 'Edit Employee' : 'Add Employee'}</h1>
        <p className="page-subtitle">{isEdit ? 'Update employee information' : 'Register a new employee'}</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 divide-y divide-slate-200">
        <div className="px-4 py-3 bg-slate-50 text-sm font-semibold text-slate-600">Personal Information</div>
        <div className="p-4 space-y-4">
          <div className={groupClass}>
            <div><label className="label">First Name</label><input type="text" className={fieldClass} name="EmpFirstName" value={formData.EmpFirstName} onChange={handleChange} required /></div>
            <div><label className="label">Last Name</label><input type="text" className={fieldClass} name="EmpLastName" value={formData.EmpLastName} onChange={handleChange} required /></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div><label className="label">Gender</label><select className={fieldClass} name="EmpGender" value={formData.EmpGender} onChange={handleChange} required><option>Male</option><option>Female</option><option>Other</option></select></div>
            <div><label className="label">Date of Birth</label><input type="date" className={fieldClass} name="EmpDateOfBirth" value={formData.EmpDateOfBirth} onChange={handleChange} required /></div>
            <div><label className="label">Hire Date</label><input type="date" className={fieldClass} name="EmpHireDate" value={formData.EmpHireDate} onChange={handleChange} required /></div>
          </div>
        </div>

        <div className="px-4 py-3 bg-slate-50 text-sm font-semibold text-slate-600">Contact Details</div>
        <div className="p-4 space-y-4">
          <div><label className="label">Email</label><input type="email" className={fieldClass} name="EmpEmail" value={formData.EmpEmail} onChange={handleChange} required /></div>
          <div className={groupClass}>
            <div><label className="label">Telephone</label><input type="text" className={fieldClass} name="EmpTelephone" value={formData.EmpTelephone} onChange={handleChange} required /></div>
            <div><label className="label">Address</label><input type="text" className={fieldClass} name="EmpAddress" value={formData.EmpAddress} onChange={handleChange} required /></div>
          </div>
        </div>

        <div className="px-4 py-3 bg-slate-50 text-sm font-semibold text-slate-600">Employment Details</div>
        <div className="p-4 space-y-4">
          <div className={groupClass}>
            <div><label className="label">Department</label><select className={fieldClass} name="Department" value={formData.Department} onChange={handleChange}><option value="">— Select —</option>{departments.map(d => <option key={d._id} value={d._id}>{d.DepartName}</option>)}</select></div>
            <div><label className="label">Position</label><select className={fieldClass} name="Position" value={formData.Position} onChange={handleChange}><option value="">— Select —</option>{positions.map(p => <option key={p._id} value={p._id}>{p.PosName}</option>)}</select></div>
          </div>
          <div><label className="label">Status</label><select className={fieldClass} name="EmpStatus" value={formData.EmpStatus} onChange={handleChange} required>{statusOptions.map(s => <option key={s} value={s}>{s}</option>)}</select></div>
        </div>

        <div className="px-4 py-3 bg-slate-50 flex items-center justify-end gap-2">
          <button type="button" onClick={() => navigate('/employees')} className="btn btn-ghost">Cancel</button>
          <button type="submit" disabled={loading} className="btn btn-teal">{loading ? 'Saving...' : (isEdit ? 'Update' : 'Save')}</button>
        </div>
      </form>
    </div>
  )
}

export default EmployeeForm
