"use client";

import React, { useState, useEffect, useCallback } from "react";
import {
  ArrowRightCircle,
  Link,
  Copy,
  X,
  ExternalLink,
  Check,
} from "react-feather";
// import { useRouter } from "next/navigation";
import Image from "next/image";
import apiClient from "@/lib/apiClient";
import "../../../styles/deep-link-style.css";
import { logger } from "@/lib/logger";


interface StorefrontUrl {
  platform_id: number;
  platform_name: string; // API returns lowercase: "amazon", "target", "walmart"
  platform_logo: string;
  store_front_url: string;
  logo: string;
  website: string;
}

interface StorefrontResponse {
  success: boolean;
  data: {
    partner_id: number;
    store_front_urls: StorefrontUrl[];
    total_count: number;
    showAddUrlPopup?: boolean;
    message?: string;
  };
}

export default function DeepLinksPage() {
  // const router = useRouter();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isNonCommissionableModalOpen, setIsNonCommissionableModalOpen] =
    useState(false);
  const [isNonCommissionableModalVisible, setIsNonCommissionableModalVisible] =
    useState(false);
  const [isSidePanelOpen, setIsSidePanelOpen] = useState(false);
  const [isSidePanelVisible, setIsSidePanelVisible] = useState(false);
  /* eslint-disable @typescript-eslint/no-unused-vars */
  // const [isAddUrlPopupOpen, setIsAddUrlPopupOpen] = useState(false);
  // const [isAddUrlPopupVisible, setIsAddUrlPopupVisible] = useState(false);
  const [selectedPlatform, setSelectedPlatform] =
    useState<StorefrontUrl | null>(null);
  // const [storefrontUrl, setStorefrontUrl] = useState("");
  const [deepLinkUrl, setDeepLinkUrl] = useState("");
  const [short_url, setShort_url] = useState("");
  const [copied, setCopied] = useState(false);
  const [searchInputValue, setSearchInputValue] = useState("");
  const [isGenerating, setIsGenerating] = useState(false);
  const [storefrontUrls, setStorefrontUrls] = useState<StorefrontUrl[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState<string>("");
  const searchInputRef = React.useRef<HTMLInputElement | null>(null);
  const [fallbackUrl, setFallbackUrl] = useState("");

  const fetchStorefrontUrls = useCallback(async () => {
    try {
      setIsLoading(true);

      const response = await apiClient.get("/brands/store-front-urls");
      const data: StorefrontResponse = response.data;
      if (data.success) {
        setStorefrontUrls(data.data.store_front_urls || []);
        // Check if we should show the add URL popup
        // if (
        //   data.data.showAddUrlPopup ||
        //   data.data.store_front_urls.length === 0
        // )
      } else {
        logger.error("Failed to fetch storefront URLs:", data?.data?.message || "Unknown error");
        // Show popup if API fails
        // showAddUrlPopup();
      }
    } catch (error: unknown) {
      logger.error("Failed to fetch storefront URLs:", error);

      // Extract error message from API response if available
      let errorMessage = "Failed to fetch storefront URLs";

      if (
        error &&
        typeof error === "object" &&
        "response" in error &&
        error.response &&
        typeof error.response === "object" &&
        "data" in error.response &&
        error.response.data &&
        typeof error.response.data === "object"
      ) {
        if ("message" in error.response.data && error.response.data.message) {
          // API returned an error message
          errorMessage = error.response.data.message as string;
        } else if (
          "error" in error.response.data &&
          error.response.data.error
        ) {
          // API returned an error field
          errorMessage = error.response.data.error as string;
        }
      } else if (error instanceof Error) {
        // Standard error message
        errorMessage = error.message;
      }

      // Show popup if API fails
      // showAddUrlPopup();
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Fetch storefront URLs on page load
  useEffect(() => {
    fetchStorefrontUrls();
  }, [fetchStorefrontUrls]);



  const isValidUrl = (value: string) => {
    try {
      new URL(value);
      return true;
    } catch {
      return false;
    }
  };

  const handleSearchClick = async () => {
    const productUrl = searchInputValue.trim();
    const fallback = fallbackUrl.trim();

    if (productUrl === fallback) {
      setErrorMessage("Fallback URL cannot be the same as the source URL.");
      return;
    }

    // Required check
    if (!productUrl || !fallback) {
      setErrorMessage("Both product URL and fallback URL are required");
      return;
    }

    // URL validation
    if (!isValidUrl(productUrl)) {
      setErrorMessage("Please enter a valid product URL");
      return;
    }

    if (!isValidUrl(fallback)) {
      setErrorMessage("Please enter a valid fallback URL");
      return;
    }

    setIsGenerating(true);
    setErrorMessage("");

    try {
      const response = await apiClient.post(
        "/product/save-affiliate-links",
        {
          url: searchInputValue.trim(),
          fallback_url: fallbackUrl.trim(), // ✅ passed to API
        }
      );

      const data = response.data;
      const isCommissionable = data.data?.isCommissionable;

      if (!data.success) {
        throw new Error("API request failed");
      }

      setErrorMessage("");
      setSearchInputValue("");
      setFallbackUrl("");

      if (isCommissionable) {
        const deeplinkUrl =
          data.data?.product?.deeplinkUrl || data.data?.deeplinkUrl;
        const short_url =
          data.data?.product?.short_url || data.data?.short_url;

        if (!deeplinkUrl) {
          throw new Error("No deep link URL found in response");
        }

        setShort_url(short_url || "");
        setDeepLinkUrl(deeplinkUrl);
        setIsModalOpen(true);
        setTimeout(() => setIsModalVisible(true), 10);
      } else {
        setIsNonCommissionableModalOpen(true);
        setTimeout(
          () => setIsNonCommissionableModalVisible(true),
          10
        );
      }
    } catch (error: unknown) {
      const message = "Something went wrong";
      setErrorMessage(message);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key !== "Enter") return;

    // Prevent form submit / page reload
    e.preventDefault();

    // Only submit if both inputs have values and not loading
    if (
      !isGenerating &&
      searchInputValue.trim() &&
      fallbackUrl.trim()
    ) {
      handleSearchClick();
    } else {
      setErrorMessage("Both Product URL and Fallback URL are required");
    }
  };


  const handleCloseModal = () => {
    setIsModalVisible(false);
    // Wait for animation to complete before hiding
    setTimeout(() => {
      setIsModalOpen(false);
      setCopied(false);
    }, 300);
  };

  const handleCloseNonCommissionableModal = () => {
    setIsNonCommissionableModalVisible(false);
    // Wait for animation to complete before hiding
    setTimeout(() => {
      setIsNonCommissionableModalOpen(false);
    }, 300);
  };

  const handlePlatformClick = async (platform: StorefrontUrl) => {
    if (!platform) return;

    if (platform && platform.store_front_url) {
      // URL exists, open sidebar
      setSelectedPlatform(platform);
      // setStorefrontUrl(platform.store_front_url);
      setIsSidePanelOpen(true);
      setTimeout(() => setIsSidePanelVisible(true), 10);
    }
  };

  const handleCloseSidePanel = () => {
    setIsSidePanelVisible(false);
    setTimeout(() => {
      setIsSidePanelOpen(false);
      setSelectedPlatform(null);
      // setStorefrontUrl("");
    }, 300);
  };

  const handleCopyLink = async () => {
    try {
      await navigator.clipboard.writeText(short_url || deepLinkUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      logger.error("Failed to copy link:", err);
    }
  };
  return (
    <div className="pcoded-main-container bg-light webContent deep-link-page">
      <div className="pcoded-content">
        {/* Header Section */}
        <div className="row align-items-center">
          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 text-md-start text-center mb-md-0 mb-2">
            <h3 className="subHeading">Deep Links</h3>
          </div>
        </div>

        {/* Storefront Section */}
        <section className="storefront-section my-links-page mt-3 mb-3">
          <div className="row justify-content-center">
            <div className="col-12 col-sm-12 col-md-12 col-lg-11 col-xl-10 col-xxl-10 mb-3">
              <div className="card p-0">
                <div className="card-body w-100 text-center p-3 p-md-4">
                  <h5 className="subHeading mb-0 mt-2">Smart Deep Links</h5>
                  <p className="mb-2">for 3X the conversion</p>
                  <p className="mt-2 mt-3">
                    Monetize your favorite brands with smart deep links
                  </p>
                  <div className="mt-3 mb-3">
                    {/* Product / Category URL */}
                    <div className="input-group search-input-group search-input-group2">
                      <input
                        type="text"
                        ref={searchInputRef}
                        className="form-control form-control-light"
                        placeholder="Paste product or category link"
                        value={searchInputValue}
                        onChange={(e) => {
                          setSearchInputValue(e.target.value);
                          if (errorMessage) setErrorMessage("");
                        }}
                        onKeyDown={handleKeyDown}
                        disabled={isGenerating}
                      />
                    </div>

                    {/* Fallback URL */}
                    <div className="mt-3 mb-2 fw-semibold text-start color-third">
                      Fallback URL (Required)
                    </div>
                    <p className="text-start mb-2">
                      Paste the link users should be redirected to once the click limit is
                      reached. When your link hits its cap, traffic will automatically redirect
                      here (e.g. your link-in-bio, main website, or storefront).
                    </p>

                    <div className="input-group search-input-group search-input-group2">
                      <input
                        type="text"
                        className="form-control form-control-light"
                        placeholder="Paste fallback URL"
                        value={fallbackUrl}
                        onChange={(e) => {
                          setFallbackUrl(e.target.value);
                          if (errorMessage) setErrorMessage("");
                        }}
                        onKeyDown={handleKeyDown}
                        disabled={isGenerating}
                      />
                    </div>
                    {/* Submit button */}
                    <div className="mt-3 text-center">
                      <button
                        className="button btn-first mx-auto px-5"
                        onClick={handleSearchClick}
                        disabled={
                          isGenerating ||
                          !searchInputValue.trim() ||
                          !fallbackUrl.trim()
                        }
                      >
                        {isGenerating ? "Submitting..." : "Submit"}
                      </button>
                    </div>

                    {/* Status / Error */}
                    <div className="mt-2">
                      {isGenerating && (
                        <div className="text-center">
                          <small className="text-muted">Generating deep link...</small>
                        </div>
                      )}
                      {errorMessage && (
                        <div className="text-center">
                          <small className="text-danger">{errorMessage}</small>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
              <div className="mt-3">
                {!isLoading && storefrontUrls.length > 0 && (
                  <>
                    <p className="mb-4 text-center fw-semibold w-100">
                      Or browse products from brand(s) below
                    </p>
                    <div className="affiliate-links-wrapper d-flex overflow-auto gap-2">
                      {storefrontUrls.map((platform, i) => (
                        <div
                          key={`${platform.platform_id}-${i}`}
                          className="affiliate-link links-cards card p-1 p-md-3 flex-shrink-0"
                          style={{ width: "100px", textAlign: "center" }}
                        >
                          <a
                            className="mb-0 affiliate-btn d-flex flex-column align-items-center"
                            onClick={() => handlePlatformClick(platform)}
                          >
                            <Image
                              src={platform.logo}
                              alt={platform.platform_name}
                              width={40}
                              height={40}
                              className="mb-1 object-contain"
                            />
                            <span
                              className="d-block text-break"
                              style={{
                                wordBreak: "break-word",
                                whiteSpace: "normal",
                              }}
                            >
                              {platform?.platform_name?.toUpperCase() || ""}
                            </span>
                          </a>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </section>


        {/* Side Panel for Platform Navigation */}
        {isSidePanelOpen && (
          <>
            {/* Side Panel Backdrop */}
            <div
              className={`side-panel-backdrop ${isSidePanelVisible ? "show" : ""
                }`}
              onClick={handleCloseSidePanel}
            />
            {/* Side Panel */}
            <div className={`side-panel ${isSidePanelVisible ? "show" : ""}`}>
              <div className="side-panel-header">
                <div className="d-flex align-items-center gap-2">
                  <Image
                    src={selectedPlatform?.logo || ""}
                    alt={selectedPlatform?.platform_name || ""}
                    width={24}
                    height={24}
                  />

                  <h5 className="mb-0">
                    {selectedPlatform?.platform_name?.toUpperCase() || ""}{" "}
                  </h5>
                </div>
                <button
                  type="button"
                  className="btn-close-side-panel"
                  onClick={handleCloseSidePanel}
                >
                  <X size={20} />
                </button>
              </div>

              <div className="side-panel-content">
                <div className="deep-link-workflow">
                  <h6 className="mb-3">Deep Link Process</h6>
                  <div className="workflow-steps">
                    <div className="step">
                      <div className="step-number">1</div>
                      <div className="step-content">
                        <strong>Browse Products</strong>
                        <small>Find products you want to promote</small>
                      </div>
                    </div>
                    <div className="step">
                      <div className="step-number">2</div>
                      <div className="step-content">
                        <strong>Copy URL</strong>
                        <small>Copy the product page URL</small>
                      </div>
                    </div>
                    <div className="step">
                      <div className="step-number">3</div>
                      <div className="step-content">
                        <strong>Paste & Generate</strong>
                        <small>Paste URL in search input box</small>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div className="side-panel-footer">
                <a
                  href={selectedPlatform?.store_front_url || ""}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="button btn-first btn-first-pink w-100 "
                >
                  <ExternalLink size={16} className="me-2" />
                  Start Browsing {selectedPlatform?.platform_name || ""}
                </a>
              </div>
            </div>
          </>
        )}

        {/* Link Modal */}
        {isModalOpen && (
          <>
            {/* Modal Backdrop */}
            <div
              className={`modal-backdrop fade ${isModalVisible ? "show" : ""}`}
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                width: "100vw",
                height: "100vh",
                backgroundColor: "rgba(0, 0, 0, 0.5)",
                zIndex: 1040,
                transition: "opacity 0.3s ease",
                cursor: "pointer",
              }}
              onClick={handleCloseModal}
            />

            {/* Modal */}
            <div
              className={`modal fade my-modal ${isModalVisible ? "show" : ""
                } d-block`}
              id="linkModal"
              style={{ zIndex: 1050 }}
              onClick={handleCloseModal}
            >
              <div
                className="modal-dialog modal-dialog-centered"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="modal-content">
                  <div className="modal-body text-center p-3">
                    <div className="modal-name mb-0 d-flex justify-content-end">
                      <button
                        type="button"
                        className="btn-close"
                        onClick={handleCloseModal}
                        aria-label="Close"
                      >
                        x
                      </button>
                    </div>
                    <Image
                      src="/img/icons/check.svg"
                      alt="check Image"
                      width={48}
                      height={48}
                      className="checkModal mb-3"
                    />
                    <h5 className="mb-3">
                      Deep link created and added to My Links
                    </h5>
                    {short_url || deepLinkUrl ? (
                      <a
                        className="input-links mb-3"
                        href={short_url || deepLinkUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        {short_url || deepLinkUrl}
                      </a>
                    ) : (
                      <div className="alert alert-warning mb-3">
                        Deep link generated successfully! URL will be displayed
                        here.
                      </div>
                    )}
                    <div className="card-btn-area justify-content-center mb-2 mt-3 ">
                      {deepLinkUrl && (
                        <a
                          href={short_url || deepLinkUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="btn btn-first btn-first-pink small-btn"
                        >
                          <Link size={16} className="me-2" /> Check link
                        </a>
                      )}
                      <button
                        onClick={handleCopyLink}
                        className="btn btn-first btn-first-pink small-btn code-copy-button mb-1 "
                        disabled={!deepLinkUrl}
                      >
                        {copied ? (
                          <>
                            <Check size={16} className="me-2" />
                            Copied!
                          </>
                        ) : (
                          <>
                            <Copy size={16} className="me-2" />
                            Copy Link
                          </>
                        )}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </>
        )}

        {/* Non-Commissionable Modal */}
        {isNonCommissionableModalOpen && (
          <>
            {/* Modal Backdrop */}
            <div
              className={`modal-backdrop fade ${isNonCommissionableModalVisible ? "show" : ""
                }`}
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                width: "100vw",
                height: "100vh",
                backgroundColor: "rgba(0, 0, 0, 0.5)",
                zIndex: 1040,
                transition: "opacity 0.3s ease",
                cursor: "pointer",
              }}
              onClick={handleCloseNonCommissionableModal}
            />

            {/* Modal */}
            <div
              className={`modal fade my-modal ${isNonCommissionableModalVisible ? "show" : ""
                } d-block`}
              id="nonCommissionableModal"
              style={{ zIndex: 1050 }}
              onClick={handleCloseNonCommissionableModal}
            >
              <div
                className="modal-dialog modal-dialog-centered"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="modal-content">
                  <div className="modal-body text-center p-3">
                    <div className="modal-name mb-0 d-flex justify-content-end">
                      <button
                        type="button"
                        className="btn-close"
                        onClick={handleCloseNonCommissionableModal}
                        aria-label="Close"
                      >
                        x
                      </button>
                    </div>
                    <div className="mb-3">
                      <div className="alert alert-warning mb-3">
                        <strong>Brand Not Commissionable</strong>
                      </div>
                    </div>
                    <h5 className="mb-3">
                      This brand isn’t part of our affiliate program at the moment.
                    </h5>
                    <p className="text-muted mb-4">
                      But good news — plenty of other brands are ready for you to monetize! Please try deep linking another brand.
                    </p>
                    <div className="card-btn-area justify-content-center mb-2 mt-3">
                      <button
                        onClick={handleCloseNonCommissionableModal}
                        className="btn btn-first btn-first-pink small-btn"
                      >
                        Try Another Brand
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
