import { Card } from './ui/card';
import { currency } from '../lib/format';
import { useMemo } from 'react';
import { useApp } from '../context/AppContext';
import { BarChart, Bar, CartesianGrid, XAxis, Tooltip, ResponsiveContainer } from 'recharts';

type Props = { periodFilter?: (date: Date) => boolean };

export const DashboardCards = ({ periodFilter }: Props) => {
  const { orders, appointments, user } = useApp();
  const shopId = user?.shopId;

  const filteredOrders = useMemo(
    () =>
      (shopId ? orders.filter((o) => o.shopId === shopId) : orders).filter((o) =>
        periodFilter ? periodFilter(new Date(o.createdAt)) : true
      ),
    [orders, shopId, periodFilter]
  );
  const filteredAppts = useMemo(
    () =>
      (shopId ? appointments.filter((a) => a.shopId === shopId) : appointments).filter((a) =>
        periodFilter ? periodFilter(new Date(a.date.replace(' ', 'T'))) : true
      ),
    [appointments, shopId, periodFilter]
  );

  const total = filteredOrders.reduce((s, o) => s + o.total, 0);
  const pending = filteredAppts.filter((a) => a.status === 'pendente').length;
  const confirmed = filteredAppts.filter((a) => a.status === 'confirmado').length;

  const chartData = filteredOrders.reduce<Record<string, number>>((acc, o) => {
    const month = new Date(o.createdAt).toLocaleString('pt-BR', { month: 'short' });
    acc[month] = (acc[month] || 0) + o.total;
    return acc;
  }, {});
  const dataset = Object.entries(chartData).map(([name, value]) => ({ name, value }));

  return (
    <div className="space-y-4">
      <div className="grid md:grid-cols-3 gap-3">
        <Card className="p-4">
          <div className="text-sm text-slate-600">Faturamento</div>
          <div className="text-xl font-semibold text-indigo-700">{currency(total)}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-slate-600">Agendamentos pendentes</div>
          <div className="text-xl font-semibold text-slate-900">{pending}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-slate-600">Confirmados</div>
          <div className="text-xl font-semibold text-slate-900">{confirmed}</div>
        </Card>
      </div>
      <Card className="p-4 h-72">
        <h3 className="text-sm font-semibold text-slate-900 mb-3">Faturamento por mês</h3>
        {dataset.length ? (
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={dataset}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <Tooltip />
              <Bar dataKey="value" fill="#f59e0b" radius={[6, 6, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        ) : (
          <p className="text-sm text-slate-500">Sem dados ainda.</p>
        )}
      </Card>
    </div>
  );
};





