import { useQuery } from '@tanstack/react-query';
import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import config from '../../config';

interface SalesData {
  date: string;
  total: number;
}

export function Overview() {
  const { data, isLoading, error } = useQuery<SalesData[]>({
    queryKey: ['sales-overview'],
    queryFn: async () => {
      const response = await fetch(`${config.apiUrl}/dashboard/sales-overview`);
      if (!response.ok) {
        throw new Error('Failed to fetch sales overview');
      }
      const rawData = await response.json();
      return rawData.map((item: SalesData) => ({
        ...item,
        total: parseFloat(item.total.toString()),
        date: new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
      }));
    },
  });

  if (isLoading) {
    return <div>Loading chart...</div>;
  }

  if (error) {
    return <div className="text-red-500">Error loading sales overview</div>;
  }

  return (
    <ResponsiveContainer width="100%" height={350}>
      <LineChart data={data}>
        <XAxis
          dataKey="date"
          stroke="#888888"
          fontSize={12}
          tickLine={false}
          axisLine={false}
        />
        <YAxis
          stroke="#888888"
          fontSize={12}
          tickLine={false}
          axisLine={false}
          tickFormatter={(value) => `$${value.toLocaleString()}`}
        />
        <Tooltip 
          formatter={(value: number) => [`$${value.toLocaleString()}`, 'Sales']}
          labelFormatter={(label) => `Date: ${label}`}
        />
        <Line
          type="monotone"
          dataKey="total"
          stroke="hsl(var(--primary))"
          strokeWidth={2}
          dot={false}
        />
      </LineChart>
    </ResponsiveContainer>
  );
} 