import Layout from "@/components/layout";
import MainTitleComponent from '@/components/main-title';
import MainDescriptionComponent from '@/components/main-description';
import { FC, useEffect, useRef, useState } from "react";
import useWindowSize from '@/hooks/useWindowSize';
import RightArrow from 'public/icons/right-arrow.svg';
import LeftArrow from 'public/icons/left-arrow.svg';
import Close from 'public/icons/close.svg';
import { get } from "@/lib/fetch";
import { GetServerSideProps } from "next";
import { COMPONENT_LIST } from '@/components/components';
import { NEXT_PUBLIC_API_URL } from "@/lib/constants";
import { useRouter } from "next/router";

interface NavigationArrow {
  onClickArrow: ((event: React.MouseEvent<HTMLElement>) => void);
}
 
const NavitationArrows: FC<NavigationArrow> = ({ onClickArrow }) => (
  <div className="navigation-arrow" data-show="true">
    <div className="navigation-arrow-item navigation-arrow-left" onClick={onClickArrow}>
      <span className="icon">
        <LeftArrow />
      </span>
    </div>
    <div className="navigation-arrow-item navigation-arrow-right" onClick={onClickArrow}>
      <span className="icon">
        <RightArrow />
      </span>
    </div>
  </div>
);

export default function Work({ work }) {
  const { 
    banner, title, description, productList, dynamicZone, seoGoogleTags, seoFacebookTags, seoTwitterTags
  } = work?.acf;

  const mainContent = useRef(null);
  const [width] = useWindowSize();
  const [offset, setOffset] = useState(0);
  const router = useRouter();

  const onClickArrow = (event: React.MouseEvent<HTMLDivElement>) => {
    const arrow = (event.target as HTMLElement).closest('.navigation-arrow-item');
    const projects = JSON.parse(window.localStorage.getItem('projects')) as Record<string, any>[];
    const id = parseInt(`${router.query.slug}`, 10);
    const indexCurrentProy = projects.findIndex(proy => proy.id === id);
    const workRoute = window.location.href.split('/').slice(0, window.location.href.split('/').length - 1).join('/');

    if (arrow.classList.contains('navigation-arrow-right')) {
      if (indexCurrentProy === (projects.length - 1)) return;
      window.location.href= `${workRoute}/${projects[indexCurrentProy + 1].id}`;
      return;
    }

    if (indexCurrentProy === 0) return;
    window.location.href = `${workRoute}/${projects[indexCurrentProy - 1].id}`;
    return;
  };

  useEffect(() => {
    const projects = JSON.parse(window.localStorage.getItem('projects')) as Record<string, any>[];
    const id = parseInt(`${router.query.slug}`, 10);
    const indexCurrentProy = projects.findIndex(proy => proy.id === id);

    const lefttArrow = document.querySelector('.navigation-arrow-left');
    const rightArrow = document.querySelector('.navigation-arrow-right');

    if (indexCurrentProy === 0) {
      lefttArrow.classList.add('hide');
    }
  
    if (indexCurrentProy === (projects.length - 1)) {
      rightArrow.classList.add('hide')
    }
  }, []);

  useEffect(() => {
    const mainContentWidth = parseInt(getComputedStyle(mainContent.current).width);
    const bannerElement = document.querySelector('.banner');
    const workTitle = document.querySelector('.work-title');
    const restElements = document.querySelectorAll('[data-show="true"]');
    setOffset((width - mainContentWidth)/2);
    bannerElement?.classList.add('show');
    workTitle?.classList.add('show');
    setTimeout(() => restElements.forEach(item => item.classList.add('show')), 120);
    
  }, [width]);

  return (
    <Layout seoGoogleTags={seoGoogleTags} seoFacebookTags={seoFacebookTags} seoTwitterTags={seoTwitterTags}>
      <div className="work-detail">
        <span className="work-close" onClick={() => {
          const { slug } = router.query;

          router.push('/');
          window.localStorage.setItem('source', `${slug}`);
        }}>
          <Close />
        </span>
        <section className="main-content" ref={mainContent}>
          {banner && <div className="columns banner">
            <div className="column is-offset-1-desktop is-10-desktop is-12-tablet">
              <img src={banner?.url} alt=""/>
            </div>
          </div>}
          <div className="columns work-title is-multiline">
            {title && <div className="column is-offset-0-desktop is-9-desktop is-offset-1-tablet is-9-tablet title">
              <MainTitleComponent {...title}/>
            </div>}
            {productList && productList.length > 0 && <div className="column is-offset-0-desktop is-2-desktop is-offset-1-tablet is-9-tablet product-list">
              <ul>
                {productList.map(item => (
                  <li key={item.id}>{item.name}</li>
                ))}
              </ul>
            </div>}
          </div>
          {description && <div className="main-description-container work-main-description-container" data-show="true">
            <MainDescriptionComponent
              content={description}
            />
          </div>}
        </section>
        {dynamicZone && dynamicZone.length > 0 && <div className="dynamic-zone" data-show="true">
          {dynamicZone.map((item: any, index: any) => {
            // const { __component, id, ...rest } = item;
            // const { __component, id, ...rest } = item;
            // const name = __component.split('.')[1];
            const name = item?.acf_fc_layout;
            const Component = COMPONENT_LIST[name];

            if (name === 'gallery') {
              return (
                item?.images && 
                  <div className="component-container" key={index}>
                    <Component
                      {...item}
                      images={item?.images?.map(galleryItem => `${galleryItem?.url}`)}
                      offset={offset}
                    />
                  </div>
              );
            }

            if (name === 'award-list') {
              return (
                item?.images &&
                  <div className="main-content component-container" key={index}>
                    <Component images={item?.images?.map(image => `${image?.url}`)} />
                  </div>
              );
            }

            return (
              <div className="main-content component-container" key={index}>
                <Component {...item} />
              </div>
            )
          })}
        </div>}
        <NavitationArrows onClickArrow={onClickArrow}/>
      </div>
    </Layout>
  );
};

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { params } = context;
  // const response = await get(`works/${params.slug}`);
  const response = await get(`wp/v2/works/${params.slug}`);

  if (!response) {
    return { notFound: true }
  }

  const { data, error } = response;

  if (data) {
    return {
      props: { work: data }
    }
  }

  if (error) {
    return { notFound: true }
  }
}