'use client';

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

type Claim = {
  id: number; claimNo: string; category: string; amountTzs: string; description: string | null;
  receiptUrl: string | null; status: string; rejectionReason: string | null; createdAt: string;
  employee: { id: number; name: string }; approvedBy: { id: number; name: string } | null;
};
type Employee = { id: number; name: string };
const emptyForm = { employeeId: '', category: 'Fuel', amountTzs: '', description: '' };
const BADGE: Record<string, string> = { PENDING: 'bg-amber-100 text-amber-700', APPROVED: 'bg-blue-100 text-blue-700', REJECTED: 'bg-red-100 text-red-700', PAID: 'bg-emerald-100 text-emerald-700' };

export default function ExpenseClaimsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [claims, setClaims] = useState<Claim[]>([]);
  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 [receipt, setReceipt] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);
  const [rejectId, setRejectId] = useState<number | null>(null);
  const [rejectReason, setRejectReason] = useState('');

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/expense-claims', accessToken, appSecretProof);
      setClaims(d.claims || []);
      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/expense-claims/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.amountTzs) return;
    setSaving(true);
    try {
      let receiptUrl: string | undefined;
      if (receipt) receiptUrl = (await adminApiUploadFile('/admin/expense-claims/upload-receipt', accessToken, appSecretProof, receipt, 'receipt')).url;
      await adminApiFetch('/admin/expense-claims', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ employeeId: Number(form.employeeId), category: form.category, amountTzs: Number(form.amountTzs), description: form.description || undefined, receiptUrl }),
      });
      show('success', 'Claim submitted.');
      setForm(emptyForm); setReceipt(null); setShowForm(false);
      load();
    } catch { show('error', 'Could not submit that claim.'); }
    finally { setSaving(false); }
  }

  async function approve(claim: Claim) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/expense-claims/${claim.id}/decision`, accessToken, appSecretProof, {
        method: 'PATCH', body: JSON.stringify({ status: 'APPROVED', approverEmployeeId: claim.employee.id }),
      });
      show('success', 'Claim approved.');
      load();
    } catch { show('error', 'Could not approve that claim.'); }
  }

  async function submitRejection(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !rejectId) return;
    const claim = claims.find((c) => c.id === rejectId);
    if (!claim) return;
    try {
      await adminApiFetch(`/admin/expense-claims/${rejectId}/decision`, accessToken, appSecretProof, {
        method: 'PATCH', body: JSON.stringify({ status: 'REJECTED', approverEmployeeId: claim.employee.id, rejectionReason: rejectReason || undefined }),
      });
      show('success', 'Claim rejected.');
      setRejectId(null); setRejectReason('');
      load();
    } catch { show('error', 'Could not reject that claim.'); }
  }

  async function markPaid(id: number) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/expense-claims/${id}/paid`, accessToken, appSecretProof, { method: 'PATCH' });
      show('success', 'Marked paid.');
      load();
    } catch { show('error', 'Could not update that claim.'); }
  }

  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">Expense Claims &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]">+ Submit Claim</button>
      </div>

      {loading ? <StatCardSkeleton count={4} /> : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {['PENDING', 'APPROVED', 'REJECTED', 'PAID'].map((s) => (
            <div key={s} className="bg-white border border-brand-border rounded-xl p-4"><p className="text-[10px] uppercase text-gray-400">{s}</p><p className="text-lg font-bold">{funnel[s] ?? 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">Claim No</th><th className="p-3 text-left">Employee</th>
              <th className="p-3 text-left">Category</th><th className="p-3 text-left">Amount</th>
              <th className="p-3 text-left">Receipt</th><th className="p-3 text-left">Status</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {claims.map((c) => (
                <tr key={c.id} className="border-t border-brand-border hover:bg-brand-bg">
                  <td className="p-3 font-semibold">{c.claimNo}</td>
                  <td className="p-3">{c.employee.name}</td>
                  <td className="p-3">{c.category}<br /><span className="text-gray-400">{c.description}</span></td>
                  <td className="p-3">TZS {Number(c.amountTzs).toLocaleString()}</td>
                  <td className="p-3">{c.receiptUrl ? <a href={c.receiptUrl} target="_blank" rel="noreferrer" className="text-brand-red">View</a> : '—'}</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${BADGE[c.status]}`}>{c.status}</span>{c.rejectionReason && <p className="text-gray-400 mt-0.5">{c.rejectionReason}</p>}</td>
                  <td className="p-3 space-x-2">
                    {c.status === 'PENDING' && <><button onClick={() => approve(c)} className="text-emerald-600 font-semibold">Approve</button><button onClick={() => setRejectId(c.id)} className="text-brand-red">Reject</button></>}
                    {c.status === 'APPROVED' && <button onClick={() => markPaid(c.id)} className="text-blue-600 font-semibold">Mark Paid</button>}
                  </td>
                </tr>
              ))}
              {claims.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-gray-400">No claims yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="Submit Expense Claim" 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}</option>)}
            </select>
            <div className="grid grid-cols-2 gap-2">
              <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                {['Fuel', 'Site Transport', 'Materials', 'Meals', 'Airtime', 'Other'].map((c) => <option key={c} value={c}>{c}</option>)}
              </select>
              <input required type="number" min={0} placeholder="Amount (TZS)" value={form.amountTzs} onChange={(e) => setForm({ ...form, amountTzs: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            </div>
            <textarea placeholder="Description" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <div>
              <label className="text-[10px] text-gray-400 uppercase">Receipt photo (optional)</label>
              <input type="file" accept="image/*" onChange={(e) => setReceipt(e.target.files?.[0] || null)} className="text-[11px]" />
            </div>
            <button disabled={saving} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Submitting…' : 'Submit Claim'}</button>
          </form>
        </Modal>
      )}

      {rejectId !== null && (
        <Modal title="Reject Claim" onClose={() => setRejectId(null)}>
          <form onSubmit={submitRejection} className="space-y-2">
            <textarea required placeholder="Reason for rejection" value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={3} />
            <button className="w-full bg-brand-red text-white text-xs py-2 rounded-lg">Reject Claim</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
