import React, { useState, useEffect, useRef } from "react";
import { DataTable } from "../ui/DataTable";
import { Pagination } from "../ui/Pagination";
import { Filters } from "../ui/Filters";
import { cn } from "../../../lib/utils";
import { getProductsPage, getProductPreview } from "../../../services/dashboardService";
import { scanProductsForAccount } from "../../../services/productsService";
import { getScanProgress } from "../../../services/ebayParserService";
import { useScan } from "../../../context/ScanContext";
import { AnimatePresence, motion } from "motion/react";

const SCAN_POLL_MS = 300;

export const ProductsSection = ({ onJumpToSection, activeAccountId }) => {
  const [statusFilter, setStatusFilter] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize] = useState(8);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [products, setProducts] = useState([]);
  const [total, setTotal] = useState(0);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [scanToast, setScanToast] = useState({ show: false, message: "", type: "success" });
  const pollRef = useRef(null);
  const { scanning, startScan, endScan, updateProgress } = useScan();

  // Lade Products wenn activeAccountId oder Filter sich ändern
  useEffect(() => {
    loadProducts();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeAccountId, page, pageSize, statusFilter, searchQuery]);

  const totalPages = Math.ceil(total / pageSize);
  const nextPage = () => {
    if (page < totalPages) setPage(page + 1);
  };
  const prevPage = () => {
    if (page > 1) setPage(page - 1);
  };

  const filters = [
    {
      id: "status",
      type: "select",
      value: statusFilter,
      options: [
        { value: "all", label: "Status: all" },
        { value: "active", label: "Active" },
        { value: "ended", label: "Ended" },
        { value: "unknown", label: "Unknown" },
      ],
    },
    {
      id: "search",
      type: "input",
      value: searchQuery,
      placeholder: "Search title",
    },
  ];

  const handleFilterChange = (id, value) => {
    if (id === "status") {
      setStatusFilter(value);
      setPage(1); // Reset to first page
    } else if (id === "search") {
      setSearchQuery(value);
      setPage(1); // Reset to first page
    }
  };

  const handleClearFilters = () => {
    setStatusFilter("all");
    setSearchQuery("");
    setPage(1);
  };

  const handleOpenProduct = async (productId) => {
    setPreviewLoading(true);
    setSelectedProduct(null);
    try {
      const preview = await getProductPreview(productId);
      setSelectedProduct(preview);
    } catch (e) {
      console.error("Fehler beim Laden des Product Previews:", e);
      setError(e.message || "Fehler beim Laden des Previews");
    } finally {
      setPreviewLoading(false);
    }
  };

  const loadProducts = async () => {
    if (!activeAccountId) {
      setProducts([]);
      setTotal(0);
      setLoading(false);
      setError(null);
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const data = await getProductsPage(activeAccountId, {
        page,
        pageSize,
        filters: {
          status: statusFilter !== "all" ? statusFilter : undefined,
          search: searchQuery.trim() || undefined,
        },
      });
      setProducts(data.items);
      setTotal(data.total);
    } catch (e) {
      console.error("Fehler beim Laden der Products:", e);
      setError(e.message || "Fehler beim Laden der Daten");
    } finally {
      setLoading(false);
    }
  };

  const handleScanProducts = async () => {
    if (!activeAccountId || scanning) {
      return;
    }

    setError(null);
    startScan();

    const stopPolling = () => {
      if (pollRef.current) {
        clearInterval(pollRef.current);
        pollRef.current = null;
      }
    };

    pollRef.current = setInterval(async () => {
      try {
        const p = await getScanProgress();
        if (p && (p.percent != null || p.phase || p.complete)) {
          updateProgress({
            percent: p.percent ?? 0,
            phase: p.phase ?? "idle",
            total: p.total ?? 0,
            current: p.current ?? 0,
            complete: !!p.complete,
          });
        }
      } catch {
        // ignore
      }
    }, SCAN_POLL_MS);

    try {
      const result = await scanProductsForAccount(activeAccountId);
      stopPolling();

      await loadProducts();

      const updated = result.updated ?? 0;
      setScanToast({
        show: true,
        message: `Scan abgeschlossen: ${result.created} neu, ${updated} aktualisiert`,
        type: "success",
      });
      setTimeout(() => {
        setScanToast({ show: false, message: "", type: "success" });
      }, 3000);
    } catch (e) {
      stopPolling();
      console.error("Fehler beim Scannen der Produkte:", e);

      const meta = e.meta || {};
      if (Object.keys(meta).length > 0) {
        console.log("[scan meta]", meta);
      }

      const errorMsg = e.message || "Fehler beim Scannen der Produkte";
      const isNoItems = errorMsg.includes("no_items_found") || errorMsg.includes("empty_items");
      const isParsingFailed = errorMsg.includes("Parsing failed");

      let toastMessage = errorMsg;
      if (isNoItems) {
        toastMessage = "0 Produkte gefunden. Bitte prüfe, ob die URL auf den Shop/Artikel-Bereich des Sellers zeigt.";
      } else if (isParsingFailed) {
        toastMessage = "Extension konnte keine Produkte finden. ";
        if (meta.pageType && meta.pageType !== "unknown") {
          toastMessage += `Seitentyp: ${meta.pageType}. `;
        }
        if (meta.reason) {
          toastMessage += `Grund: ${meta.reason}. `;
        }
        if (meta.finalUrl) {
          toastMessage += `URL: ${meta.finalUrl}`;
        }
        if (!meta.pageType && !meta.reason && !meta.finalUrl) {
          toastMessage += "Bitte stelle sicher, dass die Account-URL auf eine Seite mit Produkt-Listings zeigt (z.B. Storefront oder Seller-Listings).";
        }
      } else if (e.meta) {
        const m = e.meta;
        if (m.pageType && m.pageType !== "unknown") {
          toastMessage += ` (Seitentyp: ${m.pageType})`;
        }
        if (m.reason) {
          toastMessage += ` (${m.reason})`;
        }
      }

      setScanToast({
        show: true,
        message: toastMessage,
        type: "error",
      });
      setTimeout(() => {
        setScanToast({ show: false, message: "", type: "success" });
      }, 5000);
    } finally {
      if (pollRef.current) {
        clearInterval(pollRef.current);
        pollRef.current = null;
      }
      endScan();
    }
  };

  return (
    <section
      id="s3"
      className="flex min-h-screen w-auto flex-col gap-[18px] rounded-2xl px-4 py-4"
      style={{ scrollSnapAlign: "start", scrollSnapStop: "normal", color: "var(--text)" }}
    >
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-baseline gap-2.5">
          <h1 className="m-0 text-lg font-medium tracking-wide text-[var(--text)]">Products</h1>
          <span className="rounded-full border border-[var(--line)] bg-white/3 px-2.5 py-1.5 text-xs text-[var(--muted)]">
            explorer
          </span>
        </div>
        <div className="flex flex-wrap items-center justify-end gap-2.5">
          <button
            onClick={() => onJumpToSection("s1")}
            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
          >
            Overview
          </button>
          <button
            onClick={() => onJumpToSection("s2")}
            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
          >
            Accounts
          </button>
          <button
            onClick={() => onJumpToSection("s3")}
            className={cn(
              "rounded-xl border border-[rgba(106,166,255,0.7)] bg-[rgba(106,166,255,0.12)] px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
            )}
          >
            Products
          </button>
          <button
            onClick={() => onJumpToSection("s4")}
            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
          >
            Insights
          </button>
        </div>
      </div>

      <div className="flex items-end justify-between gap-4">
        <div>
          <h2 className="m-0 text-xl tracking-wide text-[var(--text)]">Products</h2>
          <p className="mt-1.5 mb-0 text-xs text-[var(--muted)]">
            Filter and page through products. No inner scrolling.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2.5">
          <Filters filters={filters} onChange={handleFilterChange} />
          <button
            onClick={handleClearFilters}
            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
          >
            Clear
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3.5 max-[1100px]:grid-cols-1">
        <div className="relative overflow-hidden rounded-[18px] border border-[var(--line)] bg-gradient-to-b from-white/4 to-white/2 p-4 shadow-[0_10px_30px_rgba(0,0,0,0.35)]">
          <div
            className="pointer-events-none absolute inset-[-1px] opacity-55"
            style={{
              background: "radial-gradient(600px 280px at 20% 0%, rgba(106,166,255,0.14), transparent 60%)",
            }}
          />
          <div className="relative">
            <div className="mb-4 px-0 pb-0 pt-0">
              <p className="mb-2 text-xs text-[var(--muted)]">Product list</p>
            </div>
            <div className="px-0 pb-4 pt-0">
              {loading ? (
                <div className="py-8 text-center text-xs text-[var(--muted)]">Loading...</div>
              ) : error ? (
                <div className="py-8 text-center text-xs text-red-400">{error}</div>
              ) : total === 0 && activeAccountId ? (
                <div className="flex flex-col items-center justify-center py-12 px-4">
                  <h3 className="mb-2 text-base font-semibold text-[var(--text)]">
                    Keine Produkte gefunden
                  </h3>
                  <p className="mb-6 text-center text-xs text-[var(--muted)]">
                    Scanne den Account, um Produkte zu importieren.
                  </p>
                  <button
                    onClick={handleScanProducts}
                    disabled={scanning}
                    className="rounded-xl border border-[rgba(106,166,255,0.7)] bg-[rgba(106,166,255,0.12)] px-6 py-3 text-sm font-medium text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px] disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    {scanning ? "Scanne..." : "Produkte scannen"}
                  </button>
                </div>
              ) : !activeAccountId ? (
                <div className="py-8 text-center text-xs text-[var(--muted)]">
                  No account selected
                </div>
              ) : (
                <>
                  <DataTable
                    columns={["Title", "Price", "Status", "Category", "Action"]}
                    data={products}
                    renderCell={(col, row) => {
                      if (col === "Action") {
                        return (
                          <button
                            onClick={() => handleOpenProduct(row.$id)}
                            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
                          >
                            Open
                          </button>
                        );
                      }
                      if (col === "Title") {
                        return row.product_title || row.$id;
                      }
                      if (col === "Price") {
                        return row.product_price ? `EUR ${row.product_price}` : "N/A";
                      }
                      if (col === "Status") {
                        return row.product_status || "unknown";
                      }
                      if (col === "Category") {
                        return row.product_category || "-";
                      }
                      return row[col.toLowerCase()] || "-";
                    }}
                  />
                  <Pagination
                    currentPage={page}
                    totalPages={totalPages}
                    onPrev={prevPage}
                    onNext={nextPage}
                    info={`Page ${page} / ${totalPages} - ${total} products`}
                  />
                </>
              )}
            </div>
          </div>
        </div>

        <div className="relative overflow-hidden rounded-[18px] border border-[var(--line)] bg-gradient-to-b from-white/4 to-white/2 p-4 shadow-[0_10px_30px_rgba(0,0,0,0.35)]">
          <div
            className="pointer-events-none absolute inset-[-1px] opacity-55"
            style={{
              background: "radial-gradient(600px 280px at 20% 0%, rgba(106,166,255,0.14), transparent 60%)",
            }}
          />
          <div className="relative">
            <p className="mb-2 text-xs text-[var(--muted)]">Product preview</p>
            {previewLoading ? (
              <div className="mb-4 text-xs text-[var(--muted)]">Loading preview...</div>
            ) : selectedProduct ? (
              <div className="mb-4 space-y-2 text-xs text-[var(--muted)]">
                <div>
                  <strong>Title:</strong> {selectedProduct.product_title || selectedProduct.$id}
                </div>
                {selectedProduct.product_price && (
                  <div>
                    <strong>Price:</strong> EUR {selectedProduct.product_price}
                  </div>
                )}
                {selectedProduct.product_status && (
                  <div>
                    <strong>Status:</strong> {selectedProduct.product_status}
                  </div>
                )}
                {selectedProduct.product_category && (
                  <div>
                    <strong>Category:</strong> {selectedProduct.product_category}
                  </div>
                )}
                {selectedProduct.details && (
                  <div className="mt-3 border-t border-[var(--line)] pt-2">
                    <strong>Details available</strong>
                  </div>
                )}
              </div>
            ) : (
              <div className="mb-4 text-xs text-[var(--muted)]">
                Click "Open" on a product to preview details.
              </div>
            )}
            <div className="flex items-center justify-between border-t border-[var(--line)] pt-3">
              <button
                disabled={!selectedProduct}
                className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2 text-xs text-[var(--text)] transition-all disabled:cursor-not-allowed disabled:opacity-45"
              >
                Compare similar
              </button>
              {selectedProduct && (
                <div className="text-xs text-[var(--muted)]">Preview loaded</div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Toast Notification */}
      <AnimatePresence>
        {scanToast.show && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className={cn(
              "fixed top-4 right-4 z-50 rounded-lg px-4 py-3 text-sm shadow-lg",
              scanToast.type === "success"
                ? "bg-green-50 text-green-700 dark:bg-green-900/20 dark:text-green-400"
                : "bg-red-50 text-red-700 dark:bg-red-900/20 dark:text-red-400"
            )}
          >
            {scanToast.message}
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  );
};
