import Layout from '@/components/layout';
import WorkList from '@/components/work-list';
import RightArrow from 'public/icons/right-arrow.svg';
import { useEffect, useState } from 'react';
import { GetServerSideProps } from 'next';
import { get } from '@/lib/fetch';
import useWindowSize from '@/hooks/useWindowSize';
import { NEXT_PUBLIC_API_URL, TABLET_SIZE, MOBILE_SIZE, NEXT_BASE_PATH } from '@/lib/constants';
import TitleDesktop01 from 'public/icons/home/desktop/title-01.svg';
import TitleDesktop02 from 'public/icons/home/desktop/title-02.svg';
import TitleDesktop03 from 'public/icons/home/desktop/title-03.svg';
import TitleMobile01 from 'public/icons/home/mobile/title-01.svg';
import TitleMobile02 from 'public/icons/home/mobile/title-02.svg';
import TitleMobile03 from 'public/icons/home/mobile/title-03.svg';
import TitleMobile04 from 'public/icons/home/mobile/title-04.svg';
import TitleMobile05 from 'public/icons/home/mobile/title-05.svg';

const getFullUrl = (basePath: string, url: string) => {
  if (basePath) {
    return basePath + url;
  }

  return url;
}

const onLoadMiniGallery = (transitionSpeed: number) => {
  const firstElement = document.querySelector('.work-section-gallery > div:first-child');
  firstElement.classList.add('active');
 
  window['galleryId'] = setInterval(() => {
    const current = document.querySelector('.work-section-gallery > .active');
    const nextElement = current.nextElementSibling;

    current.classList.remove('active');
    if (nextElement) {
      nextElement.classList.add('active');
    } else {
      firstElement.classList.add('active');
    }
  }, transitionSpeed*1000);
};

const onLoadDesktopElements = () => {
  const firstWork = document.querySelector('.work-section > div[data-index="0"]');
  const directionalArrow = document.querySelector('.directional-arrow');
  const texts = document.querySelectorAll('.main-title-desktop [data-transition]');
  const tabletTexts = document.querySelectorAll('.main-title-tablet [data-transition]');

  texts.forEach((text, index) => setTimeout(() => text.classList.add('play-transition'), (index+1)*150));
  tabletTexts.forEach((item, index) => setTimeout(() => item.classList.add('play-transition'), (index+1)*150));
  setTimeout(() => {
    directionalArrow.classList.add('show');
    if (!firstWork.classList.contains('fade-in') && firstWork.classList.toString() !== "") {
      firstWork.classList.add('initial-state');
    }
  }, (texts.length*150)+100);
};

const onLoadMobileElements = (width: number) => {
  let delay = 250;
  if (width < MOBILE_SIZE) delay = 420;

  const tabletTexts = document.querySelectorAll('.main-title-tablet [data-transition]');
  const mobileTexts = document.querySelectorAll('.main-title-mobile [data-transition]');
  const workCounter = document.querySelector('.work-counter');
  const workSection = document.querySelector('.work-section-mobile');
  const sliderArrow = document.querySelector('.slider-arrow');

  tabletTexts.forEach((item, index) => setTimeout(() => item.classList.add('play-transition'), (index+1)*150));
  mobileTexts.forEach((item, index) => setTimeout(() => item.classList.add('play-transition'), (index+1)*150));
  workCounter.querySelector('.current-text').textContent = '01/';
  setTimeout(() => {
    workCounter.classList.add('active-mobile');
    workSection.classList.add('active');
    sliderArrow.classList.add('active');
  }, (tabletTexts.length*150)+delay);
};

const onClickDirectionalArrow = () => {
  const texts = document.querySelectorAll('.main-title .main-title-desktop [data-transition]');
  const tabletTexts = document.querySelectorAll('.main-title-tablet [data-transition]');
  const workList = document.querySelector('.work-list');
  const workCounter = document.querySelector('.work-counter');
  const firstWork = document.querySelector('.work-section > .initial-state');
  const arrow = document.querySelector('.directional-arrow');
  const miniGalleryItems = document.querySelectorAll('.work-section-gallery > div');

  texts.forEach((text, index) => setTimeout(() => text.classList.remove('play-transition'), (index+1)*100));
  tabletTexts.forEach((text, index) => setTimeout(() => text.classList.remove('play-transition'), (index+1)*100));
  setTimeout(() => {
    firstWork?.classList.add('initial-state-change');
    arrow.classList.remove('show');
  
    workList.classList.add('active');
    workCounter.classList.add('active');

    miniGalleryItems.forEach(item => item.classList.remove('active'));
    miniGalleryItems[0].classList.add('active');
  }, (texts.length*100)+100);
  clearInterval(window['galleryId']);
};

const SliderArrow = () => {
  return (
    <div className="slider-arrow">
      scroll
      <div className="slider-arrow-icon">
        <RightArrow />
      </div>
    </div>
  );
};

const DirectionalArrow = () => {
  return (
    <div className="directional-arrow" onClick={onClickDirectionalArrow}>
      <span className="icon">
        <RightArrow />
      </span>
      <span className="text">
        work
      </span>
    </div>
  )
};

export default function Home({ home, works }) {
  // const projects = home.works.map(work => ({ id: work.id, title: work.title, imageUrl: `${NEXT_PUBLIC_API_URL}${work.banner.url}`}));
  const projects = works?.map(work => ({ id: work?.id, title: work?.title?.rendered, imageUrl: work?.better_featured_image?.source_url }));
  const [width] = useWindowSize();
  const [activatedAnimation, setActivatedAnimation] = useState(false);

  useEffect(() => {
    window.localStorage.setItem('projects', JSON.stringify(projects));
    const mainTitle = document.querySelector('.main-title');
    const firstWork = document.querySelector('.work-section > div[data-index="0"]');
    const arrow = document.querySelector('.directional-arrow');
    const headerWorkLink = document.querySelector('.header .header-menu a[data-slug="work"]');
    const logo = document.querySelector('.header .header-logo');
    const source = window.localStorage.getItem('source');
    const workList = document.querySelector('.work-list');
    const workCounter = document.querySelector('.work-counter');
    const projectsHtml = document.querySelectorAll('.work-section > div');
    const arrowUp = workCounter?.querySelector('.icon-up') as HTMLElement;
    const arrowDown = workCounter?.querySelector('.icon-down') as HTMLElement;
    const texts = document.querySelectorAll('.main-title [data-transition]');
    const tabletTexts = document.querySelectorAll('.main-title-tablet [data-transition]');

    logo.addEventListener('click', () => {
      projectsHtml.forEach(proj => proj.classList.remove('active', 'fade-in', 'fade-out', 'fade-in-opposite', 'fade-out-opposite'));
      firstWork?.classList.remove('initial-state-change');
      firstWork?.classList.add('initial-state');
      firstWork?.classList.add('active');
      arrow.classList.add('show');
      workList.classList.remove('active');
      workCounter.classList.remove('active');
      workCounter.querySelector('.current-text').textContent = '01/';
      arrowUp.style.display = 'none';
      if (projectsHtml.length > 1) arrowDown.style.display = 'block';
      texts.forEach((text, index) => setTimeout(() => text.classList.add('play-transition'), (index+1)*100));
      tabletTexts.forEach((text, index) => setTimeout(() => text.classList.add('play-transition'), (index+1)*100));
      onLoadMiniGallery(home?.acf?.home_base?.miniSliderTransitionSpeed);
    });

    headerWorkLink.addEventListener('click', () => (arrow as HTMLElement).click());

    if (projects?.length === 0) {
      setTimeout(() => {
        mainTitle.classList.add('show');
        window.localStorage.removeItem('source');
      }, 400);

      return;
    };

    if (!isNaN(parseInt(source, 10))) {
      const selectedProject = Array.from(projectsHtml).find(itemContainer => {
        return Array.from(itemContainer.children).find(item => (item as HTMLElement).dataset.id === source);
      });

      projectsHtml.forEach(group => group.classList.remove('active'));

      const currentNumber = parseInt((selectedProject as HTMLElement).dataset.index, 10);

      arrowUp.style.display = 'block';
      arrowDown.style.display = 'block';
      if ((currentNumber + 1) === projectsHtml.length) arrowDown.style.display = 'none';
      if (currentNumber === 0) arrowUp.style.display = 'none';

      workCounter.querySelector('.current-text').textContent = (currentNumber + 1) < 10 ? `0${currentNumber + 1}/` : `${currentNumber + 1}/`;

      workList.classList.add('active');
      workCounter.classList.add('active');
      selectedProject.classList.add('active', 'fade-in');
      window.localStorage.removeItem('source');

      return;
    }

    if (isNaN(Number(source))) {
      workList.classList.add('active');
      workCounter.classList.add('active');
      projectsHtml[0].classList.add('active', 'fade-in');
      window.localStorage.removeItem('source');

      return;
    }

    setTimeout(() => {
      onLoadMiniGallery(home?.acf?.home_base?.miniSliderTransitionSpeed);
    }, 500);

  }, []);

  useEffect(() => {
    setTimeout(() => {
      if (width > 0) {
        if (width <= TABLET_SIZE) {
          onLoadMobileElements(width);
        } else {
          onLoadDesktopElements();
          document.querySelector('body').classList.add('is-home');
        }
      }
    }, 300);

    return () => {
      document.querySelector('body').classList.remove('is-home');
      clearInterval(window['galleryId']);
    }
  }, [width]);

  const onWheelMainTitle = (event: React.WheelEvent<HTMLDivElement>) => {
    const { deltaY } = event;
    const workList = document.querySelector('.work-list');

    if(!workList) return;

    if (deltaY > 0 && !activatedAnimation) {
      onClickDirectionalArrow();
      setActivatedAnimation(true);
    }

    setTimeout(() => {
      setActivatedAnimation(false);
    }, 300);
  };

  return (
    <Layout seoGoogleTags={home?.acf?.seoGoogleTags} seoFacebookTags={home?.acf?.seoFacebookTags} seoTwitterTags={home?.acf?.seoTwitterTags}>
      <div className="container">
        {projects && projects?.length > 0 && <DirectionalArrow />}
        <section className="main-title" onWheel={(onWheelMainTitle)}>
          <div className="main-title-desktop">
            <div className="main-title-item"> 
              <span data-transition="down-to-up"><TitleDesktop01 /></span>
            </div>
            <div className="main-title-item">
              <span data-transition="down-to-up"><TitleDesktop02 /></span>
            </div>
            <div className="main-title-item">
              <span data-transition="down-to-up"><TitleDesktop03 /></span>
            </div>
          </div>
          <div className="main-title-tablet">
            <div className="main-title-item"> 
              <img data-transition="down-to-up" src={getFullUrl(NEXT_BASE_PATH, "/icons/home/tablet/title-01.svg")} alt=""/>
            </div>
            <div className="main-title-item">
              <img data-transition="down-to-up" src={getFullUrl(NEXT_BASE_PATH, "/icons/home/tablet/title-02.svg")} alt=""/>
            </div>
            <div className="main-title-item">
              <img data-transition="down-to-up" src={getFullUrl(NEXT_BASE_PATH, "/icons/home/tablet/title-03.svg")} alt=""/>
            </div>
          </div>
          <div className="main-title-mobile">
            <div className="main-title-item"> 
              <span data-transition="down-to-up"><TitleMobile01 /></span>
            </div>
            <div className="main-title-item">
              <span data-transition="down-to-up"><TitleMobile02 /></span>
            </div>
            <div className="main-title-item">
              <span data-transition="down-to-up"><TitleMobile03 /></span>
            </div>
            <div className="main-title-item">
              <span data-transition="down-to-up"><TitleMobile04 /></span>
            </div>
            <div className="main-title-item">
              <span data-transition="down-to-up"><TitleMobile05 /></span>
            </div>
          </div>
        </section>
        {projects && projects?.length > 0 && <WorkList projects={projects}/>}
        <SliderArrow />
      </div>
    </Layout>
  )
};

export const getServerSideProps: GetServerSideProps = async () => {
  // const response = await get(`home`);
  const response = await get(`wp/v2/pages/2`);
  const response_works = await get(`wp/v2/works`);

  if (!response && !response_works) {
    return { notFound: true }
  }

  const { data, error } = response;
  const { data: data_works, error: error_works } = response_works;

  if (data && data.length === 0 && data_works && data_works.length === 0) {
    return { notFound: true };
  }

  if (data && data_works) {
    return {
      props: { home: data, works: data_works }
    }
  }

  if (error && error_works) {
    return { notFound: true }
  }
}
