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

const periods = ['daily', 'weekly', 'monthly'];

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

  const fetchReport = async (selectedPeriod) => {
    try {
      const response = await api.get(`/reports?period=${selectedPeriod}`);
      setReport(response.data);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchReport(period);
  }, [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">
        <h2 className="text-xl font-semibold text-slate-900">Reports</h2>
        <p className="mt-2 text-sm text-slate-500">View customer, product and sales summaries for the selected period.</p>
        <div className="mt-5 flex flex-wrap gap-3">
          {periods.map((option) => (
            <button
              key={option}
              onClick={() => setPeriod(option)}
              className={`rounded-2xl px-4 py-2 text-sm font-semibold ${period === option ? 'bg-slate-900 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'}`}
            >
              {option.charAt(0).toUpperCase() + option.slice(1)}
            </button>
          ))}
        </div>
        {report ? (
          <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}</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}</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}</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})</p>
              <p className="mt-3 text-3xl font-semibold text-slate-900">{report.periodSalesCount}</p>
              <p className="mt-2 text-sm text-slate-600">Amount: {report.periodSalesAmount}</p>
            </div>
          </div>
        ) : (
          <p className="mt-6 text-slate-500">Loading report...</p>
        )}
      </section>
    </div>
  );
}
