import React, { useState, useEffect } from "react";
import axios from "axios";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, ArrowUpDown, AlertCircle, Package, Settings2, Search } from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { TIME_RANGES } from "@/lib/constants";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";

const ProductGrid = ({
  timeRange = "today",
  onTimeRangeChange,
  title = "Top Products",
  description
}) => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedTimeRange, setSelectedTimeRange] = useState(timeRange);
  const [sorting, setSorting] = useState({
    column: "totalQuantity",
    direction: "desc",
  });
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    fetchProducts();
  }, [selectedTimeRange]);

  const fetchProducts = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await axios.get("/api/klaviyo/events/products", {
        params: { timeRange: selectedTimeRange },
      });
      setProducts(response.data.stats.products.list || []);
    } catch (error) {
      console.error("Error fetching products:", error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleTimeRangeChange = (value) => {
    setSelectedTimeRange(value);
    if (onTimeRangeChange) {
      onTimeRangeChange(value);
    }
  };

  const handleSort = (column) => {
    setSorting((prev) => ({
      column,
      direction:
        prev.column === column && prev.direction === "desc" ? "asc" : "desc",
    }));
  };

  const sortedProducts = [...products].sort((a, b) => {
    const direction = sorting.direction === "desc" ? -1 : 1;
    const aValue = a[sorting.column];
    const bValue = b[sorting.column];

    if (typeof aValue === "number") {
      return (aValue - bValue) * direction;
    }
    return String(aValue).localeCompare(String(bValue)) * direction;
  });

  const filteredProducts = sortedProducts.filter(product => 
    product.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const SkeletonProduct = () => (
    <tr>
      <td className="p-1 align-middle w-[50px]">
        <Skeleton className="h-[50px] w-[50px] rounded" />
      </td>
      <td className="p-1 align-middle min-w-[200px]">
        <div className="flex flex-col gap-1">
          <Skeleton className="h-4 w-[130px]" />
          <Skeleton className="h-3 w-[120px]" />
        </div>
      </td>
      <td className="p-1 align-middle text-center">
        <Skeleton className="h-4 w-8 mx-auto" />
      </td>
      <td className="p-1 align-middle text-center">
        <Skeleton className="h-4 w-16 mx-auto" />
      </td>
      <td className="p-1 align-middle text-center">
        <Skeleton className="h-4 w-8 mx-auto" />
      </td>
    </tr>
  );

  const LoadingState = () => (
    <div className="rounded-md border h-full">
      <div className="overflow-y-auto h-full">
        <table className="w-full">
          <thead>
            <tr className="hover:bg-transparent">
              <th className="p-1.5 text-left font-medium sticky top-0 bg-white dark:bg-background z-10 w-[50px] min-w-[50px] border-b" />
              <th className="p-1.5 text-left font-medium sticky top-0 bg-white dark:bg-background z-10 min-w-[200px] border-b">
                <div className="inline-flex items-center justify-start w-full px-2 py-1 text-sm font-medium">
                  <Skeleton className="h-4 w-16" />
                </div>
              </th>
              <th className="p-1.5 font-medium text-center sticky top-0 bg-white dark:bg-background z-10 border-b">
                <div className="inline-flex items-center justify-center w-full px-2 py-1 text-sm font-medium">
                  <Skeleton className="h-4 w-8" />
                </div>
              </th>
              <th className="p-1.5 font-medium text-center sticky top-0 bg-white dark:bg-background z-10 border-b">
                <div className="inline-flex items-center justify-center w-full px-2 py-1 text-sm font-medium">
                  <Skeleton className="h-4 w-8" />
                </div>
              </th>
              <th className="p-1.5 font-medium text-center sticky top-0 bg-white dark:bg-background z-10 border-b">
                <div className="inline-flex items-center justify-center w-full px-2 py-1 text-sm font-medium">
                  <Skeleton className="h-4 w-12" />
                </div>
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
            {[...Array(10)].map((_, i) => (
              <SkeletonProduct key={i} />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  return (
    <Card className="flex flex-col h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <CardHeader className="p-6 pb-4">
        <div className="flex justify-between items-start">
          <div>
            <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">{title}</CardTitle>
            {description && (
              <CardDescription className="mt-1">{description}</CardDescription>
            )}
          </div>
          <div className="flex items-center gap-4">
            {!error && (
              <div className="relative hidden sm:block">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search products..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8 h-9 w-[200px]"
                />
              </div>
            )}
            <Select
              value={selectedTimeRange}
              onValueChange={handleTimeRangeChange}
            >
              <SelectTrigger className="w-[130px] h-9">
                <SelectValue placeholder="Select time range" />
              </SelectTrigger>
              <SelectContent>
                {TIME_RANGES.map((range) => (
                  <SelectItem key={range.value} value={range.value}>
                    {range.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
      </CardHeader>

      <CardContent className="p-6 pt-0 flex-1 overflow-hidden -mt-1">
        <div className="h-full">
          {loading ? (
            <LoadingState />
          ) : error ? (
            <Alert variant="destructive" >
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Error</AlertTitle>
              <AlertDescription>
                Failed to load products: {error}
              </AlertDescription>
            </Alert>
          ) : !products?.length ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <Package className="h-12 w-12 text-muted-foreground mb-4" />
              <p className="font-medium mb-2">No product data available</p>
              <p className="text-sm text-muted-foreground">Try selecting a different time range</p>
            </div>
          ) : (
            <div className="rounded-md border h-full">
              <div className="overflow-y-auto h-full">
                <table className="w-full">
                  <thead>
                    <tr className="hover:bg-transparent">
                      <th className="p-1.5 text-left font-medium sticky top-0 bg-white dark:bg-background z-10 w-[50px] min-w-[50px] border-b" />
                      <th className="p-1.5 text-left font-medium sticky top-0 bg-white dark:bg-background z-10 min-w-[200px] border-b">
                        <Button
                          variant={sorting.column === "name" ? "default" : "ghost"}
                          onClick={() => handleSort("name")}
                          className="w-full justify-start h-8"
                        >
                          Product
                        </Button>
                      </th>
                      <th className="p-1.5 font-medium text-center sticky top-0 bg-white dark:bg-background z-10 border-b">
                        <Button
                          variant={sorting.column === "totalQuantity" ? "default" : "ghost"}
                          onClick={() => handleSort("totalQuantity")}
                          className="w-full justify-center h-8"
                        >
                          Sold
                        </Button>
                      </th>
                      <th className="p-1.5 font-medium text-center sticky top-0 bg-white dark:bg-background z-10 border-b">
                        <Button
                          variant={sorting.column === "totalRevenue" ? "default" : "ghost"}
                          onClick={() => handleSort("totalRevenue")}
                          className="w-full justify-center h-8"
                        >
                          Rev
                        </Button>
                      </th>
                      <th className="p-1.5 font-medium text-center sticky top-0 bg-white dark:bg-background z-10 border-b">
                        <Button
                          variant={sorting.column === "orderCount" ? "default" : "ghost"}
                          onClick={() => handleSort("orderCount")}
                          className="w-full justify-center h-8"
                        >
                          Orders
                        </Button>
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                    {filteredProducts.map((product) => (
                      <tr
                        key={product.id}
                        className="hover:bg-muted/50 transition-colors"
                      >
                        <td className="p-1 align-middle w-[50px]">
                          {product.ImgThumb && (
                            <img
                              src={product.ImgThumb}
                              alt=""
                              width={50}
                              height={50}
                              className="rounded bg-muted"
                              onError={(e) => (e.target.style.display = "none")}
                            />
                          )}
                        </td>
                        <td className="p-1 align-middle min-w-[200px]">
                          <div className="flex flex-col min-w-0">
                            <TooltipProvider>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <a
                                    href={`https://backend.acherryontop.com/product/${product.id}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-sm hover:underline line-clamp-2 text-gray-900 dark:text-gray-100"
                                  >
                                    {product.name}
                                  </a>
                                </TooltipTrigger>
                                <TooltipContent side="top" className="max-w-[300px]">
                                  <p>{product.name}</p>
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          </div>
                        </td>
                        <td className="p-1 align-middle text-center text-sm font-medium">
                          {product.totalQuantity}
                        </td>
                        <td className="p-1 align-middle text-center text-emerald-600 dark:text-emerald-400 text-sm font-medium">
                          ${product.totalRevenue.toFixed(2)}
                        </td>
                        <td className="p-1 align-middle text-center text-muted-foreground text-sm">
                          {product.orderCount}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
};

export default ProductGrid;
