import { useEffect, useMemo, useState } from 'react';
import api from '../api';

export default function DashboardPage() {
  const [period, setPeriod] = useState('daily');
  const [report, setReport] = useState(null);
  const [latestSales, setLatestSales] = useState([]);

  const periods = useMemo(() => ['daily', 'weekly', 'monthly'], []);

  useEffect(() => {
    const fetchReport = async () => {
      try {
        const res = await api.get(`/reports?period=${period}`);
        setReport(res.data);
      } catch (e) {
        // keep UI stable
      }
    };

    const fetchLatestSales = async () => {
      try {
        const res = await api.get('/sales');
        setLatestSales((res.data || []).slice(0, 5));
      } catch (e) {
        // keep UI stable
      }
    };

    fetchReport();
    fetchLatestSales();
  }, [period]);

  return (
    <div className="space-y-6">
      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-slate-900">Dashboard</h2>
            <p className="mt-1 text-sm text-slate-500">At-a-glance overview of sales activity.</p>
          </div>

          <div className="flex flex-wrap gap-2">
            {periods.map((p) => (
              <button
                key={p}
                type="button"
                onClick={() => setPeriod(p)}
                className={
                  'rounded-2xl px-4 py-2 text-sm font-semibold transition ' +
                  (period === p
                    ? 'bg-slate-900 text-white shadow-[0_10px_20px_rgba(2,6,23,0.18)]'
                    : 'bg-slate-100 text-slate-700 hover:bg-slate-200')
                }
              >
                {p.charAt(0).toUpperCase() + p.slice(1)}
              </button>
            ))}
          </div>
        </div>

        <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <div className="rounded-3xl border border-slate-200 bg-slate-50 p-5">
            <p className="text-sm uppercase tracking-wide text-slate-500">Customers</p>
            <p className="mt-3 text-3xl font-semibold text-slate-900">{report?.customerCount ?? 0}</p>
          </div>
          <div className="rounded-3xl border border-slate-200 bg-slate-50 p-5">
            <p className="text-sm uppercase tracking-wide text-slate-500">Products</p>
            <p className="mt-3 text-3xl font-semibold text-slate-900">{report?.productCount ?? 0}</p>
          </div>
          <div className="rounded-3xl border border-slate-200 bg-slate-50 p-5">
            <p className="text-sm uppercase tracking-wide text-slate-500">Total Sales</p>
            <p className="mt-3 text-3xl font-semibold text-slate-900">{report?.salesCount ?? 0}</p>
          </div>
          <div className="rounded-3xl border border-slate-200 bg-slate-50 p-5">
            <p className="text-sm uppercase tracking-wide text-slate-500">Sales ({report?.period ?? period})</p>
            <p className="mt-3 text-3xl font-semibold text-slate-900">{report?.periodSalesCount ?? 0}</p>
            <p className="mt-2 text-sm text-slate-600">Amount: {report?.periodSalesAmount ?? 0}</p>
          </div>
        </div>
      </section>

      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <div className="flex items-center justify-between gap-3">
          <h2 className="text-xl font-semibold text-slate-900">Latest Sales</h2>
          <span className="text-sm text-slate-500">Recent activity</span>
        </div>

        <div className="mt-4 overflow-x-auto">
          <table className="w-full min-w-max divide-y divide-slate-200 text-left text-sm text-slate-700">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3">Invoice</th>
                <th className="px-4 py-3">Date</th>
                <th className="px-4 py-3">Customer</th>
                <th className="px-4 py-3">Product</th>
                <th className="px-4 py-3">Qty</th>
                <th className="px-4 py-3">Amount</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {latestSales.length ? (
                latestSales.map((s) => (
                  <tr key={s._id}>
                    <td className="px-4 py-3">{s.invoiceNumber}</td>
                    <td className="px-4 py-3">{new Date(s.salesDate).toLocaleDateString()}</td>
                    <td className="px-4 py-3">{s.customerNumber}</td>
                    <td className="px-4 py-3">{s.productCode}</td>
                    <td className="px-4 py-3">{s.quantitySold}</td>
                    <td className="px-4 py-3">{s.totalAmountPaid}</td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="px-4 py-6 text-center text-slate-500">
                    No sales yet.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}

