import { useEffect, useMemo, useState } from 'react'
import api from '../api/axios'
import Loading from '../components/Loading'
import { useEmployeeStore } from '../store/employeeStore'
import { useDepartmentStore } from '../store/departmentStore'
import Modal from '../components/Modal'

export default function Employee() {
  const { employees, loading, createEmployee, fetchEmployees, updateEmployee, deleteEmployee } = useEmployeeStore()
  const { departments, fetchDepartments } = useDepartmentStore()

  const [departmentOptions, setDepartmentOptions] = useState([])

  const [form, setForm] = useState({
    employeeNumber: '',
    firstName: '',
    lastName: '',
    address: '',
    position: '',
    telephone: '',
    gender: 'Male',
    hiredDate: '',
    department: ''
  })

  const [error, setError] = useState(null)
  const [success, setSuccess] = useState(null)

  const [editId, setEditId] = useState(null)

  const [confirmOpen, setConfirmOpen] = useState(false)
  const [toDeleteId, setToDeleteId] = useState(null)
  const [confirmLoading, setConfirmLoading] = useState(false)

  useEffect(() => {
    const load = async () => {
      try {
        await Promise.all([fetchEmployees(), fetchDepartments()])
      } catch (e) {
        setError(e.message)
      }
    }
    load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    setDepartmentOptions(departments || [])
  }, [departments])

  useEffect(() => {
    if (!departmentOptions.length) return
    if (!form.department) {
      setForm((s) => ({ ...s, department: departmentOptions[0]._id }))
    }
  }, [departmentOptions, form.department])

  const rows = useMemo(() => employees || [], [employees])

  const resetForm = () => {
    setEditId(null)
    setForm({
      employeeNumber: '',
      firstName: '',
      lastName: '',
      address: '',
      position: '',
      telephone: '',
      gender: 'Male',
      hiredDate: '',
      department: departmentOptions[0]?._id || ''
    })
  }

  const validate = () => {
    const req = ['employeeNumber', 'firstName', 'lastName', 'address', 'position', 'telephone', 'gender', 'hiredDate', 'department']
    for (const k of req) {
      if (!form[k] || (typeof form[k] === 'string' && form[k].toString().trim().length === 0)) return `${k} is required`
    }
    if (!['Male', 'Female', 'Other'].includes(form.gender)) return 'gender must be Male, Female, or Other'
    const d = new Date(form.hiredDate)
    if (Number.isNaN(d.getTime())) return 'hiredDate must be a valid date'
    return null
  }

  const onSubmit = async (e) => {
    e.preventDefault()
    setError(null)
    setSuccess(null)

    const errMsg = validate()
    if (errMsg) return setError(errMsg)

    const payload = {
      employeeNumber: form.employeeNumber.trim(),
      firstName: form.firstName.trim(),
      lastName: form.lastName.trim(),
      address: form.address.trim(),
      position: form.position.trim(),
      telephone: form.telephone.trim(),
      gender: form.gender,
      hiredDate: form.hiredDate,
      department: form.department
    }

    try {
      if (editId) {
        await updateEmployee(editId, payload)
        setSuccess('Employee updated successfully')
      } else {
        await createEmployee(payload)
        setSuccess('Employee created successfully')
      }
      await fetchEmployees()
      resetForm()
    } catch (err) {
      setError(err.message)
    }
  }

  const startEdit = (emp) => {
    setEditId(emp._id)
    setForm({
      employeeNumber: emp.employeeNumber || '',
      firstName: emp.firstName || '',
      lastName: emp.lastName || '',
      address: emp.address || '',
      position: emp.position || '',
      telephone: emp.telephone || '',
      gender: emp.gender || 'Male',
      hiredDate: emp.hiredDate ? new Date(emp.hiredDate).toISOString().slice(0, 10) : '',
      department: emp.department?._id || emp.department || ''
    })
  }

  const confirmDelete = async () => {
    if (!toDeleteId) return
    setConfirmLoading(true)
    try {
      await deleteEmployee(toDeleteId)
      await fetchEmployees()
      setConfirmOpen(false)
      setToDeleteId(null)
      setSuccess('Employee deleted successfully')
    } catch (err) {
      setError(err.message)
    } finally {
      setConfirmLoading(false)
    }
  }

  return (
    <div>
      <div className="mb-5">
        <h1 className="text-2xl font-bold text-slate-900">Employee</h1>
        <p className="mt-1 text-sm text-slate-500">Create employees and manage employee records.</p>
      </div>

      <div className="grid gap-4 lg:grid-cols-5">
        <section className="lg:col-span-2 rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200">
          <h2 className="text-lg font-semibold text-slate-900">{editId ? 'Update Employee' : 'Create Employee'}</h2>
          <form className="mt-4 space-y-3" onSubmit={onSubmit}>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Employee Number</label>
              <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.employeeNumber} onChange={(e) => setForm((s) => ({ ...s, employeeNumber: e.target.value }))} />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">First Name</label>
                <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.firstName} onChange={(e) => setForm((s) => ({ ...s, firstName: e.target.value }))} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Last Name</label>
                <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.lastName} onChange={(e) => setForm((s) => ({ ...s, lastName: e.target.value }))} />
              </div>
            </div>

            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Address</label>
              <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.address} onChange={(e) => setForm((s) => ({ ...s, address: e.target.value }))} />
            </div>

            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Position</label>
              <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.position} onChange={(e) => setForm((s) => ({ ...s, position: e.target.value }))} />
            </div>

            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Telephone</label>
              <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.telephone} onChange={(e) => setForm((s) => ({ ...s, telephone: e.target.value }))} />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Gender</label>
                <select className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.gender} onChange={(e) => setForm((s) => ({ ...s, gender: e.target.value }))}>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                  <option value="Other">Other</option>
                </select>
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Hired Date</label>
                <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" type="date" value={form.hiredDate} onChange={(e) => setForm((s) => ({ ...s, hiredDate: e.target.value }))} />
              </div>
            </div>

            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Department</label>
              <select className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" value={form.department} onChange={(e) => setForm((s) => ({ ...s, department: e.target.value }))}>
                {departmentOptions.map((d) => (
                  <option key={d._id} value={d._id}>
                    {d.departmentCode} - {d.departmentName}
                  </option>
                ))}
              </select>
            </div>

            {error && <div className="rounded-lg bg-red-50 p-3 text-sm text-red-700">{error}</div>}
            {success && <div className="rounded-lg bg-green-50 p-3 text-sm text-green-700">{success}</div>}

            <div className="flex gap-3">
              <button type="submit" disabled={loading} className="flex-1 rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800 disabled:opacity-60">
                {loading ? 'Saving...' : editId ? 'Update' : 'Create'}
              </button>
              <button type="button" onClick={resetForm} disabled={loading} className="rounded-xl bg-slate-100 px-4 py-2.5 text-sm font-semibold text-slate-800 hover:bg-slate-200 disabled:opacity-60">
                Reset
              </button>
            </div>
          </form>
        </section>

        <section className="lg:col-span-3 rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-slate-900">Employees</h2>
            {loading ? <Loading label="Loading" /> : null}
          </div>

          <div className="mt-4 overflow-x-auto">
            {rows.length === 0 && !loading ? (
              <div className="rounded-lg bg-slate-50 p-4 text-sm text-slate-600">No employees found.</div>
            ) : (
              <table className="min-w-full text-left text-sm">
                <thead className="text-xs uppercase text-slate-500">
                  <tr>
                    <th className="py-2 pr-3">#</th>
                    <th className="py-2 pr-3">Name</th>
                    <th className="py-2 pr-3">Position</th>
                    <th className="py-2 pr-3">Department</th>
                    <th className="py-2">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {rows.map((emp) => (
                    <tr key={emp._id} className="text-slate-800">
                      <td className="py-2 pr-3 font-medium">{emp.employeeNumber}</td>
                      <td className="py-2 pr-3">{emp.firstName} {emp.lastName}</td>
                      <td className="py-2 pr-3">{emp.position}</td>
                      <td className="py-2 pr-3">{emp.department?.departmentCode || ''}</td>
                      <td className="py-2">
                        <div className="flex flex-wrap gap-2">
                          <button
                            type="button"
                            onClick={() => startEdit(emp)}
                            className="rounded-lg bg-slate-900 px-3 py-1.5 text-xs font-semibold text-white hover:bg-slate-800"
                          >
                            Edit
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              setToDeleteId(emp._id)
                              setConfirmOpen(true)
                            }}
                            className="rounded-lg bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-700"
                          >
                            Delete
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </section>
      </div>

      <Modal
        open={confirmOpen}
        title="Delete Employee"
        danger
        confirmLabel="Delete"
        loading={confirmLoading}
        onClose={() => {
          if (!confirmLoading) {
            setConfirmOpen(false)
            setToDeleteId(null)
          }
        }}
        onConfirm={confirmDelete}
      >
        <div className="text-sm text-slate-700">This action cannot be undone. Are you sure you want to delete this employee?</div>
      </Modal>
    </div>
  )
}

