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

interface CategoryData {
  performance: {
    category: string;
    categoryPath: string;  // Full hierarchy path
    revenue: number;
    profit: number;
    growth: number;
    productCount: number;
  }[];
  distribution: {
    category: string;
    categoryPath: string;  // Full hierarchy path
    value: number;
  }[];
  trends: {
    category: string;
    categoryPath: string;  // Full hierarchy path
    month: string;
    sales: number;
  }[];
}

const COLORS = ['#4ade80', '#60a5fa', '#f87171', '#fbbf24', '#a78bfa', '#f472b6'];

export function CategoryPerformance() {
  const { data, isLoading } = useQuery<CategoryData>({
    queryKey: ['category-performance'],
    queryFn: async () => {
      const response = await fetch(`${config.apiUrl}/analytics/categories`);
      if (!response.ok) {
        throw new Error('Failed to fetch category performance');
      }
      const rawData = await response.json();
      return {
        performance: rawData.performance.map((item: any) => ({
          category: item.category || '',
          categoryPath: item.categoryPath || item.categorypath || item.category || '',
          revenue: Number(item.revenue) || 0,
          profit: Number(item.profit) || 0,
          growth: Number(item.growth) || 0,
          productCount: Number(item.productCount) || Number(item.productcount) || 0
        })),
        distribution: rawData.distribution.map((item: any) => ({
          category: item.category || '',
          categoryPath: item.categoryPath || item.categorypath || item.category || '',
          value: Number(item.value) || 0
        })),
        trends: rawData.trends.map((item: any) => ({
          category: item.category || '',
          categoryPath: item.categoryPath || item.categorypath || item.category || '',
          month: item.month || '',
          sales: Number(item.sales) || 0
        }))
      };
    },
  });

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

  const formatGrowth = (growth: number) => {
    const value = growth >= 0 ? `+${growth.toFixed(1)}%` : `${growth.toFixed(1)}%`;
    const color = growth >= 0 ? 'text-green-500' : 'text-red-500';
    return <span className={color}>{value}</span>;
  };

  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>Category Revenue Distribution</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={data.distribution}
                  dataKey="value"
                  nameKey="categoryPath"
                  cx="50%"
                  cy="50%"
                  outerRadius={100}
                  fill="#8884d8"
                  label={({ categoryPath }) => getShortCategoryName(categoryPath)}
                >
                  {data.distribution.map((entry, index) => (
                    <Cell 
                      key={`${entry.category}-${entry.value}-${index}`}
                      fill={COLORS[index % COLORS.length]} 
                    />
                  ))}
                </Pie>
                <Tooltip 
                  formatter={(value: number, _: string, props: any) => [
                    `$${value.toLocaleString()}`,
                    <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">Revenue</div>
                    </div>
                  ]}
                />
                <Legend 
                  formatter={(value) => getShortCategoryName(value)} 
                  wrapperStyle={{ fontSize: '12px' }}
                />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Category Growth Rates</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={data.performance}>
                <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">Growth Rate</div>
                    </div>
                  ]}
                />
                <Bar 
                  dataKey="growth" 
                  fill="#4ade80"
                  name="Growth Rate"
                />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Category Performance Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {data.performance.map((category) => (
              <div key={`${category.category}-${category.revenue}`} className="flex items-center">
                <div className="flex-1">
                  <div className="space-y-1">
                    <p className="text-sm font-medium">{getShortCategoryName(category.categoryPath)}</p>
                    <p className="text-xs text-muted-foreground">{category.categoryPath}</p>
                  </div>
                  <p className="text-sm text-muted-foreground mt-1">
                    {category.productCount} products
                  </p>
                </div>
                <div className="ml-4 text-right space-y-1">
                  <p className="text-sm font-medium">
                    ${category.revenue.toLocaleString()} revenue
                  </p>
                  <p className="text-sm text-muted-foreground">
                    ${category.profit.toLocaleString()} profit
                  </p>
                  <p className="text-sm text-muted-foreground">
                    Growth: {formatGrowth(category.growth)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
} 