"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { PageHeader, PageLoader, StatCard, Badge, TableShell, fmtKes } from "@/components/ui";

interface Stats {
  employees: number;
  clients: number;
  invoiced: number;
  collected: number;
  outstanding: number;
  invoiceCount: number;
  pendingLeave: number;
  lastPayroll: { periodLabel: string; totalNet: number; employeeCount: number } | null;
  recentInvoices: Array<{ id: number; invoiceNo: string; clientName: string; total: number; status: string; dueDate: string }>;
  recentPayments: Array<{ id: number; invoiceNo: string; clientName: string; amount: number; method: string; reference: string; paidAt: string }>;
}

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState("");

  useEffect(() => {
    fetch("/api/dashboard")
      .then((r) => r.json())
      .then((d) => (d.error ? setError(d.error) : setStats(d)))
      .catch((e) => setError(e.message));
  }, []);

  if (error) return <p className="rounded-lg bg-rose-50 p-4 text-sm text-rose-700">{error}</p>;
  if (!stats) return <PageLoader label="Loading dashboard…" />;

  return (
    <div>
      <PageHeader title="Dashboard" subtitle="Overview of Macsoft's business performance" />

      <div className="mb-4 flex flex-col gap-3 rounded-2xl border border-amber-200 bg-gradient-to-r from-amber-50 to-white p-4 sm:flex-row sm:items-center sm:justify-between sm:p-5">
        <div>
          <p className="text-xs font-semibold uppercase tracking-wide text-amber-600">📦 PHP / MySQL edition for cPanel</p>
          <p className="mt-1 text-sm text-slate-700">
            Download the standalone <span className="font-semibold">PHP + MySQL version</span> of this ERP — upload to
            shared cPanel hosting, run the web installer, done. Full instructions in the included README.
          </p>
        </div>
        <a
          href="/api/download/php-package"
          className="shrink-0 rounded-lg bg-amber-500 px-4 py-2 text-center text-sm font-semibold text-white shadow-sm transition hover:bg-amber-600"
        >
          ⬇ Download ZIP
        </a>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Total Invoiced" value={fmtKes(stats.invoiced)} hint={`${stats.invoiceCount} invoices`} icon="🧾" tone="blue" />
        <StatCard label="Collected" value={fmtKes(stats.collected)} hint="Payments received" icon="💰" tone="emerald" />
        <StatCard label="Outstanding" value={fmtKes(stats.outstanding)} hint="Awaiting payment" icon="⏳" tone="amber" />
        <StatCard label="Active Employees" value={String(stats.employees)} hint={`${stats.pendingLeave} pending leave requests`} icon="👥" tone="slate" />
      </div>

      {stats.lastPayroll && (
        <div className="mt-4 flex flex-col gap-3 rounded-2xl border border-blue-100 bg-gradient-to-r from-blue-50 to-white p-4 sm:flex-row sm:items-center sm:justify-between sm:p-5">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wide text-blue-600">Latest payroll run</p>
            <p className="mt-1 text-sm text-slate-700">
              <span className="font-semibold">{stats.lastPayroll.periodLabel}</span> · {stats.lastPayroll.employeeCount} employees ·
              net pay <span className="font-semibold">{fmtKes(stats.lastPayroll.totalNet)}</span>
            </p>
          </div>
          <Link href="/dashboard/payroll" className="text-sm font-semibold text-blue-700 hover:underline">
            View payroll →
          </Link>
        </div>
      )}

      <div className="mt-6 grid grid-cols-1 gap-6 xl:grid-cols-2">
        <section>
          <div className="mb-3 flex items-center justify-between">
            <h2 className="text-sm font-semibold text-slate-700">Recent invoices</h2>
            <Link href="/dashboard/invoices" className="text-xs font-semibold text-blue-700 hover:underline">
              View all
            </Link>
          </div>
          <TableShell head={["Invoice", "Client", "Total", "Status"]}>
            {stats.recentInvoices.map((inv) => (
              <tr key={inv.id} className="hover:bg-slate-50">
                <td className="px-4 py-3">
                  <Link href={`/dashboard/invoices/${inv.id}`} className="font-medium text-blue-700 hover:underline">
                    {inv.invoiceNo}
                  </Link>
                </td>
                <td className="max-w-[140px] truncate px-4 py-3 text-slate-600">{inv.clientName}</td>
                <td className="whitespace-nowrap px-4 py-3 font-medium">{fmtKes(inv.total)}</td>
                <td className="px-4 py-3"><Badge value={inv.status} /></td>
              </tr>
            ))}
          </TableShell>
        </section>

        <section>
          <div className="mb-3 flex items-center justify-between">
            <h2 className="text-sm font-semibold text-slate-700">Recent payments</h2>
            <Link href="/dashboard/payments" className="text-xs font-semibold text-blue-700 hover:underline">
              View all
            </Link>
          </div>
          <TableShell head={["Reference", "Client", "Amount", "Method"]}>
            {stats.recentPayments.map((p) => (
              <tr key={p.id} className="hover:bg-slate-50">
                <td className="px-4 py-3 font-mono text-xs text-slate-600">{p.reference || p.invoiceNo}</td>
                <td className="max-w-[140px] truncate px-4 py-3 text-slate-600">{p.clientName}</td>
                <td className="whitespace-nowrap px-4 py-3 font-medium text-emerald-700">{fmtKes(p.amount)}</td>
                <td className="px-4 py-3"><Badge value={p.method} /></td>
              </tr>
            ))}
          </TableShell>
        </section>
      </div>
    </div>
  );
}
