import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import axios from "axios";
import { apiClient } from "@/utils/apiClient";
import { toast } from "sonner";
import { Loader2, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
  PaginationEllipsis,
} from "@/components/ui/pagination";
import { ProductSearch } from "@/components/product-editor/ProductSearch";
import { ProductEditForm, LAYOUT_ICONS } from "@/components/product-editor/ProductEditForm";
import type { LayoutMode } from "@/components/product-editor/ProductEditForm";
import type { SearchProduct, FieldOptions, FieldOption, LineOption, LandingExtra, ProductImage } from "@/components/product-editor/types";
import { ExternalLink } from "lucide-react"; 

const PER_PAGE = 20;
const PROD_IMG_HOST = "https://sbing.com";

interface FilterSummaryItem {
  type: string;
  op: string;
  v1: string | null;
  v2: string | null;
  v1Label: string | null;
  v2Label: string | null;
}

const OP_SYMBOLS: Record<string, string> = {
  equals: "=",
  notequals: "≠",
  greater: ">",
  greater_equals: "≥",
  less: "<",
  less_equals: "≤",
  contains: "contains",
  notcontains: "excludes",
  begins: "starts with",
};

function formatFilterBadges(filters: FilterSummaryItem[]): { key: string; text: string }[] {
  // Group same type+op rows so "line=5 OR line=7" becomes "Line = Lawn Fawn, Carta Bella"
  const groups = new Map<string, { type: string; op: string; v1s: string[]; v2: string | null }>();
  for (const f of filters) {
    const key = `${f.type}:${f.op}`;
    const display = f.v1Label ?? f.v1;
    if (groups.has(key)) {
      if (display) groups.get(key)!.v1s.push(display);
    } else {
      groups.set(key, { type: f.type, op: f.op, v1s: display ? [display] : [], v2: f.v2Label ?? f.v2 });
    }
  }
  return Array.from(groups.entries()).map(([key, g]) => {
    const label = FILTER_LABELS[g.type] ?? g.type.replace(/_/g, " ");
    let text: string;
    if (["true", "true1"].includes(g.op)) {
      text = label;
    } else if (g.op === "false") {
      text = `not ${label}`;
    } else if (g.op === "isnull") {
      text = `${label} is empty`;
    } else if (g.op === "between" && g.v2) {
      text = `${label}: ${g.v1s[0] ?? ""}–${g.v2}`;
    } else {
      const sym = OP_SYMBOLS[g.op] ?? g.op;
      text = g.v1s.length ? `${label} ${sym} ${g.v1s.join(", ")}` : label;
    }
    return { key, text };
  });
}

const FILTER_LABELS: Record<string, string> = {
  company: "company",
  line: "line",
  subline: "subline",
  no_company: "no company",
  no_line: "no line",
  no_subline: "no subline",
  artist: "artist",
  price: "price",
  default_price: "default price",
  price_for_sort: "price for sort",
  salepercent_for_sort: "sale % for sort",
  "salepercent_for_sort__clearance": "sale % for sort (clearance)",
  weight: "weight",
  weight_price_ratio: "weight/price ratio",
  price_weight_ratio: "price/weight ratio",
  length: "length",
  width: "width",
  height: "height",
  no_dim: "no dimensions",
  size_cat: "size category",
  dimension: "dimension",
  yarn_weight: "yarn weight",
  material: "material",
  hide: "hidden",
  hide_in_shop: "hidden in shop",
  discontinued: "discontinued",
  force_flag: "force flag",
  exclusive: "exclusive",
  lock_quantity: "lock qty",
  show_notify: "show notify",
  downloadable: "downloadable",
  usa_only: "usa only",
  not_clearance: "not clearance",
  stat_stop: "stats stopped",
  notnew: "not new",
  not_backinstock: "not back-in-stock",
  reorder: "reorder",
  score: "score",
  sold_view_score: "sold/view score",
  visibility_score: "visibility score",
  health_score: "health score",
  tax_code: "tax code",
  investor: "investor",
  category: "category",
  theme: "theme",
  pid: "product id",
  basket: "basket",
  vendor: "vendor",
  vendor_reference: "supplier id",
  notions_reference: "notions id",
  itemnumber: "item number",
};

/** Strip all HTML except <b>, </b>, and <br> tags */
function sanitizeHtml(html: string): string {
  return html.replace(/<\/?(?!b>|br\s*\/?>)[^>]*>/gi, "");
}

/** Strip all HTML tags for use in plain text contexts */
function stripHtml(html: string): string {
  return html.replace(/<[^>]*>/g, "");
}

export default function ProductEditor() {
  const [allProducts, setAllProducts] = useState<SearchProduct[]>([]);
  const [fieldOptions, setFieldOptions] = useState<FieldOptions | null>(null);
  const [isLoadingOptions, setIsLoadingOptions] = useState(true);
  const [isLoadingProducts, setIsLoadingProducts] = useState(false);
  const [layoutMode, setLayoutMode] = useState<LayoutMode>("full");
  const [page, setPage] = useState(1);
  const [activeTab, setActiveTab] = useState("new");
  const [loadedTab, setLoadedTab] = useState<string | null>(null);

  // Query picker state
  const [queryId, setQueryId] = useState<string>("");
  const [queryStatus, setQueryStatus] = useState<{ id: string; name: string; count: number; filters: FilterSummaryItem[]; unsupported: string[] } | null>(null);

  // Line picker state
  const [lineCompany, setLineCompany] = useState<string>("");
  const [lineLine, setLineLine] = useState<string>("");
  const [lineSubline, setLineSubline] = useState<string>("");
  const [lineOptions, setLineOptions] = useState<LineOption[]>([]);
  const [sublineOptions, setSublineOptions] = useState<LineOption[]>([]);
  const [isLoadingLines, setIsLoadingLines] = useState(false);
  const [isLoadingSublines, setIsLoadingSublines] = useState(false);

  // Landing extras state
  const [landingExtras, setLandingExtras] = useState<Record<string, LandingExtra[]>>({});
  const [isLoadingExtras, setIsLoadingExtras] = useState(false);
  const [activeLandingItem, setActiveLandingItem] = useState<string | null>(null);
  const [viewingFeaturedExtra, setViewingFeaturedExtra] = useState<LandingExtra | null>(null);
  const [newFeedOnly, setNewFeedOnly] = useState(false);
  const [preorderFeedOnly, setPreorderFeedOnly] = useState(false);
  const [lineNewOnly, setLineNewOnly] = useState(false);
  const [linePreorderOnly, setLinePreorderOnly] = useState(false);

  // Abort controller for cancelling in-flight product requests
  const abortRef = useRef<AbortController | null>(null);

  const filteredProducts = useMemo(() => {
    if (viewingFeaturedExtra && activeTab === "new" && newFeedOnly) {
      return allProducts.filter((p) => p.is_new);
    }
    if (viewingFeaturedExtra && activeTab === "preorder" && preorderFeedOnly) {
      return allProducts.filter((p) => p.is_preorder);
    }
    if (activeTab === "by-line" && (lineNewOnly || linePreorderOnly)) {
      return allProducts.filter((p) =>
        (lineNewOnly && p.is_new) || (linePreorderOnly && p.is_preorder)
      );
    }
    return allProducts;
  }, [allProducts, viewingFeaturedExtra, activeTab, newFeedOnly, preorderFeedOnly, lineNewOnly, linePreorderOnly]);

  const totalPages = Math.ceil(filteredProducts.length / PER_PAGE);
  const products = useMemo(
    () => filteredProducts.slice((page - 1) * PER_PAGE, page * PER_PAGE),
    [filteredProducts, page]
  );

  // Batch-fetch images for the current page of products
  const [batchImages, setBatchImages] = useState<Record<number, ProductImage[]>>({});
  useEffect(() => {
    if (products.length === 0) return;
    const pids = products.map((p) => p.pid);
    const controller = new AbortController();
    apiClient
      .get("/api/import/product-images-batch", {
        params: { pids: pids.join(",") },
        signal: controller.signal,
      })
      .then((res) => {
        setBatchImages((prev) => ({ ...prev, ...res.data }));
      })
      .catch((e) => {
        if (!axios.isCancel(e)) console.error("Failed to batch-load images", e);
      });
    return () => controller.abort();
  }, [products]);

  useEffect(() => {
    apiClient
      .get("/api/import/field-options")
      .then((res) => setFieldOptions(res.data))
      .catch((err) => {
        console.error("Failed to load field options:", err);
        toast.error("Failed to load field options");
      })
      .finally(() => setIsLoadingOptions(false));
    // Auto-load the default tab
    handleTabChange("new");
  }, []);

  // Load lines when company changes
  useEffect(() => {
    setLineLine("");
    setLineSubline("");
    setLineOptions([]);
    setSublineOptions([]);
    if (!lineCompany) return;
    setIsLoadingLines(true);
    apiClient
      .get(`/api/import/product-lines/${lineCompany}`)
      .then((res) => setLineOptions(res.data))
      .catch(() => setLineOptions([]))
      .finally(() => setIsLoadingLines(false));
  }, [lineCompany]);

  // Load sublines when line changes
  useEffect(() => {
    setLineSubline("");
    setSublineOptions([]);
    if (!lineLine) return;
    setIsLoadingSublines(true);
    apiClient
      .get(`/api/import/sublines/${lineLine}`)
      .then((res) => setSublineOptions(res.data))
      .catch(() => setSublineOptions([]))
      .finally(() => setIsLoadingSublines(false));
  }, [lineLine]);

  const loadedPids = useMemo(
    () => new Set(allProducts.map((p) => Number(p.pid))),
    [allProducts]
  );

  const handleSearchSelect = useCallback((product: SearchProduct) => {
    setAllProducts((prev) => {
      if (prev.some((p) => p.pid === product.pid)) return prev;
      return [product, ...prev];
    });
    setPage(1);
  }, []);

  const handleNewSearch = useCallback(() => {
    setAllProducts([]);
    setPage(1);
  }, []);

  const handleLoadAllSearch = useCallback(async (pids: number[]) => {
    const hadExisting = allProducts.length > 0;
    setIsLoadingProducts(true);
    try {
      const res = await apiClient.get("/api/import/search-products", {
        params: { pid: pids.join(",") },
      });
      const fetched = res.data as SearchProduct[];
      setAllProducts((prev) => {
        const existingPids = new Set(prev.map((p) => p.pid));
        const newProducts = fetched.filter((p) => !existingPids.has(p.pid));
        return [...prev, ...newProducts];
      });
      setPage(1);
      if (fetched.length > 1) {
        toast.success(
          hadExisting
            ? `Loaded remaining ${fetched.length} products`
            : "Loaded all products"
        );
      }
    } catch {
      toast.error("Failed to load products");
    } finally {
      setIsLoadingProducts(false);
    }
  }, []);

  const handleRemoveProduct = useCallback((pid: number) => {
    setAllProducts((prev) => prev.filter((p) => p.pid !== pid));
  }, []);

  const loadFeedProducts = useCallback(async (endpoint: string, label: string) => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    setAllProducts([]);
    setIsLoadingProducts(true);
    try {
      const res = await apiClient.get(`/api/import/${endpoint}`, { signal: controller.signal });
      setAllProducts(res.data);
      setPage(1);
      toast.success(`Loaded ${res.data.length} ${label} products`);
    } catch (e) {
      if (!axios.isCancel(e)) toast.error(`Failed to load ${label} products`);
    } finally {
      setIsLoadingProducts(false);
    }
  }, []);

  const loadLandingExtras = useCallback(async (catId: number, tabKey: string) => {
    if (landingExtras[tabKey]) return;
    setIsLoadingExtras(true);
    try {
      const res = await apiClient.get("/api/import/landing-extras", {
        params: { catId, sid: 0 },
      });
      setLandingExtras((prev) => ({ ...prev, [tabKey]: res.data }));
    } catch {
      console.error("Failed to load landing extras");
    } finally {
      setIsLoadingExtras(false);
    }
  }, [landingExtras]);

  const handleLandingClick = useCallback(async (extra: LandingExtra) => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    setActiveLandingItem(extra.path);
    setViewingFeaturedExtra(extra);
    setNewFeedOnly(false);
    setPreorderFeedOnly(false);
    setAllProducts([]);
    setIsLoadingProducts(true);
    try {
      const res = await apiClient.get("/api/import/path-products", {
        params: { path: extra.path },
        signal: controller.signal,
      });
      setAllProducts(res.data);
      setPage(1);
      toast.success(`Loaded ${res.data.length} products for ${stripHtml(extra.name)}`);
    } catch (e) {
      if (!axios.isCancel(e)) toast.error("Failed to load products for " + stripHtml(extra.name));
    } finally {
      setIsLoadingProducts(false);
      setActiveLandingItem(null);
    }
  }, []);

  // Auto-load when switching tabs
  const handleTabChange = useCallback((tab: string) => {
    setActiveTab(tab);
    setQueryStatus(null);
    setQueryId("");
    setViewingFeaturedExtra(null);
    setNewFeedOnly(false);
    setPreorderFeedOnly(false);
    setLineNewOnly(false);
    setLinePreorderOnly(false);
    if (tab === "new" && loadedTab !== "new") {
      setLoadedTab("new");
      loadFeedProducts("new-products", "new");
      loadLandingExtras(-2, "new");
    } else if (tab === "preorder" && loadedTab !== "preorder") {
      setLoadedTab("preorder");
      loadFeedProducts("preorder-products", "pre-order");
      loadLandingExtras(-16, "preorder");
    } else if (tab === "hidden" && loadedTab !== "hidden") {
      setLoadedTab("hidden");
      loadFeedProducts("hidden-new-products", "hidden");
    } else if (tab === "search" || tab === "by-line" || tab === "by-query") {
      abortRef.current?.abort();
      setAllProducts([]);
      setPage(1);
    }
  }, [loadedTab, loadFeedProducts, loadLandingExtras]);

  const loadLineProducts = useCallback(async () => {
    if (!lineCompany || !lineLine) return;
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    setAllProducts([]);
    setIsLoadingProducts(true);
    setLineNewOnly(false);
    setLinePreorderOnly(false);
    try {
      const params: Record<string, string> = { company: lineCompany, line: lineLine };
      if (lineSubline) params.subline = lineSubline;
      const res = await apiClient.get("/api/import/line-products", { params, signal: controller.signal });
      setAllProducts(res.data);
      setPage(1);
      toast.success(`Loaded ${res.data.length} products`);
    } catch (e) {
      if (!axios.isCancel(e)) toast.error("Failed to load line products");
    } finally {
      setIsLoadingProducts(false);
    }
  }, [lineCompany, lineLine, lineSubline]);

  const loadQueryProducts = useCallback(async () => {
    const qid = queryId.trim();
    if (!qid || isNaN(Number(qid))) return;
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    setAllProducts([]);
    setQueryStatus(null);
    setIsLoadingProducts(true);
    try {
      const res = await apiClient.get("/api/import/query-products", {
        params: { query_id: qid },
        signal: controller.signal,
      });
      const { results, filters, unsupported } = res.data;
      setAllProducts(results);
      setPage(1);
      setQueryStatus({
        id: qid,
        name: res.headers["x-query-name"] || "",
        count: results.length,
        filters: filters ?? [],
        unsupported: unsupported ?? [],
      });
      if (unsupported?.length) {
        toast.warning(`Query #${qid}: ${unsupported.length} unsupported filter(s) removed — results may be broader than expected`);
      }
    } catch (e) {
      if (!axios.isCancel(e)) toast.error("Failed to load query products");
    } finally {
      setIsLoadingProducts(false);
    }
  }, [queryId]);

  const renderLandingExtras = (tabKey: string) => {
    const extras = landingExtras[tabKey];
    if (!extras || extras.length === 0) return null;

    return (
      <div className="mb-4">
        <div className="flex gap-3 overflow-x-auto pb-2 items-start">
          {extras.map((extra) => (
            <button
              key={extra.extra_id}
              onClick={() => handleLandingClick(extra)}
              disabled={activeLandingItem === extra.path}
              className="flex-shrink-0 group relative w-28 text-left"
            >
              <div className="aspect-square w-full overflow-hidden rounded-lg border bg-card hover:bg-accent transition-colors relative">
                {extra.image && (
                  <img
                    src={extra.image.startsWith("/") ? PROD_IMG_HOST + extra.image : extra.image}
                    alt={stripHtml(extra.name)}
                    className="w-full h-full object-cover group-hover:scale-105 transition-transform"
                    loading="lazy"
                  />
                )}
                {activeLandingItem === extra.path && (
                  <div className="absolute inset-0 flex items-center justify-center bg-background/60">
                    <Loader2 className="h-4 w-4 animate-spin" />
                  </div>
                )}
              </div>
              <div className="pt-1 text-center">
                {(() => {
                  const parts = extra.name.split(/<br\s*\/?>/i).map(stripHtml);
                  return (
                    <div className="text-xs leading-snug">
                      {parts[0] && <span className="font-semibold">{parts[0]}</span>}
                      {parts[1] && <><br /><span className="font-normal">{parts[1]}</span></>}
                    </div>
                  );
                })()}
                {extra.top_text && (
                  <div
                    className="text-[10px] text-muted-foreground mt-0.5"
                    dangerouslySetInnerHTML={{ __html: sanitizeHtml(extra.top_text) }}
                  />
                )}
              </div>
            </button>
          ))}
        </div>
      </div>
    );
  };

  const renderPagination = () => {
    if (totalPages <= 1) return null;

    const getPageNumbers = () => {
      const pages: (number | "ellipsis")[] = [];
      if (totalPages <= 7) {
        for (let i = 1; i <= totalPages; i++) pages.push(i);
      } else {
        pages.push(1);
        if (page > 3) pages.push("ellipsis");
        for (let i = Math.max(2, page - 1); i <= Math.min(totalPages - 1, page + 1); i++) {
          pages.push(i);
        }
        if (page < totalPages - 2) pages.push("ellipsis");
        pages.push(totalPages);
      }
      return pages;
    };

    return (
      <Pagination>
        <PaginationContent>
          <PaginationItem>
            <PaginationPrevious
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              className={page === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
            />
          </PaginationItem>
          {getPageNumbers().map((p, i) =>
            p === "ellipsis" ? (
              <PaginationItem key={`e${i}`}>
                <PaginationEllipsis />
              </PaginationItem>
            ) : (
              <PaginationItem key={p}>
                <PaginationLink
                  isActive={p === page}
                  onClick={() => setPage(p)}
                  className="cursor-pointer"
                >
                  {p}
                </PaginationLink>
              </PaginationItem>
            )
          )}
          <PaginationItem>
            <PaginationNext
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              className={page === totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
            />
          </PaginationItem>
        </PaginationContent>
      </Pagination>
    );
  };

  if (isLoadingOptions) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="container mx-auto py-6 max-w-4xl space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Product Editor</h1>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-sm text-muted-foreground">Layout: </span>
          <ToggleGroup
            type="single"
            value={layoutMode}
            onValueChange={(v) => { if (v) setLayoutMode(v as LayoutMode); }}
          >
            {LAYOUT_ICONS.map(({ mode, label, icon: Icon }) => (
              <Tooltip key={mode}>
                <TooltipTrigger asChild>
                  <ToggleGroupItem value={mode} size="sm" variant="outline">
                    <Icon className="h-4 w-4" />
                    <span className="text-xs">{label}</span>
                  </ToggleGroupItem>
                </TooltipTrigger>
                <TooltipContent side="bottom">{label}</TooltipContent>
              </Tooltip>
            ))}
          </ToggleGroup>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={handleTabChange}>
        <TabsList>
          <TabsTrigger value="new">New</TabsTrigger>
          <TabsTrigger value="preorder">Pre-Order</TabsTrigger>
          <TabsTrigger value="hidden">Hidden (New)</TabsTrigger>
          <TabsTrigger value="by-line">By Line</TabsTrigger>
          <TabsTrigger value="by-query">By Query</TabsTrigger>
          <TabsTrigger value="search">Search</TabsTrigger>
        </TabsList>

        <TabsContent value="search" className="mt-4">
          <ProductSearch
            onSelect={handleSearchSelect}
            onLoadAll={handleLoadAllSearch}
            onNewSearch={handleNewSearch}
            loadedPids={loadedPids}
          />
        </TabsContent>

        <TabsContent value="by-query" className="mt-4">
          <div className="flex items-center gap-3">
            <Input
              placeholder="Query ID..."
              value={queryId}
              onChange={(e) => setQueryId(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") loadQueryProducts(); }}
              className="w-52"
            />
            <Button onClick={loadQueryProducts} disabled={!queryId.trim() || isNaN(Number(queryId)) || isLoadingProducts}>
              {isLoadingProducts && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
              Load
            </Button>
            {queryStatus && (
              <Button variant="outline" size="icon" onClick={loadQueryProducts} disabled={isLoadingProducts} title="Refresh query results">
                <RefreshCw className="h-4 w-4" />
              </Button>
            )}
          </div>
          {isLoadingProducts && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground mt-3">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading products...
            </div>
          )}
          {queryStatus && !isLoadingProducts && (
            <div className="mt-3 text-sm text-muted-foreground space-y-1.5">
              <div>
                Showing {queryStatus.count} product{queryStatus.count !== 1 ? "s" : ""} from query {queryStatus.id}
                {queryStatus.name ? ` — ${queryStatus.name}` : ""}.{" "}
                <a
                  href={`https://backend.acherryontop.com/product_tool/${queryStatus.id}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 underline hover:text-foreground"
                >
                  Open in Product Tool <ExternalLink className="h-3 w-3" />
                </a>
              </div>
              {queryStatus.filters.length > 0 && (
                <div className="flex flex-wrap gap-1 items-center">
                  <span className="text-xs">Filters:</span>
                  {formatFilterBadges(queryStatus.filters).map(({ key, text }) => (
                    <span key={key} className="inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs font-medium">
                      {text}
                    </span>
                  ))}
                </div>
              )}
              {queryStatus.unsupported.length > 0 && (
                <div className="text-amber-600 dark:text-amber-400">
                  {queryStatus.unsupported.length} filter type{queryStatus.unsupported.length !== 1 ? "s" : ""} not supported ({queryStatus.unsupported.join(", ")}). Results may be broader than expected.
                </div>
              )}
            </div>
          )}
        </TabsContent>

        <TabsContent value="new" className="mt-4">
          {isLoadingExtras && !landingExtras["new"] && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground mb-3">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading featured lines...
            </div>
          )}
          {renderLandingExtras("new")}
          {viewingFeaturedExtra && activeTab === "new" && !isLoadingProducts && allProducts.length > 0 && !allProducts.every((p) => p.is_new) && (
            <div className="flex items-center space-x-2 mb-3">
              <Switch
                id="new-only"
                checked={newFeedOnly}
                onCheckedChange={(checked) => {
                  setNewFeedOnly(checked);
                  setPage(1);
                }}
              />
              <Label htmlFor="new-only" className="text-sm text-muted-foreground">Show only new products</Label>
              {newFeedOnly && (
                <span className="text-xs text-muted-foreground">{filteredProducts.length} of {allProducts.length}</span>
              )}
            </div>
          )}
          {isLoadingProducts && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading products...
            </div>
          )}
        </TabsContent>

        <TabsContent value="preorder" className="mt-4">
          {isLoadingExtras && !landingExtras["preorder"] && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground mb-3">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading featured lines...
            </div>
          )}
          {renderLandingExtras("preorder")}
          {viewingFeaturedExtra && activeTab === "preorder" && !isLoadingProducts && allProducts.length > 0 && !allProducts.every((p) => p.is_preorder) && (
            <div className="flex items-center space-x-2 mb-3">
              <Switch
                id="preorder-only"
                checked={preorderFeedOnly}
                onCheckedChange={(checked) => {
                  setPreorderFeedOnly(checked);
                  setPage(1);
                }}
              />
              <Label htmlFor="preorder-only" className="text-sm text-muted-foreground">Show only pre-order products</Label>
              {preorderFeedOnly && (
                <span className="text-xs text-muted-foreground">{filteredProducts.length} of {allProducts.length}</span>
              )}
            </div>
          )}
          {isLoadingProducts && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading products...
            </div>
          )}
        </TabsContent>

        <TabsContent value="hidden" className="mt-4">
          {isLoadingProducts && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading products...
            </div>
          )}
        </TabsContent>

        <TabsContent value="by-line" className="mt-4">
          <div className="flex items-center gap-3">
            <Select value={lineCompany} onValueChange={setLineCompany}>
              <SelectTrigger className="w-52">
                <SelectValue placeholder="Select company..." />
              </SelectTrigger>
              <SelectContent>
                {fieldOptions?.companies.map((c: FieldOption) => (
                  <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={lineLine} onValueChange={setLineLine} disabled={!lineCompany || isLoadingLines}>
              <SelectTrigger className="w-52">
                <SelectValue placeholder={isLoadingLines ? "Loading..." : "Select line..."} />
              </SelectTrigger>
              <SelectContent>
                {lineOptions.map((l) => (
                  <SelectItem key={l.value} value={l.value}>{l.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            {sublineOptions.length > 0 && (
              <Select value={lineSubline} onValueChange={setLineSubline} disabled={isLoadingSublines}>
                <SelectTrigger className="w-52">
                  <SelectValue placeholder={isLoadingSublines ? "Loading..." : "All sublines"} />
                </SelectTrigger>
                <SelectContent>
                  {sublineOptions.map((s) => (
                    <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
            <Button onClick={loadLineProducts} disabled={!lineLine || isLoadingProducts}>
              {isLoadingProducts && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
              Load
            </Button>
          </div>
          {isLoadingProducts && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground mt-3">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading products...
            </div>
          )}
          {!isLoadingProducts && allProducts.length > 0 && activeTab === "by-line" && (allProducts.some((p) => p.is_new && !p.is_preorder) || allProducts.some((p) => p.is_preorder)) && (
            <div className="flex items-center gap-4 mt-3">
              {!allProducts.every((p) => p.is_new) && allProducts.some((p) => p.is_new) && (
                <div className="flex items-center space-x-2">
                  <Switch
                    id="line-new-only"
                    checked={lineNewOnly}
                    onCheckedChange={(checked) => {
                      setLineNewOnly(checked);
                      setPage(1);
                    }}
                  />
                  <Label htmlFor="line-new-only" className="text-sm text-muted-foreground">Show only new products</Label>
                </div>
              )}
              {!allProducts.every((p) => p.is_preorder) && allProducts.some((p) => p.is_preorder) && (
                <div className="flex items-center space-x-2">
                  <Switch
                    id="line-preorder-only"
                    checked={linePreorderOnly}
                    onCheckedChange={(checked) => {
                      setLinePreorderOnly(checked);
                      setPage(1);
                    }}
                  />
                  <Label htmlFor="line-preorder-only" className="text-sm text-muted-foreground">Show only pre-order</Label>
                </div>
              )}
              {(lineNewOnly || linePreorderOnly) && (
                <span className="text-xs text-muted-foreground">{filteredProducts.length} of {allProducts.length}</span>
              )}
            </div>
          )}
        </TabsContent>
      </Tabs>

      {renderPagination()}

      {products.length > 0 && fieldOptions && (
        <div className="space-y-4">
          {products.map((product) => (
            <ProductEditForm
              key={product.pid}
              product={product}
              fieldOptions={fieldOptions}
              layoutMode={layoutMode}
              initialImages={batchImages[product.pid]}
              onClose={() => handleRemoveProduct(product.pid)}
            />
          ))}
        </div>
      )}

      {renderPagination()}
    </div>
  );
}
