'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { TableSkeleton, StatCardSkeleton } from '@/components/Skeletons';
import Modal from '@/components/Modal';

type LeaveReq = {
  id: number; type: string; startDate: string; endDate: string; daysCount: number; reason: string | null;
  status: string; createdAt: string;
  employee: { id: number; name: string; employeeNo: string; roleTitle: string };
  approvedBy: { id: number; name: string } | null;
};
type Employee = { id: number; name: string; employeeNo: string };
const TYPE_LABEL: Record<string, string> = { ANNUAL: 'Annual', SICK: 'Sick', UNPAID: 'Unpaid', COMPASSIONATE: 'Compassionate' };
const BADGE: Record<string, string> = { PENDING: 'bg-amber-100 text-amber-700', APPROVED: 'bg-emerald-100 text-emerald-700', REJECTED: 'bg-red-100 text-red-700' };
const emptyForm = { employeeId: '', type: 'ANNUAL', startDate: '', endDate: '', reason: '' };

export default function LeavePage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [requests, setRequests] = useState<LeaveReq[]>([]);
  const [funnel, setFunnel] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showForm, setShowForm] = useState(false);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/leave', accessToken, appSecretProof);
      setRequests(d.requests || []);
      setFunnel(d.funnel || {});
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function openForm() {
    setShowForm(true);
    if (!accessToken || !appSecretProof) return;
    try { const d = await adminApiFetch('/admin/leave/lookups/employees', accessToken, appSecretProof); setEmployees(d.employees || []); }
    catch { show('error', 'Could not load employees.'); }
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.employeeId || !form.startDate || !form.endDate) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/leave', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ employeeId: Number(form.employeeId), type: form.type, startDate: form.startDate, endDate: form.endDate, reason: form.reason || undefined }),
      });
      show('success', 'Leave request submitted.');
      setForm(emptyForm); setShowForm(false);
      load();
    } catch { show('error', 'Could not submit that request.'); }
    finally { setSaving(false); }
  }

  async function decide(reqItem: LeaveReq, status: 'APPROVED' | 'REJECTED') {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/leave/${reqItem.id}/decision`, accessToken, appSecretProof, {
        method: 'PATCH', body: JSON.stringify({ status, approverEmployeeId: reqItem.employee.id }),
      });
      show('success', status === 'APPROVED' ? 'Leave approved.' : 'Leave rejected.');
      load();
    } catch { show('error', 'Could not update that request.'); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-xl font-bold">Leave Management &bull; admin.lussavara.co.tz</h1>
        <button onClick={openForm} className="bg-brand-red text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03]">+ New Leave Request</button>
      </div>

      {loading ? <StatCardSkeleton count={3} /> : (
        <div className="grid grid-cols-3 gap-3">
          <div className="bg-amber-50 border border-amber-200 rounded-xl p-4"><p className="text-[10px] uppercase text-amber-600">Pending</p><p className="text-lg font-bold text-amber-700">{funnel.PENDING ?? 0}</p></div>
          <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4"><p className="text-[10px] uppercase text-emerald-600">Approved</p><p className="text-lg font-bold text-emerald-700">{funnel.APPROVED ?? 0}</p></div>
          <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-[10px] uppercase text-gray-400">Rejected</p><p className="text-lg font-bold">{funnel.REJECTED ?? 0}</p></div>
        </div>
      )}

      {loading ? <TableSkeleton rows={6} cols={6} /> : (
        <div className="bg-white rounded-xl border border-brand-border overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg"><tr>
              <th className="p-3 text-left">Employee</th><th className="p-3 text-left">Type</th>
              <th className="p-3 text-left">Dates</th><th className="p-3 text-left">Days</th>
              <th className="p-3 text-left">Reason</th><th className="p-3 text-left">Status</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {requests.map((r) => (
                <tr key={r.id} className="border-t border-brand-border hover:bg-brand-bg">
                  <td className="p-3 font-semibold">{r.employee.name}<br /><span className="text-gray-400 font-normal">{r.employee.roleTitle}</span></td>
                  <td className="p-3">{TYPE_LABEL[r.type]}</td>
                  <td className="p-3">{new Date(r.startDate).toLocaleDateString()} – {new Date(r.endDate).toLocaleDateString()}</td>
                  <td className="p-3">{r.daysCount}</td>
                  <td className="p-3 text-gray-500">{r.reason || '—'}</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${BADGE[r.status]}`}>{r.status}</span></td>
                  <td className="p-3 space-x-2">
                    {r.status === 'PENDING' && <><button onClick={() => decide(r, 'APPROVED')} className="text-emerald-600 font-semibold">Approve</button><button onClick={() => decide(r, 'REJECTED')} className="text-brand-red">Reject</button></>}
                  </td>
                </tr>
              ))}
              {requests.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-gray-400">No leave requests yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="New Leave Request" onClose={() => setShowForm(false)}>
          <form onSubmit={submit} className="space-y-2">
            <select required value={form.employeeId} onChange={(e) => setForm({ ...form, employeeId: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
              <option value="">Select employee…</option>
              {employees.map((e) => <option key={e.id} value={e.id}>{e.name} ({e.employeeNo})</option>)}
            </select>
            <select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
              {Object.entries(TYPE_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
            <div className="grid grid-cols-2 gap-2">
              <div><label className="text-[10px] text-gray-400 uppercase">Start</label><input required type="date" value={form.startDate} onChange={(e) => setForm({ ...form, startDate: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" /></div>
              <div><label className="text-[10px] text-gray-400 uppercase">End</label><input required type="date" value={form.endDate} onChange={(e) => setForm({ ...form, endDate: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" /></div>
            </div>
            <textarea placeholder="Reason (optional)" value={form.reason} onChange={(e) => setForm({ ...form, reason: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <button disabled={saving} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Submitting…' : 'Submit Request'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
