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

function UserForm() {
  const { id } = useParams()
  const navigate = useNavigate()
  const isEdit = Boolean(id)
  const [formData, setFormData] = useState({ UserName: '', Password: '', Employee: '' })
  const [employees, setEmployees] = useState([])
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const empRes = await employeeAPI.getAll()
        setEmployees(empRes.data)
        if (isEdit) {
          const userRes = await userAPI.getById(id)
          setFormData({ UserName: userRes.data.UserName, Password: '', Employee: userRes.data.Employee?._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 {
      const data = { ...formData }
      if (isEdit && !data.Password) delete data.Password
      if (isEdit) await userAPI.update(id, data)
      else await userAPI.create(data)
      navigate('/users')
    } 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 User' : 'Add User'}</h1>
        <p className="page-subtitle">{isEdit ? 'Update user account' : 'Create a new user account'}</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">Username</label>
          <input type="text" name="UserName" value={formData.UserName} onChange={handleChange} required className="input" placeholder="Username" />
        </div>
        <div>
          <label className="label">Password {isEdit && <span className="text-xs text-slate-400 font-normal">(leave blank to keep current)</span>}</label>
          <input type="password" name="Password" value={formData.Password} onChange={handleChange} required={!isEdit} className="input" placeholder={isEdit ? 'New password (optional)' : 'Password'} />
        </div>
        <div>
          <label className="label">Employee</label>
          <select name="Employee" value={formData.Employee} onChange={handleChange} required className="input">
            <option value="">Select Employee</option>
            {employees.map(e => <option key={e._id} value={e._id}>{e.EmpFirstName} {e.EmpLastName} — {e.EmpEmail}</option>)}
          </select>
        </div>
        <div className="flex justify-end gap-2">
          <button type="button" onClick={() => navigate('/users')} 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 UserForm
