import React, { useEffect, useState, useRef } from "react";
import "./HomePage.styles.scss";
import { ReactComponent as LaunchIcon } from "../../assets/landingPageAssets/launch.svg";
import BookDemoIcon from "../../assets/landingPageAssets/book-demo.svg";
import ConfigurationIcon from "../../assets/landingPageAssets/configuration_icon.svg";
import {
  CAROUSEL_IMAGES,
  CAROUSEL_IMAGES_TEXT,
  AGENTIC_USECASES,
  findClient,
} from "./constant";
import { Button } from "../Button";
import { Panel } from "../Panel";

export const HomePage = ({
  clientName = "",
  userName = "",
  toolKitItems = [],
  smartAiItems = [],
  configurationsMenuItems = [],
  activeToolKitItem: currentActiveToolKitItem = null,
  activeSmartAiItem: currentActiveSmartAiItem = null,
  onLaunchClick = () => {},
  onBookDemoClick = () => {},
  onViewReleasedNotesClick = () => {},
  onConfigurationsClick = () => {},
  onKnowMoreClick = () => {},
  showConfigurationsButton = true,
}) => {
  const [activeToolKitItem, setActiveToolKitItem] = useState(
    currentActiveToolKitItem
  );
  const [activeSmartAiItem, setActiveSmartAiItem] = useState(
    currentActiveSmartAiItem
  );
  const [activeSmartAiItemIndex, setActiveSmartAiItemIndex] = useState(null);
  const [activeToolKitItemIndex, setActiveToolKitItemIndex] = useState(null);
  const [isConfigurationsMenuOpen, setIsConfigurationsMenuOpen] =
    useState(false);
  const [activeCarouselImage, setActiveCarouselImage] = useState(0);
  const [isAgenticUsecasesOpen, setIsAgenticUsecasesOpen] = useState(false);
  const [hoverAgenticUsecases, setHoverAgenticUsecases] = useState(null);
  const [width, setWidth] = useState(0);
  const intervalRef = useRef(null);
  const smartAiToolKitContentRef = useRef(null);
  const [activeClientLogo, setActiveClientLogo] = useState(null);

  const handleToolKitItemClick = (item, index) => {
    setActiveToolKitItem((prev) => (prev === item ? null : item));
    const groupStartIndex = Math.floor(index / 3) * 3;
    setActiveToolKitItemIndex(groupStartIndex);
  };
  const handleSmartAiItemClick = (item, index) => {
    setActiveSmartAiItem((prev) => (prev === item ? null : item));
    const groupStartIndex = Math.floor(index / 3) * 3;
    setActiveSmartAiItemIndex(groupStartIndex);
  };

  const handleClickOutside = (e) => {
    if (
      isConfigurationsMenuOpen &&
      !e.target.closest(".configurations_menu_container") &&
      !e.target.closest(".floating_btn_container")
    ) {
      setIsConfigurationsMenuOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", (e) => {
      handleClickOutside(e);
    });
    return () => {
      document.removeEventListener("mousedown", (e) => {
        handleClickOutside(e);
      });
    };
  }, [isConfigurationsMenuOpen]);

  const startCarouselInterval = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    intervalRef.current = setInterval(() => {
      setActiveCarouselImage((prev) => (prev + 1) % CAROUSEL_IMAGES.length);
    }, 1000);
  };

  useEffect(() => {
    startCarouselInterval();
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  const handleCarouselImageClick = (index) => {
    setActiveCarouselImage(index);
    startCarouselInterval();
  };

  useEffect(() => {
    if (!smartAiToolKitContentRef.current) return;

    const observer = new ResizeObserver(([entry]) => {
      setWidth(entry.contentRect.width);
    });

    observer.observe(smartAiToolKitContentRef.current);

    return () => {
      observer.disconnect();
    };
  }, []);

  useEffect(() => {
    if (clientName) {
      setActiveClientLogo(findClient(clientName));
    }
  }, [clientName]);

  return (
    <div className="main_landingpage_container">
      {/* left panel starts here */}

      <div className="left_panel">
        {/* left panel header starts here */}

        <div className="left_panel_header">
          {/* left section header starts here */}

          <div className="left_section_header">
            <div className="left_section_IA_logo_container"></div>
            <div className="right_content_container">
              <div className="right_content_title">
                <span className="non_gradient_text">
                  Welcome {userName}👋, Here’s your toolkit powered by{" "}
                </span>
                <span className="gradient_text">Agentic AI</span>
              </div>
              <div className="right_content_description">
                Access your tools and explore new solutions to level up.
              </div>
            </div>
          </div>

          {/* left section header ends here */}

          <div className="center_graidient_container"></div>
          <div className="center_image_container"></div>
          <div className="bottom_image_container"></div>

          {/* right section header starts here */}

          {/* <div className="right_section_header">
            <div className="right_section_ai_icon icon1"></div>
            <div className="right_section_ai_icon icon2"></div>
            <div className="right_section_ai_icon icon3"></div>
            <div className="right_section_ai_icon icon4"></div>
            <div className="right_section_ai_icon icon5"></div>
            <div className="right_section_ai_icon icon6"></div>
          </div> */}

          {/* right section header ends here */}
        </div>

        {/* left panel header ends here */}

        {/* Tool kit starts here*/}

        <div className="left_panel_product_container">
          <div className="tool_kit_container">
            <div className="toolkit_header_container">
              <div className="common_header toolkit_header_icon">
                Your tool kit 🧰
              </div>
              {showConfigurationsButton && (
                <Button
                  variant="tertiary"
                  onClick={() =>
                    setIsConfigurationsMenuOpen(!isConfigurationsMenuOpen)
                  }
                  icon={<img src={ConfigurationIcon} alt="configuration" />}
                  className="floating_btn_container"
                >
                  Configurations
                </Button>
              )}
              {isConfigurationsMenuOpen &&
                configurationsMenuItems.length > 0 && (
                  <div className="configurations_menu_container">
                    {configurationsMenuItems.map((item, index) => (
                      <div
                        key={`configurations-menu-item-${index}`}
                        className="configurations_menu_item"
                        onClick={() => onConfigurationsClick(item)}
                      >
                        <img
                          src={item.logo}
                          alt="configuration"
                          className="configurations_menu_item_logo"
                        />
                        <div className="configurations_menu_item_content">
                          <span className="configurations_menu_item_content_label">
                            {item.label}
                          </span>
                          <span className="configurations_menu_item_content_desc">
                            {item.desc}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
            </div>

            <div className={`tool_kit_content`}>
              {toolKitItems.map((item, index) => (
                <div
                  key={`tool-kit-item-container-${index}`}
                  className="tool_kit_item_container"
                  style={{ position: "relative", width: "32%" }}
                >
                  <div
                    key={index}
                    className={`tool_kit_item ${
                      activeToolKitItem === item ? "tool_kit_item_active" : ""
                    }`}
                    onClick={() => handleToolKitItemClick(item, index)}
                  >
                    {/* <div className="top_patch"></div> */}
                    <div
                      className={`tool_kit_item_icon ${item.name.replace(
                        /\s+/g,
                        ""
                      )}_icon`}
                    >
                      {item.name}
                    </div>
                    <div className="tool_kit_item_content">
                      {item.description}
                    </div>
                    <div className="url_container">
                      <Button variant="url" onClick={() => {}} className="url">
                        View more
                      </Button>
                    </div>
                    <div className="top_cta_container">
                      <div className="left_curve_container"></div>
                      <div className="right_curve_container"></div>

                      <Button
                        icon={<LaunchIcon />}
                        variant="primary"
                        onClick={() => {
                          onLaunchClick(item);
                        }}
                        className="primary_btn_home_page"
                      >
                        {item.cta || "Launch"}
                      </Button>
                    </div>
                    <div className="arrow_chevron_container">
                      <div className="arrow_chevron"></div>
                    </div>
                    {(item?.isNewProduct || item?.releaseStatus) && (
                      <div className={`bottom_ribbon_container ${item?.releaseStatus ? "release-status-ribbon" : ""}`}>
                        <span>{item?.releaseStatus || "New"}</span>
                      </div>
                    )}
                  </div>
                  {activeToolKitItemIndex === index && (
                    <div
                      className={`know_more_container ms_km_container ${
                        activeToolKitItem === null
                          ? "ms_km_container_hidden"
                          : ""
                      } tool_kit_know_more_container`}
                      style={{
                        width: `${width}px`,
                      }}
                    >
                      <div
                        className="close_icon"
                        onClick={() => setActiveToolKitItem(null)}
                      ></div>
                      <div className="km_heading_container">
                        <div
                          className={`know_more_container_heading ${activeToolKitItem?.name}_icon`}
                        >
                          {activeToolKitItem?.name}
                        </div>
                        <div className="tick_mark_enabled">Access Enabled</div>
                      </div>

                      <p className="km_description">
                        {activeToolKitItem?.details}
                      </p>

                      <div className="km_folder_container">
                        {activeToolKitItem?.folderContent?.map(
                          (item, index) => (
                            <div className="km_folder_item" key={`km-folder-item-${index}`}>
                              <div className="km_bulb_icon"></div>
                              <div className="km_folder_content">{item}</div>
                            </div>
                          )
                        )}
                      </div>

                      <div className="launch_button_container">
                        <Button
                          variant="secondary"
                          onClick={() => {
                            onLaunchClick(activeToolKitItem);
                          }}
                          icon={<LaunchIcon />}
                        >
                          {activeToolKitItem?.cta || "Launch"}
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>

            {/* <div
              className={`know_more_container ms_km_container ${
                activeToolKitItem === null ? "ms_km_container_hidden" : ""
              } tool_kit_know_more_container`}
            >
              <div
                className="close_icon"
                onClick={() => setActiveToolKitItem(null)}
              ></div>
              <div className="km_heading_container">
                <div
                  className={`know_more_container_heading ${activeToolKitItem?.name}_icon`}
                >
                  {activeToolKitItem?.name}
                </div>
                <div className="tick_mark_enabled">Access Enabled</div>
              </div>

              <p className="km_description">{activeToolKitItem?.details}</p>

              <div className="km_folder_container">
                {activeToolKitItem?.folderContent?.map((item, index) => (
                  <div className="km_folder_item" key={index}>
                    <div className="km_bulb_icon"></div>
                    <div className="km_folder_content">{item}</div>
                  </div>
                ))}
              </div>

              <div className="launch_button_container">
                <Button
                  variant="secondary"
                  onClick={() => {
                    onLaunchClick(activeToolKitItem);
                  }}
                  icon={<LaunchIcon />}
                >
                  {activeToolKitItem?.cta || "Launch"}
                </Button>
              </div>
            </div> */}
          </div>

          {/* Smart AI solution begins here*/}

          <div className="tool_kit_container smart_ai_tool_container">
            <div className="common_header toolkit_header_icon">
              Explore our smart Ai driven solutions 💡
            </div>

            <div className="tool_kit_content" ref={smartAiToolKitContentRef}>
              {smartAiItems.map((item, index) => (
                <div className="tool_kit_item_container" key={`smart-ai-item-container-${index}`}>
                  {/* <div className="top_patch"></div> */}
                  <div
                    key={index}
                    className={`tool_kit_item ${
                      activeSmartAiItem === item ? "tool_kit_item_active" : ""
                    }`}
                    onClick={() => handleSmartAiItemClick(item, index)}
                  >
                    <div
                      className={`tool_kit_item_icon ${item.name.replace(
                        /\s+/g,
                        ""
                      )}_icon`}
                    >
                      {item.name}
                    </div>
                    <div className="tool_kit_item_content">
                      {item.description}
                    </div>
                    <div className="url_container">
                      <Button variant="url" onClick={() => {}} className="url">
                        View more
                      </Button>
                    </div>
                    <div className="top_cta_container">
                      <div className="left_curve_container"></div>
                      <div className="right_curve_container"></div>
                      <Button
                        // icon={<BookDemoIcon />}
                        variant="tertiary"
                        onClick={() => {
                          onBookDemoClick(item);
                        }}
                      >
                        {item.cta || "Book demo"}
                      </Button>
                    </div>
                    <div className="arrow_chevron_container">
                      <div className="arrow_chevron"></div>
                    </div>
                    {(item?.isNewProduct || item?.releaseStatus) && (
                      <div className={`bottom_ribbon_container ${item?.releaseStatus ? "release-status-ribbon" : ""}`}>
                        <span>{item?.releaseStatus || "New"}</span>
                      </div>
                    )}
                  </div>
                  {activeSmartAiItemIndex === index && (
                    <div
                      className={`know_more_container ms_km_container ${
                        activeSmartAiItem === null
                          ? "ms_km_container_hidden"
                          : ""
                      }`}
                      style={{
                        width: `${width}px`,
                      }}
                    >
                      <div
                        className="close_icon"
                        onClick={() => setActiveSmartAiItem(null)}
                      ></div>
                      <div className="km_heading_container">
                        <div
                          className={`know_more_container_heading ${activeSmartAiItem?.name}_icon`}
                        >
                          {activeSmartAiItem?.name}
                        </div>
                      </div>

                      <p className="km_description">
                        {activeSmartAiItem?.details}
                      </p>

                      <div className="km_folder_container">
                        {activeSmartAiItem?.folderContent?.map(
                          (item, index) => (
                            <div className="km_folder_item" key={`km-folder-item-${index}`}>
                              <div className="km_bulb_icon"></div>
                              <div className="km_folder_content">{item}</div>
                            </div>
                          )
                        )}
                      </div>

                      <div className="launch_button_container">
                        <Button
                          variant="url"
                          onClick={() => {
                            onKnowMoreClick(activeSmartAiItem);
                          }}
                          className="url"
                        >
                          {activeSmartAiItem?.cta || "Know more"}
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Smart AI solution ends here*/}
        </div>
      </div>

      {/* left panel ends here */}

      {/* right panel starts here */}

      <div className="right_panel">
        {activeClientLogo?.image && (
          <div className="client_logo_container">
            <img
              src={activeClientLogo.image}
              alt={activeClientLogo?.name || "client-logo"}
              className="impact_client_logo_image"
            />
          </div>
        )}
        <div className="right_panel_content">
          <div className="smart_pf_panel_container">
            <div className="top_text_container">
              <div className="gradient_text">IA Smart Platform</div>
            </div>
            <div className="bottom_cards_container">
              <div className="card_ia ">
                <div className="left_image_container multi_level_planning"></div>
                <div className="right_content_container_card">
                  <span className="ia_card_heading_txt">
                    Multi-Level Planning:{" "}
                  </span>
                  Generate Optimized plans across product hierarchies
                </div>
              </div>
              <div className="card_ia">
                <div className="left_image_container strategic_objective"></div>
                <div className="right_content_container_card">
                  <span className="ia_card_heading_txt">
                    Strategic Objectives:{" "}
                  </span>
                  Define and align goals across organizational levels
                </div>
              </div>
              <div className="card_ia">
                <div className="left_image_container ai_ml_powered"></div>
                <div className="right_content_container_card">
                  <span className="ia_card_heading_txt">AI/ML Powered: </span>
                  Advanced analytics and intelligent automation
                </div>
              </div>
            </div>

            {/* IA Smart Platform ends here */}
          </div>

          <div className="latest_updates_container">
            <div className="latest_updates_header">Latest Updates</div>
            <div className="latest_updates_content">
              New features and improvements are now available
            </div>
            <Button variant="url" onClick={onViewReleasedNotesClick}>
              View released notes
            </Button>
          </div>

          {/* Smart Agent studio Platform starts here*/}

          <div className="smart_agent_studio_container">
            <div className="smart_agent_pf_headiing">
              SmartAgent Studio Platform
            </div>

            <div className="carousel_main_container">
              <div className="video_container">
                {CAROUSEL_IMAGES.map((image, index) => (
                  <div
                    key={`carousel-slide-${index}`}
                    className={`carousel_slide ${
                      index === activeCarouselImage
                        ? "carousel_slide_active"
                        : ""
                    }`}
                  >
                    <img
                      src={image}
                      alt={`carousel-${index}`}
                      className="carousel_image"
                    />
                    <span className="video_text">
                      {CAROUSEL_IMAGES_TEXT[index]}
                    </span>
                  </div>
                ))}
              </div>

              <div className="carousel_dot_container">
                {CAROUSEL_IMAGES.map((item, index) => (
                  <div
                    className={`carousel_dot ${
                      index === activeCarouselImage ? "dot_active" : ""
                    }`}
                    key={`carousel-dot-${index}`}
                    onClick={() => handleCarouselImageClick(index)}
                  ></div>
                ))}
              </div>
            </div>

            <div className="agentic_usecases_container">
              <Button
                variant="tertiary"
                onClick={() => {
                  setIsAgenticUsecasesOpen(true);
                }}
                icon={<img src={BookDemoIcon} alt="book-demo" />}
              >
                Find Agentic Usecases
              </Button>
            </div>
            <Panel
              anchor="right"
              className="agentic_usecases_panel"
              onClose={() => {
                setIsAgenticUsecasesOpen(false);
              }}
              size="large"
              title="Agentic Usecases"
              open={isAgenticUsecasesOpen}
              setIsOpen={setIsAgenticUsecasesOpen}
            >
              <div className="agentic_usecases_panel_content">
                {AGENTIC_USECASES.map((item, index) => (
                  <div className="agentic_usecases_panel_content_item_container" key={`agentic-usecases-panel-content-item-container-${index}`}>
                    <Button
                      variant="tertiary"
                      onClick={() => {
                        onBookDemoClick(item);
                      }}
                      // icon={<BookDemoIcon />}
                      className="agentic_usecases_panel_content_item_button"
                    >
                      Book demo
                    </Button>
                    <div
                      className="agentic_usecases_panel_content_item"
                      key={index}
                      style={{
                        backgroundColor: item.background,
                        borderColor:
                          hoverAgenticUsecases === item
                            ? item.borderColor
                            : "transparent",
                        backgroundImage: `url(${item.backgroundImage}), url(${item.backgroundImage}), url(${item.backgroundImage})`,
                        backgroundRepeat: "no-repeat",
                        backgroundSize: "44px",
                        backgroundPosition:
                          "right 35px top 15px, top -28px right 4px, top 29px right -14px",
                      }}
                      onMouseLeave={() => setHoverAgenticUsecases(null)}
                      onMouseEnter={() => setHoverAgenticUsecases(item)}
                    >
                      <img
                        src={item.image}
                        alt={item.name}
                        className="agentic_usecases_panel_content_item_image"
                      />
                      <div className="agentic_usecases_panel_content_item_content">
                        <span className="agentic_usecases_panel_content_item_name">
                          {item.name}
                        </span>
                        <span className="agentic_usecases_panel_content_item_description">
                          {item.description}
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Panel>
          </div>

          {/* Smart Agent studio Platform ends here*/}

          {/* Latest Updates starts here*/}
        </div>

        {/* Latest Updates ends here*/}
      </div>

      {/* right panel ends here */}
    </div>
  );
};
