'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import StatCard from '@/components/StatCard';
import { StatCardSkeleton } from '@/components/Skeletons';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

type TrendPoint = { date: string; revenueTzs: number; orders: number };

export default function AnalyticsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [stats, setStats] = useState<Record<string, number> | null>(null);
  const [trends, setTrends] = useState<TrendPoint[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    Promise.all([
      adminApiFetch('/admin/analytics', accessToken, appSecretProof),
      adminApiFetch('/admin/analytics/trends', accessToken, appSecretProof),
    ])
      .then(([s, t]) => { setStats(s.stats); setTrends(t.series || []); })
      .catch(() => { setError('You do not have permission to view this page.'); show('error', 'Could not load analytics.'); })
      .finally(() => setLoading(false));
  }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

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

  const chartData = trends.map((t) => ({ ...t, label: new Date(t.date).toLocaleDateString([], { day: '2-digit', month: 'short' }) }));

  return (
    <div className="space-y-4">
      <h1 className="text-lg font-bold">Analytics</h1>
      {loading ? (
        <StatCardSkeleton count={4} />
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard label="Revenue This Month (TZS)" value={(stats?.revenueThisMonthTzs ?? 0).toLocaleString()} />
          <StatCard label="Orders This Month" value={stats?.ordersThisMonth ?? 0} />
          <StatCard label="Pending Quotes" value={stats?.pendingQuotes ?? 0} />
          <StatCard label="Open Tickets" value={stats?.openTickets ?? 0} />
        </div>
      )}

      {!loading && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-white border border-brand-border rounded-xl p-4">
            <p className="text-xs font-semibold mb-3">Revenue — Last 14 Days</p>
            <ResponsiveContainer width="100%" height={220}>
              <LineChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#E5E5E7" />
                <XAxis dataKey="label" tick={{ fontSize: 10 }} />
                <YAxis tick={{ fontSize: 10 }} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                <Tooltip formatter={(v: number) => `TZS ${v.toLocaleString()}`} contentStyle={{ fontSize: 12, borderRadius: 8 }} />
                <Line type="monotone" dataKey="revenueTzs" stroke="#C1272D" strokeWidth={2} dot={false} name="Revenue" />
              </LineChart>
            </ResponsiveContainer>
          </div>

          <div className="bg-white border border-brand-border rounded-xl p-4">
            <p className="text-xs font-semibold mb-3">Orders — Last 14 Days</p>
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#E5E5E7" />
                <XAxis dataKey="label" tick={{ fontSize: 10 }} />
                <YAxis tick={{ fontSize: 10 }} allowDecimals={false} />
                <Tooltip contentStyle={{ fontSize: 12, borderRadius: 8 }} />
                <Bar dataKey="orders" fill="#121212" radius={[4, 4, 0, 0]} name="Orders" />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}
    </div>
  );
}
