"use client";
import React, { useEffect, useState, useRef } from "react";
import { ArrowRight, Check, HelpCircle, Search, X } from "react-feather";
import apiClient from "@/lib/apiClient";
import TruncateWithCustomTooltip from "@/components/TruncateWithTooltip";
import { useConnectionStatus } from "@/hooks/useConnectionStatus";
import { useAppDispatch } from "@/hooks/useAppDispatch";
import { fetchConnectionStatus } from "@/features/autoDm/autoDmThunk";
import { logger } from "@/lib/logger";

type BrandStatus =
  | "Approved"
  | "Applied"
  | "Disapproved"
  | "Paused"
  | "Live"
  | string;

type Brand = {
  id: string;
  name: string;
  logo: string;
  status: BrandStatus;
  campaignType: string;
  kpi: string;
  deepLink: "Enabled" | "Disabled";
  commissionRate: string;
  campaignLive?: boolean;
};

const BrandsSection: React.FC = () => {
  const [brands, setBrands] = useState<Brand[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [scrollPosition, setScrollPosition] = useState(0);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [isApplying, setIsApplying] = useState(false);
  const [filters, setFilters] = useState<Record<string, boolean>>({
    All: true,
    Approved: false,
    Applied: false,
    Disapproved: false,
    Paused: false,
  });
  const [pagination, setPagination] = useState({
    currentPage: 1,
    totalPages: 1,
    totalItems: 0,
    startItem: 0,
    endItem: 0,
    hasNext: false,
    hasPrev: false,
  });

  const isLoadingRef = useRef(false);
  const dispatch = useAppDispatch();

  // Ensure connection status is fetched consistently across all pages
  useConnectionStatus();

  // Directly call details API whenever this page is rendered
  useEffect(() => {
    const hasValidToken =
      typeof window !== "undefined" && localStorage.getItem("access_token");

    if (hasValidToken) {
      dispatch(fetchConnectionStatus());
    }
  }, [dispatch]);

  const isValidImageUrl = (url: string): boolean => {
    return (
      typeof url === "string" &&
      url.length > 0 &&
      /\.(jpeg|jpg|gif|png|webp|svg)$/.test(url)
    );
  };

  // Define a type for the brand object
  interface BrandInfo {
    brandName?: string;
    logo?: string;
    advertiserUrl?: string;
  }
    const LOGO_API_BASE =
  process.env.NODE_ENV === "production"
    ? "https://api.theagency.com"
    : "https://devapi.theagency.com";
const getLogoUrl = (brand: BrandInfo = {} as BrandInfo): string => {
    // :one: Direct logo already available
    if (brand && brand.logo && brand.logo.trim()) {
      return brand.logo;
    }

    // :two: Use brandName → convert to domain
    if (brand && brand.brandName) {
      const cleanDomain =
        brand.brandName.toLowerCase().replace(/\s+/g, "") + ".com";
      return `${LOGO_API_BASE}/logo/${cleanDomain}`;
    }

    // :three: Fallback
    return "";
  };

  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [applyingBrands, setApplyingBrands] = useState<Set<string>>(new Set());

  const handleFilterChange = (status: string) => {
    let newFilters: Record<string, boolean> = { ...filters };

    if (status === "All") {
      // const newValue = !filters.All;
      newFilters = {
        All: true,
        Approved: false,
        Applied: false,
        Disapproved: false,
        Paused: false,
      };
    } else {
      newFilters[status] = !filters[status];
      newFilters.All = false;
    }
    const anySelected = Object.keys(newFilters).some(
      (key) => key !== "All" && newFilters[key]
    );
    if (!anySelected) {
      newFilters = {
        All: true,
        Approved: false,
        Applied: false,
        Disapproved: false,
        Paused: false,
      };
    }

    setFilters(newFilters);
  };

  const loadBrands = async (
    currentFilters: Record<string, boolean>,
    page = 1
  ) => {
    // Prevent duplicate calls
    if (isLoadingRef.current) {
      return;
    }

    isLoadingRef.current = true;
    setIsLoading(true);

    try {
      const selectedStatuses = Object.entries(currentFilters)
        .filter(([key, value]) => value && key !== "All")
        .map(([key]) => key);

      let statusesParam = "";

      if (currentFilters.All) {
        statusesParam = "Applied,Approved,Paused,Disapproved,Live";
      } else if (selectedStatuses.length > 0) {
        statusesParam = selectedStatuses.join(",");
      } else {
        statusesParam = "";
      }

      const response = await apiClient.get("/brands", {
        params: {
          statuses: statusesParam,
          page,
          limit: 12,
          search: searchTerm,
        },
      });

      const data = response?.data?.data;

      setBrands(data?.brands || []);

      if (data?.pagination) {
        const { page, limit, total_pages, has_next, has_prev } =
          data.pagination;
        const totalItems = data?.count ?? 0;

        const startItem = (page - 1) * limit + 1;
        const endItem = Math.min(page * limit, totalItems);

        setPagination({
          currentPage: page,
          totalPages: total_pages,
          totalItems,
          startItem,
          endItem,
          hasNext: has_next,
          hasPrev: has_prev,
        });
      }
    } catch (err) {
      logger.error("Failed to load brands:", err);
    } finally {
      isLoadingRef.current = false;
      setIsLoading(false);
    }
  };
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearch(searchTerm);
    }, 1000); // delay in ms

    return () => {
      clearTimeout(handler); // cleanup on change/unmount
    };
  }, [searchTerm]);
  useEffect(() => {
    loadBrands(filters, 1);
  }, [filters, debouncedSearch]);

  useEffect(() => {
    // Only run on client side
    if (typeof window === "undefined") return;

    const initializePopovers = async () => {
      try {
        const { Popover } = await import("bootstrap");
        const triggers = document.querySelectorAll(
          '[data-bs-toggle="popover"]'
        );
        triggers.forEach((el) => {
          const existing = Popover.getInstance(el);
          if (existing) existing.dispose();
          new Popover(el, { trigger: "hover", placement: "right" });
        });
      } catch (error) {
        logger.error("Failed to initialize popovers:", error);
      }
    };

    initializePopovers();
  }, []);

  const handleApply = async (offerId: string) => {
    // Prevent multiple clicks
    if (applyingBrands.has(offerId) || isApplying) return;

    try {
      // Add to loading set
      setIsApplying(true);
      setApplyingBrands((prev) => new Set(prev).add(offerId));
      setScrollPosition(window.scrollY);
      // const currentScroll = window.scrollY;
      await apiClient.post("/brands/apply", { offerId });
      await loadBrands(filters, pagination.currentPage);
      // window.scrollTo(0, currentScroll);
      setShowSuccessModal(true);
    } catch (err) {
      logger.error("Failed to apply brand:", err);
      alert("Something went wrong");
    } finally {
      // Remove from loading set
      setIsApplying(false);
      setApplyingBrands((prev) => {
        const newSet = new Set(prev);
        newSet.delete(offerId);
        return newSet;
      });
    }
  };
  // After brands reload, restore scroll
  useEffect(() => {
    if (scrollPosition > 0) {
      window.scrollTo(0, scrollPosition);
    }
  }, [brands]);

  const renderCTA = (brand: Brand) => {
    const isEligible =
      !["Applied", "Approved", "Paused", "Disapproved"].includes(
        brand.status
      ) &&
      (brand.campaignLive ?? true);
    const isApplying = applyingBrands.has(brand.id);

    if (isEligible) {
      return (
        <div className="d-flex gap-2 mt-3">
          <button
            type="button"
            className="w-100 btn-first btn-first-pink small-btn"
            onClick={() => handleApply(brand.id)}
            disabled={isApplying}
            style={
              isApplying
                ? { pointerEvents: "none", opacity: 0.6, cursor: "not-allowed" }
                : {}
            }
          >
            {isApplying ? (
              <>
                <div
                  className="spinner-border spinner-border-sm me-2"
                  role="status"
                  style={{ width: "1rem", height: "1rem" }}
                >
                  <span className="visually-hidden">Loading...</span>
                </div>
                Applying...
              </>
            ) : (
              <>
                Apply <ArrowRight />
              </>
            )}
          </button>
        </div>
      );
    }

    if (["Applied", "Paused"].includes(brand.status)) {
      return (
        <div className="d-flex gap-2 mt-3">
          <button
            type="button"
            className="w-100 btn btn-secondary small-btn"
            disabled
          >
            {brand.status}
          </button>
        </div>
      );
    }

    return null;
  };
  const formatCommissionRate = (rate: unknown): string => {
    if (rate === null || rate === undefined) return "--";

    const num = Number(rate);
    if (!isNaN(num)) return `${num.toFixed(2)}/click`;

    if (typeof rate === "string") {
      const val = rate.toLowerCase().trim();
      if (val === "n/a" || val === "na") return "--";
      return rate; // show other strings as-is
    }

    return String(rate); // fallback for non-string, non-number
  };

  const handlePageChange = (newPage: number) => {
    logger.log("Handling page change to:", newPage);
    if (newPage < 1 || newPage > pagination.totalPages) return;
    loadBrands(filters, newPage);
  };
  return (
    <>
      {isApplying && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100vw',
            height: '100vh',
            backgroundColor: 'rgba(0, 0, 0, 0)',
            zIndex: 9999,
            // cursor: 'not-allowed',
          }}
          onClick={(e) => e.preventDefault()}
        />
      )}
      <div
        className="pcoded-main-container bg-light webContent"
        style={isApplying ? { pointerEvents: 'none', userSelect: 'none' } : {}}
      >
        <div className="pcoded-content">
          <div className="row align-items-end mb-md-0 mb-2">
            <div className="col-md-6 mt-3 text-md-start text-center">
              <div>
                <h3 className="subHeading">Brands</h3>
                <a className="mb-3 mt-3 ml-2 d-block text-decoration-none">
                  Browse available brand campaigns. Rates shown here may change over time.
                  <button
                    type="button"
                    className="no-bg-btn"
                    data-bs-toggle="popover"
                    data-bs-placement="right"
                    data-bs-content="Don’t see a brand you want to promote? Your brand manager can help get it onboarded - just reach out!"
                  >
                    &nbsp; <HelpCircle />
                  </button>
                </a>
              </div>
            </div>

            {/* ✅ Filters */}
            <div className="col-md-6 mt-3">
              <div className="mb-3 radio-btn-area d-flex justify-content-center justify-content-md-end gap-2 flex-wrap">
                {Object.keys(filters).map((status) => (
                  <div key={status} className="d-flex align-items-center">
                    <input
                      type="checkbox"
                      className="btn-check"
                      id={`filter-${status}`}
                      checked={filters[status]}
                      onChange={() => handleFilterChange(status)}
                      disabled={isLoading}
                    />
                    <label
                      className={`btn btn-outline-primary d-flex align-items-center justify-content-center gap-2  ${isLoading ? "disabled" : ""
                        }`}
                      htmlFor={`filter-${status}`}
                      style={{
                        opacity: isLoading ? 0.6 : 1,
                        cursor: isLoading ? "not-allowed" : "pointer",
                      }}
                    >
                      {status}

                      {filters[status] && status !== "All" && !isLoading && (
                        <X
                          size={14}
                          style={{ cursor: "pointer" }}
                          onClick={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                            handleFilterChange(status);
                          }}
                        />
                      )}
                    </label>
                  </div>
                ))}
              </div>
            </div>
            <div className="col-12 col-md-4 mb-3 d-flex justify-content-center">
              <div className="search-section links-search d-flex gap-2 w-100 w-md-auto">
                <div className="search-input-group d-flex align-items-center">
                  <input
                    type="text"
                    className="form-control form-control-light"
                    placeholder="Search by brand name"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                  <button className="search-btn" type="button">
                    <Search />
                  </button>
                </div>
              </div>
            </div>
          </div>
          {/* ✅ Brands Grid */}
          <div className="row mt-3 g-4 ">
            {isLoading ? (
              <div className="col-12">
                <div className="text-center py-5">
                  <div
                    className="spinner-border mb-3"
                    role="status"
                    style={{ width: "3rem", height: "3rem", color: "#C600BA" }}
                  >
                    <span className="visually-hidden">Loading...</span>
                  </div>
                  <h5 className="text-muted">
                    Fetching available brand campaigns...
                  </h5>
                  <p className="text-muted">
                    Please wait while we load the latest brand opportunities.
                  </p>
                </div>
              </div>
            ) : (
              <>
                {brands?.map(
                  (
                    brand: any // eslint-disable-line @typescript-eslint/no-explicit-any
                  ) => (
                    <div
                      key={brand.id}
                      className="col-xxl-4 col-xl-4 col-lg-4 col-md-6 col-sm-12"
                    >
                      <div className="card rounded h-100">
                        <div className="card-body platform-card my-card brands-card mt-0 text-center d-flex flex-column">
                          <a
                            className="logos-image mb-3"
                            style={{ minHeight: "80px" }}
                          >
                            <img
                              src={getLogoUrl(brand)}
                              alt={brand.name}
                              width={200}
                              height={60}
                              style={{ objectFit: "contain" }}
                              loading="lazy"
                              onError={(e) => {
                                e.currentTarget.onerror = null; // Prevent infinite loop
                                const fallbackUrl = isValidImageUrl(
                                  brand?.advertiserUrl
                                )
                                  ? brand?.advertiserUrl
                                  : "";
                                e.currentTarget.src = fallbackUrl || "";
                              }}
                            />
                          </a>

                          <p className="mb-2 fw-semibold brands-name">
                            {brand?.name?.toUpperCase() || ""}
                          </p>

                          <p className="mb-2">
                            <Check
                              size={16}
                              className={`rounded-5 stroke-white status-icons ${["Applied", "Approved"].includes(brand.status)
                                  ? "bg-success"
                                  : "bg-warning"
                                }`}
                            />{" "}
                            {brand.status}
                          </p>

                          <p className="mb-2">
                            Campaign Type: <strong>{brand.campaignType}</strong>
                          </p>

                          {brand.status === "Approved" && (
                            <>
                              <p className="mb-1">
                                KPI:{" "}
                                <TruncateWithCustomTooltip
                                  text={brand.kpi}
                                  maxLength={25}
                                  className="fw-semibold text-black"
                                />
                              </p>
                              <p className="mb-1">
                                Commission Rate:{" "}
                                <strong>
                                  {formatCommissionRate(brand?.commissionRate)}
                                </strong>
                              </p>
                            </>
                          )}

                          {renderCTA(brand)}
                        </div>
                      </div>
                    </div>
                  )
                )}
                {brands.length === 0 && !isLoading && (
                  <div className="text-center text-muted">No brands found</div>
                )}
              </>
            )}
          </div>
          {!isLoading && brands?.length > 0 && (
            <div
              className="d-flex flex-wrap justify-content-center align-items-center gap-2 py-2  mb-3"
              style={{ rowGap: "0.5rem" }}
            >
              <div
                className="pagination-info text-muted small text-center"
                aria-live="polite"
              >
                Showing {pagination.startItem} to {pagination.endItem} of{" "}
                {pagination.totalItems} entries
              </div>
              <div className="d-flex align-items-center gap-1">
                <button
                  className="btn btn-outline-secondary btn-sm"
                  onClick={() => handlePageChange(pagination.currentPage - 1)}
                  disabled={pagination.currentPage === 1}
                >
                  &lt; Prev
                </button>
                {pagination.currentPage}
                <button
                  className="btn btn-outline-secondary btn-sm"
                  onClick={() => handlePageChange(pagination.currentPage + 1)}
                  disabled={pagination.currentPage === pagination.totalPages}
                >
                  Next &gt;
                </button>
              </div>
            </div>
          )}
        </div>

        {/* ✅ Success Modal */}
        {showSuccessModal && (
          <div
            className="modal fade show d-block"
            tabIndex={-1}
            style={{
              backgroundColor: "rgba(0,0,0,0.5)",
              zIndex: 1050, // keep modal above everything
            }}
            onClick={() => setShowSuccessModal(false)}
          >
            <div
              className="modal-dialog modal-dialog-centered"
              onClick={(e) => e.stopPropagation()}
            >
              <div
                className="modal-content rounded-3 shadow position-relative"
                style={{ pointerEvents: "auto", zIndex: 1100 }}
              >
                {/* ✅ Close button */}
                <button
                  type="button"
                  className="btn-close position-absolute top-0 end-0 m-3"
                  style={{ zIndex: 1200 }}
                  onClick={() => {
                    setShowSuccessModal(false);
                  }}
                ></button>

                <div className="modal-body text-center p-5">
                  {/* Circle with check */}
                  <div className="d-flex justify-content-center mb-4">
                    <div
                      className="rounded-circle d-flex align-items-center justify-content-center"
                      style={{
                        width: "70px",
                        height: "70px",
                        border: "2px solid #C600BA",
                      }}
                    >
                      <Check color="#C600BA" size={32} />
                    </div>
                  </div>

                  <p className="fw-semibold mb-1">
                    You&#39;ve successfully applied to this campaign.
                  </p>
                  <p className="fw-semibold">
                    Your brand manager will reach out to you!
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default BrandsSection;
