import { useEffect, useMemo, useState } from 'react'
import { useDepartmentStore } from '../store/departmentStore'
import Loading from '../components/Loading'

export default function Department() {
  const { departments, fetchDepartments, createDepartment, loading } = useDepartmentStore()
  const [departmentCode, setDepartmentCode] = useState('')
  const [departmentName, setDepartmentName] = useState('')
  const [error, setError] = useState(null)
  const [success, setSuccess] = useState(null)

  useEffect(() => {
    fetchDepartments().catch((e) => setError(e.message))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

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

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

    if (departmentCode.trim().length < 2) return setError('Department code is required (min 2 characters)')
    if (departmentName.trim().length < 2) return setError('Department name is required (min 2 characters)')

    try {
      await createDepartment({ departmentCode: departmentCode.trim(), departmentName: departmentName.trim() })
      setSuccess('Department created successfully')
      setDepartmentCode('')
      setDepartmentName('')
      await fetchDepartments()
    } catch (err) {
      setError(err.message)
    }
  }

  return (
    <div>
      <div className="mb-5">
        <h1 className="text-2xl font-bold text-slate-900">Department</h1>
        <p className="mt-1 text-sm text-slate-500">Create and manage departments.</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">Create Department</h2>
          <form className="mt-4 space-y-3" onSubmit={onSubmit}>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Department Code</label>
              <input
                value={departmentCode}
                onChange={(e) => setDepartmentCode(e.target.value)}
                className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Department Name</label>
              <input
                value={departmentName}
                onChange={(e) => setDepartmentName(e.target.value)}
                className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400"
              />
            </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>}

            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800 disabled:opacity-60"
            >
              {loading ? 'Creating...' : 'Create'}
            </button>
          </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">Departments</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 departments 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">Code</th>
                    <th className="py-2 pr-3">Name</th>
                    <th className="py-2">Created</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {rows.map((d) => (
                    <tr key={d._id} className="text-slate-800">
                      <td className="py-2 pr-3 font-medium">{d.departmentCode}</td>
                      <td className="py-2 pr-3">{d.departmentName}</td>
                      <td className="py-2">{new Date(d.createdAt).toLocaleDateString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </section>
      </div>
    </div>
  )
}

