'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';

type Entry = { id: number; type: string; category: string; amountTzs: string; reference: string | null; createdBy: { name: string } | null; createdAt: string };
type Summary = { cashInToday: number; expensesToday: number; balance: number };

export default function CashbookPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [entries, setEntries] = useState<Entry[]>([]);
  const [summary, setSummary] = useState<Summary | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState({ type: 'INCOME', category: '', amountTzs: '', reference: '' });

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/cashbook', accessToken, appSecretProof);
      setEntries(d.entries || []);
      setSummary(d.summary || null);
    } 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 submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/cashbook', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ ...form, amountTzs: Number(form.amountTzs) }),
      });
      show('success', `${form.type === 'INCOME' ? 'Income' : 'Expense'} of TZS ${Number(form.amountTzs).toLocaleString()} recorded.`);
      setForm({ type: 'INCOME', category: '', amountTzs: '', reference: '' });
      load();
    } catch { show('error', 'Could not save that entry.'); }
    finally { setSaving(false); }
  }

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

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">Cashbook &bull; M-Pesa / Tigo Pesa / Bank / Cash</h1>

      {loading ? <StatCardSkeleton count={3} /> : (
        <div className="grid grid-cols-3 gap-3">
          <div className="bg-white p-3 rounded-xl border border-brand-border transition-all hover:shadow-md hover:-translate-y-0.5"><p className="text-xs text-gray-500">Cash In Today</p><p className="text-xl font-bold text-green-600">TZS {(summary?.cashInToday ?? 0).toLocaleString()}</p></div>
          <div className="bg-white p-3 rounded-xl border border-brand-border transition-all hover:shadow-md hover:-translate-y-0.5"><p className="text-xs text-gray-500">Expenses Today</p><p className="text-xl font-bold text-red-600">TZS {(summary?.expensesToday ?? 0).toLocaleString()}</p></div>
          <div className="bg-white p-3 rounded-xl border border-brand-border transition-all hover:shadow-md hover:-translate-y-0.5"><p className="text-xs text-gray-500">Balance</p><p className="text-xl font-bold">TZS {(summary?.balance ?? 0).toLocaleString()}</p></div>
        </div>
      )}

      <form onSubmit={submit} className="bg-white p-4 rounded-xl border border-brand-border grid grid-cols-2 md:grid-cols-5 gap-2">
        <select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
          <option value="INCOME">Income</option><option value="EXPENSE">Expense</option>
        </select>
        <input required placeholder="Category (M-Pesa, Rent…)" 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" />
        <input required type="number" 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" />
        <input placeholder="Reference" value={form.reference} onChange={(e) => setForm({ ...form, reference: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
        <button disabled={saving} className="bg-brand-charcoal text-white text-xs rounded-lg disabled:opacity-60 transition-transform hover:scale-[1.02]">{saving ? 'Saving…' : 'Add Entry'}</button>
      </form>

      {loading ? <TableSkeleton rows={5} cols={5} /> : (
        <div className="bg-white rounded-xl border border-brand-border p-4">
          <table className="w-full text-xs">
            <thead><tr><th className="p-2 text-left">Type</th><th className="p-2 text-left">Category</th><th className="p-2 text-left">Amount</th><th className="p-2 text-left">Reference</th><th className="p-2 text-left">By</th></tr></thead>
            <tbody>
              {entries.map((e) => (
                <tr key={e.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="p-2"><span className={`px-2 py-0.5 rounded-full ${e.type === 'INCOME' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{e.type}</span></td>
                  <td className="p-2">{e.category}</td>
                  <td className="p-2">TZS {Number(e.amountTzs).toLocaleString()}</td>
                  <td className="p-2 text-gray-500">{e.reference || '—'}</td>
                  <td className="p-2 text-gray-500">{e.createdBy?.name || '—'}</td>
                </tr>
              ))}
              {entries.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-gray-400">No entries yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
