"use client";

import { useEffect, useState, FormEvent } from "react";
import {
  PageHeader, PageLoader, EmptyState, Modal, Badge, TableShell,
  fmtKes, inputCls, btnPrimary, btnGhost, btnDanger, Field, Spinner,
} from "@/components/ui";

interface Employee {
  id: number;
  staffNo: string;
  fullName: string;
  email: string;
  phone: string;
  nationalId: string;
  kraPin: string;
  nssfNo: string;
  shifNo: string;
  department: string;
  position: string;
  employmentType: string;
  basicSalary: number;
  allowances: number;
  bankName: string;
  bankAccount: string;
  hireDate: string;
  status: string;
}

const blank: Omit<Employee, "id"> = {
  staffNo: "", fullName: "", email: "", phone: "", nationalId: "", kraPin: "",
  nssfNo: "", shifNo: "", department: "Engineering", position: "", employmentType: "Permanent",
  basicSalary: 0, allowances: 0, bankName: "", bankAccount: "", hireDate: "", status: "active",
};

export default function EmployeesPage() {
  const [rows, setRows] = useState<Employee[] | null>(null);
  const [modal, setModal] = useState<null | { mode: "create" } | { mode: "edit"; row: Employee }>(null);
  const [form, setForm] = useState(blank);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");

  const load = () => fetch("/api/employees").then((r) => r.json()).then(setRows);
  useEffect(() => { load(); }, []);

  const openCreate = () => { setForm(blank); setError(""); setModal({ mode: "create" }); };
  const openEdit = (row: Employee) => { setForm({ ...row }); setError(""); setModal({ mode: "edit", row }); };

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    const editing = modal?.mode === "edit" ? modal.row : null;
    try {
      const res = await fetch(editing ? `/api/employees/${editing.id}` : "/api/employees", {
        method: editing ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to save");
      setRows((prev) =>
        editing
          ? (prev ?? []).map((r) => (r.id === editing.id ? data : r))
          : [data, ...(prev ?? [])],
      );
      setModal(null);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setSaving(false);
    }
  };

  const remove = async (row: Employee) => {
    if (!confirm(`Delete ${row.fullName}? Their payslips and leave records will also be removed.`)) return;
    const prev = rows;
    setRows((r) => (r ?? []).filter((x) => x.id !== row.id)); // optimistic
    const res = await fetch(`/api/employees/${row.id}`, { method: "DELETE" });
    if (!res.ok) setRows(prev); // rollback
  };

  const filtered = (rows ?? []).filter(
    (r) =>
      r.fullName.toLowerCase().includes(search.toLowerCase()) ||
      r.department.toLowerCase().includes(search.toLowerCase()) ||
      r.staffNo.toLowerCase().includes(search.toLowerCase()),
  );

  return (
    <div>
      <PageHeader
        title="Employees"
        subtitle="Manage your team, contracts and compensation"
        action={<button onClick={openCreate} className={btnPrimary}>+ Add employee</button>}
      />

      <div className="mb-4">
        <input
          className={`${inputCls} sm:max-w-xs`}
          placeholder="Search by name, staff no or department…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {!rows ? (
        <PageLoader label="Loading employees…" />
      ) : filtered.length === 0 ? (
        <EmptyState
          icon="👥"
          title={search ? "No matching employees" : "No employees yet"}
          description={search ? "Try a different search term." : "Add your first employee to start running payroll."}
          action={!search && <button onClick={openCreate} className={btnPrimary}>+ Add employee</button>}
        />
      ) : (
        <TableShell head={["Employee", "Department", "Position", "Gross Pay", "Type", "Status", ""]}>
          {filtered.map((r) => (
            <tr key={r.id} className="hover:bg-slate-50">
              <td className="px-4 py-3">
                <p className="font-medium text-slate-900">{r.fullName}</p>
                <p className="text-xs text-slate-500">{r.staffNo} · {r.email}</p>
              </td>
              <td className="px-4 py-3 text-slate-600">{r.department}</td>
              <td className="max-w-[160px] truncate px-4 py-3 text-slate-600">{r.position}</td>
              <td className="whitespace-nowrap px-4 py-3 font-medium">{fmtKes(r.basicSalary + r.allowances)}</td>
              <td className="px-4 py-3 text-slate-600">{r.employmentType}</td>
              <td className="px-4 py-3"><Badge value={r.status} /></td>
              <td className="whitespace-nowrap px-4 py-3 text-right">
                <div className="flex justify-end gap-2">
                  <button onClick={() => openEdit(r)} className={btnGhost}>Edit</button>
                  <button onClick={() => remove(r)} className={btnDanger}>Delete</button>
                </div>
              </td>
            </tr>
          ))}
        </TableShell>
      )}

      <Modal open={!!modal} onClose={() => setModal(null)} title={modal?.mode === "edit" ? "Edit employee" : "Add employee"} wide>
        <form onSubmit={submit}>
          {error && <div className="mb-4 rounded-lg bg-rose-50 px-3 py-2 text-sm text-rose-700">{error}</div>}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <Field label="Full name *"><input className={inputCls} required value={form.fullName} onChange={(e) => setForm({ ...form, fullName: e.target.value })} /></Field>
            <Field label="Email *"><input type="email" className={inputCls} required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></Field>
            <Field label="Phone"><input className={inputCls} value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} /></Field>
            <Field label="Staff No"><input className={inputCls} placeholder="Auto if blank" value={form.staffNo} onChange={(e) => setForm({ ...form, staffNo: e.target.value })} /></Field>
            <Field label="National ID"><input className={inputCls} value={form.nationalId} onChange={(e) => setForm({ ...form, nationalId: e.target.value })} /></Field>
            <Field label="KRA PIN"><input className={inputCls} value={form.kraPin} onChange={(e) => setForm({ ...form, kraPin: e.target.value })} /></Field>
            <Field label="NSSF No"><input className={inputCls} value={form.nssfNo} onChange={(e) => setForm({ ...form, nssfNo: e.target.value })} /></Field>
            <Field label="SHIF No"><input className={inputCls} value={form.shifNo} onChange={(e) => setForm({ ...form, shifNo: e.target.value })} /></Field>
            <Field label="Department">
              <select className={inputCls} value={form.department} onChange={(e) => setForm({ ...form, department: e.target.value })}>
                {["Engineering", "Finance", "Human Resources", "Sales", "Support", "Design", "General"].map((d) => <option key={d}>{d}</option>)}
              </select>
            </Field>
            <Field label="Position"><input className={inputCls} value={form.position} onChange={(e) => setForm({ ...form, position: e.target.value })} /></Field>
            <Field label="Employment type">
              <select className={inputCls} value={form.employmentType} onChange={(e) => setForm({ ...form, employmentType: e.target.value })}>
                {["Permanent", "Contract", "Casual", "Intern"].map((d) => <option key={d}>{d}</option>)}
              </select>
            </Field>
            <Field label="Hire date"><input type="date" className={inputCls} value={form.hireDate} onChange={(e) => setForm({ ...form, hireDate: e.target.value })} /></Field>
            <Field label="Basic salary (KES) *"><input type="number" min={0} className={inputCls} required value={form.basicSalary} onChange={(e) => setForm({ ...form, basicSalary: Number(e.target.value) })} /></Field>
            <Field label="Allowances (KES)"><input type="number" min={0} className={inputCls} value={form.allowances} onChange={(e) => setForm({ ...form, allowances: Number(e.target.value) })} /></Field>
            <Field label="Status">
              <select className={inputCls} value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
            </Field>
            <Field label="Bank name"><input className={inputCls} value={form.bankName} onChange={(e) => setForm({ ...form, bankName: e.target.value })} /></Field>
            <Field label="Bank account"><input className={inputCls} value={form.bankAccount} onChange={(e) => setForm({ ...form, bankAccount: e.target.value })} /></Field>
          </div>
          <div className="mt-6 flex justify-end gap-2">
            <button type="button" onClick={() => setModal(null)} className={btnGhost}>Cancel</button>
            <button type="submit" disabled={saving} className={btnPrimary}>
              {saving && <Spinner className="h-4 w-4 text-white" />}
              {saving ? "Saving…" : "Save employee"}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
