import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, LineChart, Line } from 'recharts';
import config from '../../config';

interface ProfitData {
  byCategory: {
    category: string;
    categoryPath: string;  // Full hierarchy path
    profitMargin: number;
    revenue: number;
    cost: number;
  }[];
  overTime: {
    date: string;
    profitMargin: number;
    revenue: number;
    cost: number;
  }[];
  topProducts: {
    product: string;
    category: string;
    categoryPath: string;  // Full hierarchy path
    profitMargin: number;
    revenue: number;
    cost: number;
  }[];
}

export function ProfitAnalysis() {
  const { data, isLoading } = useQuery<ProfitData>({
    queryKey: ['profit-analysis'],
    queryFn: async () => {
      const response = await fetch(`${config.apiUrl}/analytics/profit`);
      if (!response.ok) {
        throw new Error('Failed to fetch profit analysis');
      }
      const rawData = await response.json();
      return {
        byCategory: rawData.byCategory.map((item: any) => ({
          category: item.category || '',
          categoryPath: item.categorypath || item.category || '',
          profitMargin: item.profitmargin !== null ? Number(item.profitmargin) : 0,
          revenue: Number(item.revenue) || 0,
          cost: Number(item.cost) || 0
        })),
        overTime: rawData.overTime.map((item: any) => ({
          date: item.date || '',
          profitMargin: item.profitmargin !== null ? Number(item.profitmargin) : 0,
          revenue: Number(item.revenue) || 0,
          cost: Number(item.cost) || 0
        })),
        topProducts: rawData.topProducts.map((item: any) => ({
          product: item.product || '',
          category: item.category || '',
          categoryPath: item.categorypath || item.category || '',
          profitMargin: item.profitmargin !== null ? Number(item.profitmargin) : 0,
          revenue: Number(item.revenue) || 0,
          cost: Number(item.cost) || 0
        }))
      };
    },
  });

  if (isLoading || !data) {
    return <div>Loading profit analysis...</div>;
  }

  const getShortCategoryName = (path: string) => path.split(' > ').pop() || path;

  return (
    <div className="grid gap-4">
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Profit Margins by Category</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={data.byCategory}>
                <XAxis 
                  dataKey="categoryPath" 
                  tick={({ x, y, payload }) => (
                    <g transform={`translate(${x},${y})`}>
                      <text
                        x={0}
                        y={0}
                        dy={16}
                        textAnchor="end"
                        fill="#888888"
                        transform="rotate(-35)"
                      >
                        {getShortCategoryName(payload.value)}
                      </text>
                    </g>
                  )}
                />
                <YAxis tickFormatter={(value) => `${value}%`} />
                <Tooltip 
                  formatter={(value: number, _: string, props: any) => [
                    `${value.toFixed(1)}%`,
                    <div key="tooltip">
                      <div className="font-medium">Category Path:</div>
                      <div className="text-sm text-muted-foreground">{props.payload.categoryPath}</div>
                      <div className="mt-1">Profit Margin</div>
                    </div>
                  ]}
                />
                <Bar 
                  dataKey="profitMargin" 
                  fill="#4ade80"
                  name="Profit Margin"
                />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader>
            <CardTitle>Profit Margin Trend</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={data.overTime}>
                <XAxis 
                  dataKey="date" 
                  tickFormatter={(value) => new Date(value).toLocaleDateString()}
                />
                <YAxis tickFormatter={(value) => `${value}%`} />
                <Tooltip
                  labelFormatter={(label) => new Date(label).toLocaleDateString()}
                  formatter={(value: number) => [`${value.toFixed(1)}%`, 'Profit Margin']}
                />
                <Line 
                  type="monotone" 
                  dataKey="profitMargin" 
                  stroke="#4ade80" 
                  name="Profit Margin"
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Top Performing Products by Profit Margin</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {data.topProducts.map((product) => (
              <div key={`${product.product}-${product.category}`} className="flex items-center">
                <div className="flex-1">
                  <p className="text-sm font-medium">{product.product}</p>
                  <div className="text-xs text-muted-foreground space-y-1">
                    <p className="font-medium">Category:</p>
                    <p>{product.categoryPath}</p>
                  </div>
                  <p className="text-sm text-muted-foreground mt-1">
                    Revenue: ${product.revenue.toLocaleString()}
                  </p>
                </div>
                <div className="ml-4 text-right">
                  <p className="text-sm font-medium">
                    {product.profitMargin.toFixed(1)}% margin
                  </p>
                  <p className="text-sm text-muted-foreground">
                    Cost: ${product.cost.toLocaleString()}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
} 