import React, { useState, useEffect, useContext } from "react";
import styled from "styled-components";
import { SiteContext } from "@arcteryx/components-contexts";
import { Breakpoint, Body1Styles, Subtitle3 } from "@arcteryx/components-typography";
import { Button } from "@arcteryx/components-button";
import { IndexContext } from "../context/IndexContext";
import PropTypes from "prop-types";
import { adaptCMSSearchStaticLinks } from "../helpers/adaptCMSSearchStaticLinks";

const SearchStaticLinksWrapper = styled.div`
  max-width: 95.333rem;
  margin: 0 auto;
  padding: 1rem 0;
  h4 {
    margin: 0 0.5rem;
    color: var(--colour-copy);
  }
  width: 98%;
  ${Breakpoint("sm")`
    width: 94%;
  `}
  ${Breakpoint("lg")`
    width: 88%;
  `}
`;

const ButtonWrapper = styled.div`
  padding: 0.5rem 0 1.5rem;
  .button {
    border: 1px solid var(--pinline-grey) !important;
    padding: 0.5rem;
    height: 30px;
    font-size: 1rem;
    color: var(--colour-grey-dark);
    text-transform: none;
    font-weight: inherit;
    margin: 0.5rem;
  }
`;

const StyledSubtitle3 = styled(Subtitle3)`
  margin-left: 0.5rem;
`;

const FinderButton = styled(Button)`
  background-color: var(--white);
  display: inline-flex;
  align-items: center;
  padding: 0px 8px 2px;
  gap: 12px;
  border: 1px solid var(--inactive-state-grey);
  cursor: pointer;

  span {
    ${Body1Styles}
  }
`;

const SectionWrapper = styled.div``;

export const SearchStaticLinks = ({ cmsStaticSearchLinks }) => {
  const { market, country, language } = useContext(SiteContext);
  const [sections, setSections] = useState(null);
  const { suggestedSearch } = useContext(IndexContext);

  const handleClick = (link) => {
    if (link.url.startsWith("?search")) {
      const searchParams = new URLSearchParams(link.url);
      const query =
        searchParams
          .get("search")
          ?.split("-")
          .map((e) => e.charAt(0).toUpperCase() + e.slice(1))
          .join(" ") || link.label;
      const { setIsOpen, setQuery, refresh, setContext } = suggestedSearch;
      setIsOpen(false);
      setQuery(query);
      setContext({
        staticTerm: query,
      });
      refresh();
    } else {
      const url = new URL(link.url);
      window.location.href = `${url.origin}/${country}/${language}${url.pathname}/${url.search}`;
    }
  };

  if (market === "leaf") {
    return null;
  }

  useEffect(() => {
    const adaptedData = adaptCMSSearchStaticLinks(cmsStaticSearchLinks);
    setSections(adaptedData);
  }, [cmsStaticSearchLinks]);

  return (
    <SearchStaticLinksWrapper>
      {sections?.length
        ? sections?.map(({ header, links }, index) => (
            <SectionWrapper key={index}>
              <StyledSubtitle3>{header}</StyledSubtitle3>
              <ButtonWrapper>
              {links?.length &&
                  links?.map((link, i) => (
                    <FinderButton context="Secondary-cta" onClick={() => handleClick(link)} key={i}>
                      {link.label}
                    </FinderButton>
                  ))}
              </ButtonWrapper>
            </SectionWrapper>
          ))
        : ""}
    </SearchStaticLinksWrapper>
  );
};

SearchStaticLinks.propTypes = {
  cmsStaticSearchLinks: PropTypes.array,
};
