"use client"

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/common/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/common/table";
import { Badge } from "@/components/common/badge";
import { useToast } from "@/lib/hooks/use-toast";
import { Skeleton } from "@/components/common/skeleton";
import { Package } from "lucide-react";
import { getProductPerformanceWithStore, type ProductPerformance } from "@/lib/services/analytics-service";
import { formatGBP, formatNumber } from "@/lib/utils/format";
import { TableSkeleton } from './SkeletonLoaders';

export default function ProductPerformanceChart() {
  const [data, setData] = useState<ProductPerformance[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  useEffect(() => {
    const fetchProductData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const response = await getProductPerformanceWithStore();
        setData(response);
      } catch (err) {
        console.error('Error fetching product performance:', err);
        setError('Failed to load product data');
        toast({
          title: "Error",
          description: "Failed to load product performance data.",
          variant: "destructive",
        });
      } finally {
        setIsLoading(false);
      }
    };

    fetchProductData();
  }, [toast]);

  if (isLoading) {
    return (
      <TableSkeleton
        title="Product Performance"
        description="Top performing products by revenue and sales"
        icon={Package}
        rows={8}
        columns={5}
      />
    );
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Product Performance
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <Package className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">Failed to load product data</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (data.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Product Performance
          </CardTitle>
          <CardDescription>
            Top performing products by revenue and sales
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <Package className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">No product performance data available</p>
            <p className="text-sm text-muted-foreground mt-2">
              Start selling products to see performance metrics
            </p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Package className="h-5 w-5" />
          Product Performance
        </CardTitle>
        <CardDescription>
          Top performing products by revenue and sales
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Product</TableHead>
              <TableHead className="text-right">Units Sold</TableHead>
              <TableHead className="text-right">Revenue</TableHead>
              <TableHead className="text-right">Orders</TableHead>
              <TableHead className="text-right">Avg Price</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.map((product) => (
              <TableRow key={product.productId}>
                <TableCell>
                  <div className="flex items-center gap-3">
                    <div
                      className="h-10 w-10 bg-cover bg-center rounded border flex-shrink-0"
                      style={{
                        backgroundImage: product.image
                          ? `url(/api/products/${product.productId}/image)`
                          : 'none'
                      }}
                    />
                    <div>
                      <div className="font-medium">{product.name}</div>
                    </div>
                  </div>
                </TableCell>
                <TableCell className="text-right font-medium">
                  {formatNumber(parseInt(product.totalSold.toFixed(0)))} {product.unitType}
                </TableCell>
                <TableCell className="text-right font-medium text-green-600">
                  {formatGBP(product.totalRevenue)}
                </TableCell>
                <TableCell className="text-right">
                  {product.orderCount}
                </TableCell>
                <TableCell className="text-right">
                  {formatGBP(product.averagePrice)}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}

