import { useState, useMemo } from 'react';
import { useProviders } from '@/hooks/useProviders';
import { useStats } from '@/hooks/useStats';
import { StatCards } from './StatCards';
import { UsageChart } from './UsageChart';
import { StatsTable } from './StatsTable';

export function StatsPage() {
  const { data: providers = [] } = useProviders();

  const [providerId, setProviderId] = useState<string | undefined>();
  const [modelName, setModelName] = useState<string | undefined>();
  const [dateRange, setDateRange] = useState<[Date | null, Date | null] | null>(null);

  const params = useMemo(
    () => ({
      providerId,
      modelName,
      startDate: dateRange?.[0]?.toISOString().split('T')[0],
      endDate: dateRange?.[1]?.toISOString().split('T')[0],
    }),
    [providerId, modelName, dateRange],
  );

  const { data: stats = [], isLoading } = useStats(params);

  return (
    <div>
      <StatCards stats={stats} />
      <UsageChart stats={stats} />
      <StatsTable
        providers={providers}
        stats={stats}
        loading={isLoading}
        providerId={providerId}
        modelName={modelName}
        dateRange={dateRange}
        onProviderIdChange={setProviderId}
        onModelNameChange={setModelName}
        onDateRangeChange={setDateRange}
      />
    </div>
  );
}
