import { useEffect, useState } from 'react';
import { Plus, Search, Pencil, Trash2, User } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../api/axios';
import Modal from '../components/Modal';
import { formatCurrency, roleLabels, statusColors } from '../utils/format';

const emptyForm = {
  employeeId: '',
  firstName: '',
  lastName: '',
  email: '',
  phone: '',
  role: 'teacher',
  department: '',
  joinDate: new Date().toISOString().slice(0, 10),
  status: 'active',
  bankAccount: '',
  salary: { basic: 0, housing: 0, transport: 0, medical: 0, bonus: 0 },
  deductions: { tax: 0, pension: 0, insurance: 0, loan: 0 },
};

export default function Employees() {
  const [employees, setEmployees] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [search, setSearch] = useState('');
  const [modal, setModal] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [editId, setEditId] = useState(null);
  const [loading, setLoading] = useState(true);

  const load = () => {
    Promise.all([
      api.get('/employees', { params: { search: search || undefined } }),
      api.get('/departments'),
    ]).then(([empRes, deptRes]) => {
      setEmployees(empRes.data);
      setDepartments(deptRes.data);
    }).finally(() => setLoading(false));
  };

  useEffect(() => {
    const t = setTimeout(load, 300);
    return () => clearTimeout(t);
  }, [search]);

  const openCreate = () => {
    setForm({ ...emptyForm, department: departments[0]?._id || '' });
    setEditId(null);
    setModal(true);
  };

  const openEdit = (emp) => {
    setForm({
      ...emp,
      department: emp.department?._id || emp.department,
      joinDate: emp.joinDate?.slice(0, 10),
    });
    setEditId(emp._id);
    setModal(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await api.put(`/employees/${editId}`, form);
        toast.success('Employee updated');
      } else {
        await api.post('/employees', form);
        toast.success('Employee added');
      }
      setModal(false);
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Error saving');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this employee?')) return;
    try {
      await api.delete(`/employees/${id}`);
      toast.success('Deleted');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Delete failed');
    }
  };

  const updateNested = (section, field, value) => {
    setForm((f) => ({
      ...f,
      [section]: { ...f[section], [field]: Number(value) || 0 },
    }));
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-display text-2xl font-bold text-slate-800">Employees</h1>
          <p className="text-slate-500">Manage school staff and salary structures</p>
        </div>
        <button onClick={openCreate} className="btn-primary">
          <Plus className="h-4 w-4" /> Add Employee
        </button>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
        <input
          className="input-field pl-10"
          placeholder="Search by name, ID, email..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <div className="card overflow-hidden p-0">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50">
              <tr className="text-left text-slate-500">
                <th className="px-6 py-4 font-medium">Employee</th>
                <th className="px-6 py-4 font-medium">Role</th>
                <th className="px-6 py-4 font-medium">Department</th>
                <th className="px-6 py-4 font-medium">Net Salary</th>
                <th className="px-6 py-4 font-medium">Status</th>
                <th className="px-6 py-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={6} className="px-6 py-12 text-center text-slate-400">Loading...</td></tr>
              ) : employees.length === 0 ? (
                <tr><td colSpan={6} className="px-6 py-12 text-center text-slate-400">No employees found</td></tr>
              ) : (
                employees.map((emp) => (
                  <tr key={emp._id} className="border-t border-slate-100 hover:bg-slate-50/50">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="flex h-10 w-10 items-center justify-center rounded-full bg-brand-100 text-brand-600">
                          <User className="h-5 w-5" />
                        </div>
                        <div>
                          <p className="font-medium text-slate-800">{emp.firstName} {emp.lastName}</p>
                          <p className="text-xs text-slate-400">{emp.employeeId} · {emp.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">{roleLabels[emp.role] || emp.role}</td>
                    <td className="px-6 py-4">{emp.department?.name || '—'}</td>
                    <td className="px-6 py-4 font-semibold text-emerald-600">{formatCurrency(emp.netSalary)}</td>
                    <td className="px-6 py-4">
                      <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium capitalize ${statusColors[emp.status]}`}>
                        {emp.status?.replace('_', ' ')}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex gap-2">
                        <button onClick={() => openEdit(emp)} className="rounded-lg p-2 text-slate-500 hover:bg-brand-50 hover:text-brand-600">
                          <Pencil className="h-4 w-4" />
                        </button>
                        <button onClick={() => handleDelete(emp._id)} className="rounded-lg p-2 text-slate-500 hover:bg-red-50 hover:text-red-600">
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title={editId ? 'Edit Employee' : 'Add Employee'} wide>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1 block text-sm font-medium">Employee ID</label>
              <input className="input-field" value={form.employeeId} onChange={(e) => setForm({ ...form, employeeId: e.target.value })} required disabled={!!editId} />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Join Date</label>
              <input type="date" className="input-field" value={form.joinDate} onChange={(e) => setForm({ ...form, joinDate: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">First Name</label>
              <input className="input-field" value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Last Name</label>
              <input className="input-field" value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Email</label>
              <input type="email" className="input-field" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Phone</label>
              <input className="input-field" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Role</label>
              <select className="input-field" value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
                {Object.entries(roleLabels).map(([k, v]) => (
                  <option key={k} value={k}>{v}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Department</label>
              <select className="input-field" value={form.department} onChange={(e) => setForm({ ...form, department: e.target.value })} required>
                <option value="">Select...</option>
                {departments.map((d) => (
                  <option key={d._id} value={d._id}>{d.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Status</label>
              <select className="input-field" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                <option value="active">Active</option>
                <option value="on_leave">On Leave</option>
                <option value="terminated">Terminated</option>
              </select>
            </div>
          </div>

          <h4 className="font-semibold text-slate-700 pt-2">Salary & Allowances</h4>
          <div className="grid gap-3 grid-cols-2 sm:grid-cols-5">
            {['basic', 'housing', 'transport', 'medical', 'bonus'].map((f) => (
              <div key={f}>
                <label className="mb-1 block text-xs font-medium capitalize text-slate-500">{f}</label>
                <input type="number" className="input-field" value={form.salary[f]} onChange={(e) => updateNested('salary', f, e.target.value)} />
              </div>
            ))}
          </div>

          <h4 className="font-semibold text-slate-700">Deductions</h4>
          <div className="grid gap-3 grid-cols-2 sm:grid-cols-4">
            {['tax', 'pension', 'insurance', 'loan'].map((f) => (
              <div key={f}>
                <label className="mb-1 block text-xs font-medium capitalize text-slate-500">{f}</label>
                <input type="number" className="input-field" value={form.deductions[f]} onChange={(e) => updateNested('deductions', f, e.target.value)} />
              </div>
            ))}
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <button type="button" onClick={() => setModal(false)} className="btn-secondary">Cancel</button>
            <button type="submit" className="btn-primary">{editId ? 'Update' : 'Create'}</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
