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

export default function Salary() {
  const { salaries, loading, fetchSalaries, createSalary, updateSalary, deleteSalary } = useSalaryStore()
  const { employees, fetchEmployees } = useEmployeeStore()

  const [form, setForm] = useState({
    employee: '',
    grossSalary: '',
    totalDeduction: '',
    monthOfPayment: '',
    paymentDate: ''
  })

  const [editId, setEditId] = useState(null)
  const [error, setError] = useState(null)
  const [success, setSuccess] = 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(), fetchSalaries()])
      } catch (e) {
        setError(e.message)
      }
    }
    load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

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

  const rows = useMemo(() => salaries || [], [salaries])
  const netSalary = useMemo(() => {
    const gross = Number(form.grossSalary)
    const ded = Number(form.totalDeduction)
    if (Number.isNaN(gross) || Number.isNaN(ded)) return 0
    return gross - ded
  }, [form.grossSalary, form.totalDeduction])

  const validate = () => {
    if (!form.employee) return 'Employee is required'
    const gross = Number(form.grossSalary)
    const ded = Number(form.totalDeduction)
    if (Number.isNaN(gross) || gross <= 0) return 'Gross salary must be > 0'
    if (Number.isNaN(ded) || ded < 0) return 'Total deduction must be >= 0'
    if (ded > gross) return 'Deduction cannot exceed gross salary'
    if (!form.monthOfPayment.trim()) return 'Month of payment is required'
    const pd = new Date(form.paymentDate)
    if (Number.isNaN(pd.getTime())) return 'paymentDate must be a valid date'
    return null
  }

  const resetForm = () => {
    setEditId(null)
    setForm({
      employee: employees[0]?._id || '',
      grossSalary: '',
      totalDeduction: '',
      monthOfPayment: '',
      paymentDate: ''
    })
  }

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

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

    const payload = {
      employee: form.employee,
      grossSalary: Number(form.grossSalary),
      totalDeduction: Number(form.totalDeduction),
      monthOfPayment: form.monthOfPayment.trim(),
      paymentDate: form.paymentDate
      // netSalary is calculated by backend
    }

    try {
      if (editId) {
        await updateSalary(editId, payload)
        setSuccess('Salary updated successfully')
      } else {
        await createSalary(payload)
        setSuccess('Salary created successfully')
      }
      await fetchSalaries()
      resetForm()
    } catch (err) {
      setError(err.message)
    }
  }

  const startEdit = (s) => {
    setEditId(s._id)
    setForm({
      employee: s.employee?._id || s.employee || '',
      grossSalary: String(s.grossSalary ?? ''),
      totalDeduction: String(s.totalDeduction ?? ''),
      monthOfPayment: s.monthOfPayment || '',
      paymentDate: s.paymentDate ? new Date(s.paymentDate).toISOString().slice(0, 10) : ''
    })
  }

  const confirmDelete = async () => {
    if (!toDeleteId) return
    setConfirmLoading(true)
    try {
      await deleteSalary(toDeleteId)
      await fetchSalaries()
      setConfirmOpen(false)
      setToDeleteId(null)
      setSuccess('Salary 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">Salary</h1>
        <p className="mt-1 text-sm text-slate-500">Create and manage salary 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 Salary' : 'Create Salary'}</h2>

          <form className="mt-4 space-y-3" onSubmit={onSubmit}>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Employee</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.employee} onChange={(e) => setForm((s) => ({ ...s, employee: e.target.value }))}>
                {employees?.map((emp) => (
                  <option key={emp._id} value={emp._id}>
                    {emp.employeeNumber} - {emp.firstName} {emp.lastName}
                  </option>
                ))}
              </select>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Gross Salary</label>
                <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" type="number" min="0" step="0.01" value={form.grossSalary} onChange={(e) => setForm((s) => ({ ...s, grossSalary: e.target.value }))} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Total Deduction</label>
                <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-slate-400" type="number" min="0" step="0.01" value={form.totalDeduction} onChange={(e) => setForm((s) => ({ ...s, totalDeduction: e.target.value }))} />
              </div>
            </div>

            <div className="rounded-xl bg-slate-50 p-3">
              <div className="text-xs font-semibold text-slate-600">Net Salary (Calculated)</div>
              <div className="mt-1 text-xl font-extrabold text-slate-900">{Number.isFinite(netSalary) ? netSalary.toFixed(2) : '0.00'}</div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Month Of Payment</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.monthOfPayment} onChange={(e) => setForm((s) => ({ ...s, monthOfPayment: e.target.value }))} placeholder="e.g. May 2026" />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">Payment 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.paymentDate} onChange={(e) => setForm((s) => ({ ...s, paymentDate: e.target.value }))} />
              </div>
            </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">Salary Records</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 salary records 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">Employee</th>
                    <th className="py-2 pr-3">Gross</th>
                    <th className="py-2 pr-3">Deduction</th>
                    <th className="py-2 pr-3">Net</th>
                    <th className="py-2">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {rows.map((s) => (
                    <tr key={s._id} className="text-slate-800">
                      <td className="py-2 pr-3 font-medium">{s.employee?.firstName} {s.employee?.lastName}</td>
                      <td className="py-2 pr-3">{Number(s.grossSalary).toFixed(2)}</td>
                      <td className="py-2 pr-3">{Number(s.totalDeduction).toFixed(2)}</td>
                      <td className="py-2 pr-3 font-bold">{Number(s.netSalary).toFixed(2)}</td>
                      <td className="py-2">
                        <div className="flex flex-wrap gap-2">
                          <button type="button" onClick={() => startEdit(s)} 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(s._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 Salary"
        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 salary record?</div>
      </Modal>
    </div>
  )
}

