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 { Badge } from '@/components/ui/badge';
import config from '../../config';

interface StockData {
  turnoverByCategory: {
    category: string;
    turnoverRate: number;
    averageStock: number;
    totalSales: number;
  }[];
  stockLevels: {
    date: string;
    inStock: number;
    lowStock: number;
    outOfStock: number;
  }[];
  criticalItems: {
    product: string;
    sku: string;
    stockQuantity: number;
    reorderPoint: number;
    turnoverRate: number;
    daysUntilStockout: number;
  }[];
}

export function StockAnalysis() {
  const { data, isLoading, error } = useQuery<StockData>({
    queryKey: ['stock-analysis'],
    queryFn: async () => {
      try {
        const response = await fetch(`${config.apiUrl}/analytics/stock`);
        if (!response.ok) {
          throw new Error(`Failed to fetch: ${response.status}`);
        }
        const rawData = await response.json();
        
        if (!rawData || !rawData.turnoverByCategory) {
          return {
            turnoverByCategory: [],
            stockLevels: [],
            criticalItems: []
          };
        }
        
        return {
          turnoverByCategory: (rawData.turnoverByCategory || []).map((item: any) => ({
            category: item.category || '',
            turnoverRate: Number(item.turnoverRate || item.turnoverrate) || 0,
            averageStock: Number(item.averageStock || item.averagestock) || 0,
            totalSales: Number(item.totalSales || item.totalsales) || 0
          })),
          stockLevels: (rawData.stockLevels || []).map((item: any) => ({
            date: item.date || '',
            inStock: Number(item.inStock || item.instock) || 0,
            lowStock: Number(item.lowStock || item.lowstock) || 0,
            outOfStock: Number(item.outOfStock || item.outofstock) || 0
          })),
          criticalItems: (rawData.criticalItems || []).map((item: any) => ({
            product: item.product || '',
            sku: item.sku || '',
            stockQuantity: Number(item.stockQuantity || item.stockquantity) || 0,
            reorderPoint: Number(item.reorderPoint || item.reorderpoint) || 0,
            turnoverRate: Number(item.turnoverRate || item.turnoverrate) || 0,
            daysUntilStockout: Number(item.daysUntilStockout || item.daysuntilstockout) || 0
          }))
        };
      } catch (err) {
        console.error('Error fetching stock data:', err);
        throw err;
      }
    },
    retry: 1
  });

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

  if (error || !data) {
    return (
      <Card className="mb-4">
        <CardHeader>
          <CardTitle>Stock Analysis</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-red-500">
            Unable to load stock analysis. The stock metrics may need to be set up in the database.
          </p>
        </CardContent>
      </Card>
    );
  }

  // Early return if no data to display
  if (
    data.turnoverByCategory.length === 0 && 
    data.stockLevels.length === 0 && 
    data.criticalItems.length === 0
  ) {
    return (
      <Card className="mb-4">
        <CardHeader>
          <CardTitle>Stock Analysis</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground">
            No stock data available. This may be because the stock metrics haven't been calculated yet.
          </p>
        </CardContent>
      </Card>
    );
  }

  const getStockStatus = (daysUntilStockout: number) => {
    if (daysUntilStockout <= 7) {
      return <Badge variant="destructive">Critical</Badge>;
    }
    if (daysUntilStockout <= 14) {
      return <Badge variant="outline">Warning</Badge>;
    }
    return <Badge variant="secondary">OK</Badge>;
  };

  return (
    <div className="grid gap-4">
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Stock Turnover by Category</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={data.turnoverByCategory}>
                <XAxis dataKey="category" />
                <YAxis tickFormatter={(value) => `${value.toFixed(1)}x`} />
                <Tooltip 
                  formatter={(value: number) => [`${value.toFixed(1)}x`, 'Turnover Rate']}
                />
                <Bar 
                  dataKey="turnoverRate" 
                  fill="#fbbf24"
                  name="Turnover Rate"
                />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Stock Level Trends</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={data.stockLevels}>
                <XAxis 
                  dataKey="date" 
                  tickFormatter={(value) => new Date(value).toLocaleDateString()}
                />
                <YAxis />
                <Tooltip
                  labelFormatter={(label) => new Date(label).toLocaleDateString()}
                />
                <Line 
                  type="monotone" 
                  dataKey="inStock" 
                  stroke="#4ade80" 
                  name="In Stock"
                />
                <Line 
                  type="monotone" 
                  dataKey="lowStock" 
                  stroke="#fbbf24" 
                  name="Low Stock"
                />
                <Line 
                  type="monotone" 
                  dataKey="outOfStock" 
                  stroke="#f87171" 
                  name="Out of Stock"
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Critical Stock Items</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {data.criticalItems.map((item) => (
              <div key={`${item.sku}-${item.product}`} className="flex items-center">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-medium">{item.product}</p>
                    {getStockStatus(item.daysUntilStockout)}
                  </div>
                  <p className="text-sm text-muted-foreground">
                    SKU: {item.sku}
                  </p>
                </div>
                <div className="ml-4 text-right space-y-1">
                  <p className="text-sm font-medium">
                    {item.stockQuantity} in stock
                  </p>
                  <p className="text-sm text-muted-foreground">
                    Reorder at: {item.reorderPoint}
                  </p>
                  <p className="text-sm text-muted-foreground">
                    {item.daysUntilStockout} days until stockout
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
} 