'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { StatCardSkeleton } from '@/components/Skeletons';

type Period = { revenue: number; expenses: number; profit: number };

export default function PnLPage() {
  const { accessToken, appSecretProof } = useAuth();
  const [data, setData] = useState<{ today: Period; month: Period; year: Period; fullAccess: boolean } | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    adminApiFetch('/admin/pnl', accessToken, appSecretProof)
      .then(setData)
      .catch(() => setError('You do not have permission to view this page.'));
  }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

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

  const row = (label: string, p: Period) => (
    <div className="bg-white p-4 rounded-xl border border-brand-border transition-all hover:shadow-md hover:-translate-y-0.5">
      <p className="text-xs text-gray-500">{label}</p>
      <p className="text-sm mt-1">
        Revenue TZS {p.revenue.toLocaleString()} &bull; Expenses {p.expenses.toLocaleString()} &bull; <b>Profit {p.profit.toLocaleString()}</b>
      </p>
    </div>
  );

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">P&amp;L Report &bull; admin.lussavara.co.tz</h1>

      {!data.fullAccess && (
        <div className="bg-yellow-50 border border-yellow-200 p-3 rounded-xl text-xs">
          You&apos;re seeing the operational summary. Full P&amp;L detail (VAT breakdown, bank reconciliation) is Director-level only.
        </div>
      )}

      <div className="grid grid-cols-3 gap-4">
        {row('Today', data.today)}
        {row('This Month', data.month)}
        {row('This Year', data.year)}
      </div>

      {data.fullAccess && (
        <div className="bg-white p-4 rounded-xl border border-brand-border">
          <p className="text-sm font-semibold">Tax VAT 18% Report &bull; Bank Reconciliation &bull; Export</p>
          <p className="text-xs text-gray-500 mt-2">Director-level detail — wire the VAT breakdown and bank reconciliation export here.</p>
        </div>
      )}
    </div>
  );
}
