import React, { useState, useEffect } from "react";
import { acotService } from "@/services/dashboard/acotService";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Package, Search, X } from "lucide-react";
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 { CARD_STYLES } from "@/lib/dashboard/designTokens";
import { DashboardEmptyState, DashboardErrorState } from "@/components/dashboard/shared";

/**
 * Top Sellers — ranked product list (Sorbet Studio).
 * Rank badges cycle the pastel tile fills; revenue is the bold right column.
 */

const RANK_FILLS = ["#fbe7de", "#ddf0ea", "#faf0d7", "#eae6f6"];

const SORTS = [
  { key: "totalQuantity", label: "Sold" },
  { key: "totalRevenue", label: "Revenue" },
];

const ProductGrid = ({
  timeRange = "today",
  onTimeRangeChange,
  title = "Top sellers",
}) => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedTimeRange, setSelectedTimeRange] = useState(timeRange);
  const [sortKey, setSortKey] = useState("totalQuantity");
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearchVisible, setIsSearchVisible] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await acotService.getProducts({ timeRange: selectedTimeRange });
        if (!cancelled) setProducts(response.stats.products.list || []);
      } catch (err) {
        console.error("Error fetching products:", err);
        if (!cancelled) setError(err.message);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [selectedTimeRange]);

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

  const ranked = [...products].sort((a, b) => (b[sortKey] || 0) - (a[sortKey] || 0));
  const filtered = ranked.filter((product) =>
    product.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <Card className={`flex flex-col h-full ${CARD_STYLES.base}`}>
      <CardHeader className="border-b border-[#f0eeea] px-4 py-3">
        <div className="flex items-center justify-between gap-3">
          <CardTitle className="text-[12.5px] font-semibold tracking-tight text-[#2b2925]">
            {title}
          </CardTitle>
          <div className="flex items-center gap-1.5">
            <div className="flex items-center gap-0.5">
              {SORTS.map(({ key, label }) => (
                <button
                  key={key}
                  type="button"
                  onClick={() => setSortKey(key)}
                  className={cn(
                    "h-7 rounded-full px-2.5 text-xs font-medium transition-colors",
                    sortKey === key
                      ? "bg-[#f0eeea] text-[#2b2925]"
                      : "text-[#a09b92] hover:bg-[#f5f3f0] hover:text-[#2b2925]"
                  )}
                >
                  {label}
                </button>
              ))}
            </div>
            {!error && (
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setIsSearchVisible(!isSearchVisible)}
                className={cn(
                  "h-8 w-8 rounded-full text-[#7c7870] hover:bg-[#f5f3f0]",
                  isSearchVisible && "bg-[#f0eeea] text-[#2b2925]"
                )}
              >
                <Search className="h-3.5 w-3.5" />
              </Button>
            )}
            <BusinessRangeSelect
              value={selectedTimeRange}
              onValueChange={handleTimeRangeChange}
            />
          </div>
        </div>
        {isSearchVisible && !error && (
          <div className="relative w-full pt-1.5">
            <Search className="absolute left-3 top-[15px] h-3.5 w-3.5 text-[#a09b92]" />
            <Input
              placeholder="Search products…"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-8 w-full rounded-full border-[#e7e5e1] pl-9 pr-9 text-xs shadow-none"
              autoFocus
            />
            {searchQuery && (
              <Button
                variant="ghost"
                size="icon"
                className="absolute right-1 top-[7px] h-7 w-7 rounded-full"
                onClick={() => setSearchQuery("")}
              >
                <X className="h-3.5 w-3.5" />
              </Button>
            )}
          </div>
        )}
      </CardHeader>

      <CardContent className="flex-1 overflow-hidden p-0">
        {loading ? (
          <div>
            {[...Array(8)].map((_, i) => (
              <div
                key={i}
                className="flex items-center gap-3 border-b border-[#f5f3f0] px-4 py-2.5 last:border-b-0"
              >
                <div className="h-7 w-7 animate-pulse rounded-lg bg-[#f0eeea]" />
                <div className="h-9 w-9 animate-pulse rounded-lg bg-[#f5f3f0]" />
                <div className="flex-1">
                  <div className="h-3.5 w-3/4 animate-pulse rounded bg-[#f0eeea]" />
                  <div className="mt-1.5 h-3 w-24 animate-pulse rounded bg-[#f5f3f0]" />
                </div>
                <div className="h-4 w-14 animate-pulse rounded bg-[#f0eeea]" />
              </div>
            ))}
          </div>
        ) : error ? (
          <DashboardErrorState error={`Failed to load products: ${error}`} className="m-4" />
        ) : !filtered.length ? (
          <DashboardEmptyState
            icon={Package}
            title="No product data available"
            description="Try selecting a different time range"
            height="sm"
          />
        ) : (
          <div className="h-full overflow-y-auto">
            {filtered.map((product, index) => (
              <a
                key={product.id}
                href={`https://backend.acherryontop.com/product/${product.id}`}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-3 border-b border-[#f5f3f0] px-4 py-2 transition-colors last:border-b-0 hover:bg-[#faf9f7]"
              >
                <span
                  className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-xs font-bold tabular-nums text-[#2b2925]"
                  style={{
                    background: index < 4 ? RANK_FILLS[index] : "#f5f3f0",
                    color: index < 4 ? "#2b2925" : "#a09b92",
                  }}
                >
                  {index + 1}
                </span>
                {product.ImgThumb ? (
                  <img
                    src={product.ImgThumb}
                    alt=""
                    width={36}
                    height={36}
                    className="h-9 w-9 shrink-0 rounded-lg bg-[#faf9f7] object-contain"
                    onError={(e) => (e.target.style.visibility = "hidden")}
                  />
                ) : (
                  <span className="h-9 w-9 shrink-0 rounded-lg bg-[#faf9f7]" />
                )}
                <div className="min-w-0 flex-1">
                  <div className="truncate text-[13px] font-medium text-[#2b2925]">
                    {product.name}
                  </div>
                  <div className="text-[11px] text-[#7c7870]">
                    {product.totalQuantity} sold · {product.orderCount}{" "}
                    {product.orderCount === 1 ? "order" : "orders"}
                  </div>
                </div>
                <span className="shrink-0 text-[13px] font-bold tabular-nums text-[#2b2925]">
                  ${product.totalRevenue.toFixed(2)}
                </span>
              </a>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default ProductGrid;
