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 } 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 { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import {
  TIME_RANGES,
  formatDateForInput,
  parseDateFromInput,
} from "@/lib/constants";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";

const ProductGrid = ({
  timeRange = "today",
  startDate,
  endDate,
  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 [customDateRange, setCustomDateRange] = useState({
    startDate: formatDateForInput(startDate) || "",
    endDate: formatDateForInput(endDate) || "",
  });
  const [sorting, setSorting] = useState({
    column: "totalQuantity",
    direction: "desc",
  });

  useEffect(() => {
    fetchProducts();
  }, [selectedTimeRange, customDateRange.startDate, customDateRange.endDate]);

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

      const params =
        selectedTimeRange === "custom"
          ? {
              startDate: parseDateFromInput(
                customDateRange.startDate
              )?.toISOString(),
              endDate: parseDateFromInput(
                customDateRange.endDate
              )?.toISOString(),
            }
          : { timeRange: selectedTimeRange };

      const response = await axios.get("/api/klaviyo/events/products", {
        params,
      });
      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 SkeletonProduct = () => (
    <TableRow>
      <TableCell className="w-[50px] p-1">
        <Skeleton className="h-[50px] w-[50px] rounded" />
      </TableCell>
      <TableCell className="min-w-[200px] px-0">
        <div className="flex flex-col gap-2">
          <Skeleton className="h-4 w-[200px]" />
          <Skeleton className="h-4 w-[150px]" />
        </div>
      </TableCell>
      <TableCell className="text-center px-0">
        <Skeleton className="h-4 w-12 mx-auto" />
      </TableCell>
      <TableCell className="text-center px-0">
        <Skeleton className="h-4 w-20 mx-auto" />
      </TableCell>
      <TableCell className="text-center px-0">
        <Skeleton className="h-4 w-16 mx-auto" />
      </TableCell>
      <TableCell className="text-center hidden md:table-cell px-0">
        <Skeleton className="h-4 w-16 mx-auto" />
      </TableCell>
    </TableRow>
  );

  const LoadingState = () => (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <Skeleton className="h-6 w-48 mb-2" />
          <Skeleton className="h-4 w-64" />
        </div>
        <div className="flex items-center gap-4">
          <Skeleton className="h-9 w-[180px]" />
        </div>
      </div>
      <Table>
        <TableHeader>
          <TableRow className="hover:bg-transparent">
            <TableHead className="w-[50px] min-w-[50px]">
              <Skeleton className="h-4 w-4" />
            </TableHead>
            <TableHead className="min-w-[200px]">
              <Skeleton className="h-4 w-24" />
            </TableHead>
            <TableHead className="text-right">
              <Skeleton className="h-4 w-16 ml-auto" />
            </TableHead>
            <TableHead className="text-right">
              <Skeleton className="h-4 w-16 ml-auto" />
            </TableHead>
            <TableHead className="text-right">
              <Skeleton className="h-4 w-16 ml-auto" />
            </TableHead>
            <TableHead className="text-right hidden md:table-cell">
              <Skeleton className="h-4 w-16 ml-auto" />
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {[...Array(10)].map((_, i) => (
            <SkeletonProduct key={i} />
          ))}
        </TableBody>
      </Table>
    </div>
  );

  return (
    <Card className="flex flex-col h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <CardHeader className="p-6">
        <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">
            <Select
              value={selectedTimeRange}
              onValueChange={handleTimeRangeChange}
            >
              <SelectTrigger className="w-[180px] h-9">
                <SelectValue placeholder="Select time range" />
              </SelectTrigger>
              <SelectContent>
                {TIME_RANGES.map((range) => (
                  <SelectItem key={range.value} value={range.value}>
                    {range.label}
                  </SelectItem>
                ))}
                <SelectItem value="custom">Custom Range</SelectItem>
              </SelectContent>
            </Select>

            {selectedTimeRange === "custom" && (
              <div className="flex gap-2">
                <div>
                  <Label htmlFor="startDate" className="sr-only">
                    Start Date
                  </Label>
                  <Input
                    id="startDate"
                    type="datetime-local"
                    value={customDateRange.startDate}
                    onChange={(e) =>
                      setCustomDateRange((prev) => ({
                        ...prev,
                        startDate: e.target.value,
                      }))
                    }
                    className="h-9"
                  />
                </div>
                <div>
                  <Label htmlFor="endDate" className="sr-only">
                    End Date
                  </Label>
                  <Input
                    id="endDate"
                    type="datetime-local"
                    value={customDateRange.endDate}
                    onChange={(e) =>
                      setCustomDateRange((prev) => ({
                        ...prev,
                        endDate: e.target.value,
                      }))
                    }
                    className="h-9"
                  />
                </div>
              </div>
            )}
          </div>
        </div>
      </CardHeader>

      <CardContent className="p-6 pt-0 flex-1 overflow-hidden">
        <ScrollArea className="h-full">
          {loading && !products.length ? (
            <LoadingState />
          ) : error ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <AlertCircle className="h-12 w-12 text-destructive mb-4" />
              <p className="font-medium mb-2">Error loading products</p>
              <p className="text-sm text-muted-foreground">{error}</p>
            </div>
          ) : !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>
          ) : (
            <Table>
              <TableHeader>
                <TableRow className="hover:bg-transparent">
                  <TableHead className="w-[50px] min-w-[50px]" />
                  <TableHead className="min-w-[200px] pr-0 pl-1">
                    <Button
                      variant="ghost"
                      onClick={() => handleSort("name")}
                      className="h-8 justify-start w-full font-medium hover:bg-transparent"
                    >
                      Product
                      <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                  </TableHead>
                  <TableHead className="text-right px-0">
                    <Button
                      variant="ghost"
                      onClick={() => handleSort("totalQuantity")}
                      className="h-8 justify-end w-full font-medium hover:bg-transparent"
                    >
                      Sold
                      <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                  </TableHead>
                  <TableHead className="text-right px-0">
                    <Button
                      variant="ghost"
                      onClick={() => handleSort("totalRevenue")}
                      className="h-8 justify-end w-full font-medium hover:bg-transparent"
                    >
                      Rev
                      <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                  </TableHead>
                  <TableHead className="text-right px-0">
                    <Button
                      variant="ghost"
                      onClick={() => handleSort("orderCount")}
                      className="h-8 justify-end w-full font-medium hover:bg-transparent"
                    >
                      Orders
                      <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                  </TableHead>
                  <TableHead className="text-right hidden md:table-cell">
                    <Button
                      variant="ghost"
                      onClick={() => handleSort("price")}
                      className="h-8 justify-end w-full font-medium hover:bg-transparent"
                    >
                      Price
                      <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {sortedProducts.map((product) => (
                  <TableRow
                    key={product.id}
                    className="group hover:bg-muted/50"
                  >
                    <TableCell className="w-[50px] p-1">
                      {product.ImgThumb && (
                        <img
                          src={product.ImgThumb}
                          alt=""
                          width={50}
                          height={50}
                          className="rounded bg-muted"
                          onError={(e) => (e.target.style.display = "none")}
                        />
                      )}
                    </TableCell>
                    <TableCell className="min-w-[200px] px-0">
                      <div className="flex flex-col min-w-0">
                        <a
                          href={`https://backend.acherryontop.com/product/${product.id}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="font-medium hover:underline line-clamp-2 text-gray-900 dark:text-gray-100"
                        >
                          {product.name}
                        </a>
                        <div className="flex gap-2 text-sm text-muted-foreground px-0">
                          <span>${product.price.toFixed(2)}</span>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center font-medium px-0">
                      {product.totalQuantity}
                    </TableCell>
                    <TableCell className="text-center text-emerald-600 dark:text-emerald-400 font-medium px-0">
                      ${product.totalRevenue.toFixed(2)}
                    </TableCell>
                    <TableCell className="text-center text-muted-foreground px-0">
                      {product.orderCount}
                    </TableCell>
                    <TableCell className="text-center hidden md:table-cell px-0">
                      ${product.price.toFixed(2)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </ScrollArea>
      </CardContent>
    </Card>
  );
};

export default ProductGrid;
