import React, { useState, useEffect } from "react";
import axios from "axios";
import { acotService } from "@/services/dashboard/acotService";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, ArrowUpDown, AlertCircle, Package, Settings2, Search, X } from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { BusinessRangeSelect } from "@/components/dashboard/shared/BusinessRangeSelect";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { CARD_STYLES, TYPOGRAPHY } from "@/lib/dashboard/designTokens";
import { DashboardEmptyState, DashboardErrorState } from "@/components/dashboard/shared";

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("");
  const [isSearchVisible, setIsSearchVisible] = useState(false);

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

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

      const response = await acotService.getProducts({ timeRange: selectedTimeRange });
      setProducts(response.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 className="hover:bg-muted/50 transition-colors">
      <td className="p-1 align-middle w-[50px]">
        <Skeleton className="h-[50px] w-[50px] rounded bg-muted" />
      </td>
      <td className="p-1 align-middle min-w-[200px]">
        <div className="flex flex-col gap-1.5">
          <Skeleton className="h-4 w-[180px] bg-muted rounded-sm" />
          <Skeleton className="h-3 w-[140px] bg-muted rounded-sm" />
        </div>
      </td>
      <td className="p-1 align-middle text-center">
        <Skeleton className="h-4 w-8 mx-auto bg-muted rounded-sm" />
      </td>
      <td className="p-1 align-middle text-center">
        <Skeleton className="h-4 w-16 mx-auto bg-muted rounded-sm" />
      </td>
      <td className="p-1 align-middle text-center">
        <Skeleton className="h-4 w-8 mx-auto bg-muted rounded-sm" />
      </td>
    </tr>
  );

  const LoadingState = () => (
    <div className="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-card z-10 w-[50px] min-w-[50px] border-b border-border/50" />
              <th className="p-1.5 text-left font-medium sticky top-0 bg-card z-10 min-w-[200px] border-b border-border/50">
                <Button
                  variant="ghost"
                  className="w-full p-2 justify-start h-8 pointer-events-none"
                  disabled
                >
                  <Skeleton className="h-4 w-16 bg-muted rounded-sm" />
                </Button>
              </th>
              <th className="p-1.5 font-medium text-center sticky top-0 bg-card z-10 border-b border-border/50">
                <Button
                  variant="ghost"
                  className="w-full p-2 justify-center h-8 pointer-events-none"
                  disabled
                >
                  <Skeleton className="h-4 w-12 bg-muted rounded-sm" />
                </Button>
              </th>
              <th className="p-1.5 font-medium text-center sticky top-0 bg-card z-10 border-b border-border/50">
                <Button
                  variant="ghost"
                  className="w-full p-2 justify-center h-8 pointer-events-none"
                  disabled
                >
                  <Skeleton className="h-4 w-12 bg-muted rounded-sm" />
                </Button>
              </th>
              <th className="p-1.5 font-medium text-center sticky top-0 bg-card z-10 border-b border-border/50">
                <Button
                  variant="ghost"
                  className="w-full p-2 justify-center h-8 pointer-events-none"
                  disabled
                >
                  <Skeleton className="h-4 w-16 bg-muted rounded-sm" />
                </Button>
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border/50">
            {[...Array(20)].map((_, i) => (
              <SkeletonProduct key={i} />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  if (loading) {
    return (
      <Card className={`flex flex-col h-full ${CARD_STYLES.base}`}>
        <CardHeader className="p-6 pb-4">
          <div className="flex flex-col gap-4">
            <div className="flex justify-between items-start">
              <div>
                <CardTitle className={TYPOGRAPHY.sectionTitle}>
                  <Skeleton className="h-6 w-32 bg-muted rounded-sm" />
                </CardTitle>
                {description && (
                  <CardDescription className="mt-1">
                    <Skeleton className="h-4 w-48 bg-muted rounded-sm" />
                  </CardDescription>
                )}
              </div>
              <div className="flex items-center gap-2">
                <Skeleton className="h-9 w-9 bg-muted rounded-sm" />
                <Skeleton className="h-9 w-[130px] bg-muted rounded-sm" />
              </div>
            </div>
          </div>
        </CardHeader>

        <CardContent className="p-6 pt-0 flex-1 overflow-hidden -mt-1">
          <div className="h-full">
            <LoadingState />
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className={`flex flex-col h-full ${CARD_STYLES.base}`}>
      <CardHeader className="p-6 pb-4">
        <div className="flex flex-col gap-4">
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className={TYPOGRAPHY.sectionTitle}>{title}</CardTitle>
              {description && (
                <CardDescription className={`mt-1 ${TYPOGRAPHY.cardDescription}`}>{description}</CardDescription>
              )}
            </div>
            <div className="flex items-center gap-2">
              {!error && (
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setIsSearchVisible(!isSearchVisible)}
                  className={cn(
                    "h-9 w-9",
                    isSearchVisible && "bg-muted"
                  )}
                >
                  <Search className="h-4 w-4" />
                </Button>
              )}
              <BusinessRangeSelect
                value={selectedTimeRange}
                onValueChange={handleTimeRangeChange}
              />
            </div>
          </div>
          {isSearchVisible && !error && (
            <div className="relative w-full">
              <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search products..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9 pr-9 h-9 w-full"
                autoFocus
              />
              {searchQuery && (
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute right-1 top-1 h-7 w-7"
                  onClick={() => setSearchQuery("")}
                >
                  <X className="h-4 w-4" />
                </Button>
              )}
            </div>
          )}
        </div>
      </CardHeader>

      <CardContent className="p-6 pt-0 flex-1 overflow-hidden -mt-1">
        <div className="h-full">
          {error ? (
            <DashboardErrorState error={`Failed to load products: ${error}`} className="mx-0 my-0" />
          ) : !products?.length ? (
            <DashboardEmptyState
              icon={Package}
              title="No product data available"
              description="Try selecting a different time range"
              height="sm"
            />
          ) : (
            <div className="h-full">
              <div className="overflow-y-auto h-full">
                <table className="w-full">
                  <thead>
                    <tr className="hover:bg-transparent">
                      <th className="p-1 text-left font-medium sticky top-0 bg-card z-10 h-[50px] min-h-[50px] w-[50px] min-w-[35px] border-b border-border/50" />
                      <th className="p-1 text-left font-medium sticky top-0 bg-card z-10 border-b border-border/50">
                        <Button
                          variant={sorting.column === "name" ? "default" : "ghost"}
                          onClick={() => handleSort("name")}
                          className="w-full p-2 justify-start h-8"
                        >
                          Product
                        </Button>
                      </th>
                      <th className="p-1 font-medium text-center sticky top-0 bg-card z-10 border-b border-border/50">
                        <Button
                          variant={sorting.column === "totalQuantity" ? "default" : "ghost"}
                          onClick={() => handleSort("totalQuantity")}
                          className="w-full p-2 justify-center h-8"
                        >
                          Sold
                        </Button>
                      </th>
                      <th className="p-1 font-medium text-center sticky top-0 bg-card z-10 border-b border-border/50">
                        <Button
                          variant={sorting.column === "totalRevenue" ? "default" : "ghost"}
                          onClick={() => handleSort("totalRevenue")}
                          className="w-full p-2 justify-center h-8"
                        >
                          Rev
                        </Button>
                      </th>
                      <th className="p-1 font-medium text-center sticky top-0 bg-card z-10 border-b border-border/50">
                        <Button
                          variant={sorting.column === "orderCount" ? "default" : "ghost"}
                          onClick={() => handleSort("orderCount")}
                          className="w-full p-2 justify-center h-8"
                        >
                          Orders
                        </Button>
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/50">
                    {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 w-[50px] h-[50px] object-contain"
                              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-foreground"
                                  >
                                    {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 text-foreground">
                          {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;
