import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, ScatterChart, Scatter, ZAxis } from 'recharts';
import config from '../../config';
import { useState, useEffect } from 'react';

interface VendorData {
  performance: {
    vendor: string;
    salesVolume: number;
    profitMargin: number;
    stockTurnover: number;
    productCount: number;
    growth: number;
  }[];
  comparison?: {
    vendor: string;
    salesPerProduct: number;
    averageMargin: number;
    size: number;
  }[];
  trends?: {
    vendor: string;
    month: string;
    sales: number;
  }[];
}

export function VendorPerformance() {
  const [vendorData, setVendorData] = useState<VendorData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // Use plain fetch to bypass cache issues with React Query
    const fetchData = async () => {
      try {
        setIsLoading(true);
        
        // Add cache-busting parameter
        const response = await fetch(`${config.apiUrl}/analytics/vendors?nocache=${Date.now()}`, {
          headers: {
            "Cache-Control": "no-cache, no-store, must-revalidate",
            "Pragma": "no-cache",
            "Expires": "0"
          }
        });
        
        if (!response.ok) {
          throw new Error(`Failed to fetch: ${response.status}`);
        }
        
        const rawData = await response.json();
        
        if (!rawData || !rawData.performance) {
          throw new Error('Invalid response format');
        }
        
        // Create a complete structure even if some parts are missing
        const data: VendorData = {
          performance: rawData.performance.map((vendor: any) => ({
            vendor: vendor.vendor || '',
            salesVolume: vendor.salesVolume !== null ? Number(vendor.salesVolume) : 0,
            profitMargin: vendor.profitMargin !== null ? Number(vendor.profitMargin) : 0,
            stockTurnover: vendor.stockTurnover !== null ? Number(vendor.stockTurnover) : 0,
            productCount: Number(vendor.productCount) || 0,
            growth: vendor.growth !== null ? Number(vendor.growth) : 0
          })),
          comparison: rawData.comparison?.map((vendor: any) => ({
            vendor: vendor.vendor || '',
            salesPerProduct: vendor.salesPerProduct !== null ? Number(vendor.salesPerProduct) : 0,
            averageMargin: vendor.averageMargin !== null ? Number(vendor.averageMargin) : 0,
            size: Number(vendor.size) || 0
          })) || [],
          trends: rawData.trends?.map((vendor: any) => ({
            vendor: vendor.vendor || '',
            month: vendor.month || '',
            sales: Number(vendor.sales) || 0
          })) || []
        };
        
        setVendorData(data);
      } catch (err) {
        console.error('Error fetching vendor data:', err);
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setIsLoading(false);
      }
    };
    
    fetchData();
  }, []);

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

  if (error || !vendorData) {
    return <div className="text-red-500">Error loading vendor data: {error}</div>;
  }

  // Ensure we have at least the performance data
  const sortedPerformance = vendorData.performance
    .sort((a, b) => b.salesVolume - a.salesVolume)
    .slice(0, 10);

  // Use simplified version if comparison data is missing
  const hasComparisonData = vendorData.comparison && vendorData.comparison.length > 0;

  return (
    <div className="grid gap-4">
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Top Vendors by Sales Volume</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={sortedPerformance}>
                <XAxis dataKey="vendor" />
                <YAxis tickFormatter={(value) => `$${(value / 1000).toFixed(0)}k`} />
                <Tooltip 
                  formatter={(value: number) => [`$${value.toLocaleString()}`, 'Sales Volume']}
                />
                <Bar 
                  dataKey="salesVolume" 
                  fill="#60a5fa"
                  name="Sales Volume"
                />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {hasComparisonData ? (
          <Card>
            <CardHeader>
              <CardTitle>Vendor Performance Matrix</CardTitle>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={300}>
                <ScatterChart>
                  <XAxis 
                    dataKey="salesPerProduct" 
                    name="Sales per Product"
                    tickFormatter={(value) => `$${(value / 1000).toFixed(0)}k`}
                  />
                  <YAxis 
                    dataKey="averageMargin" 
                    name="Average Margin"
                    tickFormatter={(value) => `${value.toFixed(0)}%`}
                  />
                  <ZAxis 
                    dataKey="size" 
                    range={[50, 400]} 
                    name="Product Count"
                  />
                  <Tooltip 
                    formatter={(value: number, name: string) => {
                      if (name === 'Sales per Product') return [`$${value.toLocaleString()}`, name];
                      if (name === 'Average Margin') return [`${value.toFixed(1)}%`, name];
                      return [value, name];
                    }}
                  />
                  <Scatter 
                    data={vendorData.comparison} 
                    fill="#60a5fa"
                    name="Vendors"
                  />
                </ScatterChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardHeader>
              <CardTitle>Vendor Profit Margins</CardTitle>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={sortedPerformance}>
                  <XAxis dataKey="vendor" />
                  <YAxis tickFormatter={(value) => `${value}%`} />
                  <Tooltip 
                    formatter={(value: number) => [`${value.toFixed(1)}%`, 'Profit Margin']}
                  />
                  <Bar 
                    dataKey="profitMargin" 
                    fill="#4ade80"
                    name="Profit Margin"
                  />
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        )}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Vendor Performance Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {sortedPerformance.map((vendor) => (
              <div key={`${vendor.vendor}-${vendor.salesVolume}`} className="flex items-center">
                <div className="flex-1">
                  <p className="text-sm font-medium">{vendor.vendor}</p>
                  <p className="text-sm text-muted-foreground">
                    {vendor.productCount} products
                  </p>
                </div>
                <div className="ml-4 text-right space-y-1">
                  <p className="text-sm font-medium">
                    ${vendor.salesVolume.toLocaleString()} sales
                  </p>
                  <p className="text-sm text-muted-foreground">
                    {vendor.profitMargin.toFixed(1)}% margin
                  </p>
                  <p className="text-sm text-muted-foreground">
                    {vendor.stockTurnover.toFixed(1)}x turnover
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
} 