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

function PositionForm() {
  const { id } = useParams()
  const navigate = useNavigate()
  const isEdit = Boolean(id)
  const [formData, setFormData] = useState({ PosName: '', RequiredQualification: '' })
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (isEdit) {
      positionAPI.getById(id).then(res => setFormData({ PosName: res.data.PosName, RequiredQualification: res.data.RequiredQualification || '' })).catch(console.error)
    }
  }, [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 positionAPI.update(id, formData)
      else await positionAPI.create(formData)
      navigate('/positions')
    } 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 Position' : 'Add Position'}</h1>
        <p className="page-subtitle">{isEdit ? 'Update position details' : 'Create a new position'}</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">Position Name</label>
          <input type="text" name="PosName" value={formData.PosName} onChange={handleChange} required className="input" placeholder="e.g. Software Engineer" />
        </div>
        <div>
          <label className="label">Required Qualification</label>
          <input type="text" name="RequiredQualification" value={formData.RequiredQualification} onChange={handleChange} className="input" placeholder="e.g. Bachelor's Degree" />
        </div>
        <div className="flex justify-end gap-2">
          <button type="button" onClick={() => navigate('/positions')} className="btn btn-ghost">Cancel</button>
          <button type="submit" disabled={loading} className="btn btn-amber">{loading ? 'Saving...' : (isEdit ? 'Update' : 'Create')}</button>
        </div>
      </form>
    </div>
  )
}

export default PositionForm
