import { FC, useState } from "react";
import Link from 'next/link';
import RightArrow from 'public/icons/right-arrow.svg';
import UpArrow from 'public/icons/up-arrow.svg';
import DownArrow from 'public/icons/down-arrow.svg';
import { useRouter } from "next/router";
import useWindowSize from "@/hooks/useWindowSize";
import { SMALL_DESKTOP_SIZE } from "@/lib/constants";

interface Project {
  id: number;
  title: string;
  imageUrl: string;
}

interface WorkCounter {
  current: number;
  total: {mobile: number, desktop: number};
  onClickPage?: ((event: React.MouseEvent<HTMLElement>) => void);
}

interface WorkList {
  projects: Project[]
}

const WorkCounter: FC<WorkCounter> = ({ current, total, onClickPage }) => {
  return (
    <div className="work-counter">
      <h5>
        work
        <div className="arrow">
          <RightArrow />
        </div>
      </h5>
      <div className="project">
        <span className="current">
          <span className="current-text">{current < 10 ? `0${current}` : current}/</span>
          <span className="icon icon-up" onClick={onClickPage} style={{display: 'none'}}>
            <UpArrow />
          </span>
          {total.desktop > 1 && <span className="icon icon-down" onClick={onClickPage}>
            <DownArrow />
          </span>}
        </span>
        <span className="total mobile">{total.mobile < 10 ? `0${total.mobile}` : total.mobile}</span>
        <span className="total desktop">{total.desktop < 10 ? `0${total.desktop}` : total.desktop}</span>
      </div>
    </div>
  );
};

const WorkList: FC<WorkList> = ({ projects }) => {
  const [activatedAnimation, setActivatedAnimation] = useState(false);
  const [width] = useWindowSize();
  const groupedProjects = [];
  const router = useRouter();

  for (let i = 0; i < projects.length; i = i + 2) {
    const group = (i && i + 1) < projects?.length ? [projects[i+1], projects[i]] : [projects[i]];
    groupedProjects.push(group);
  }

  const onMouseEnter = (event: React.MouseEvent<HTMLDivElement>) => {
    if (width < SMALL_DESKTOP_SIZE) {
      return;
    }

    const item = (event.target as HTMLDivElement).closest('.work-section-item');
    const workCounter = document.querySelector('.work-counter');

    workCounter.classList.remove('active');
    if(item.classList.contains('item-one')) {
      const itemTwo = document.querySelector('.work-section > .active .work-section-item.item-two');
      if (itemTwo) {
        itemTwo.classList.add('blur', 'send-to-back');
      }
    } else {
      const itemOne = document.querySelector('.work-section > .active .work-section-item.item-one');
      if (itemOne) {
        itemOne.classList.add('blur', 'send-to-back');
      }
    }
  };

  const onMouseLeave = (event: React.MouseEvent<HTMLDivElement>) => {
    if (width < SMALL_DESKTOP_SIZE) {
      return;
    }

    const item = (event.target as HTMLDivElement).closest('.work-section-item');
    const workCounter = document.querySelector('.work-counter');

    if(item.classList.contains('item-one')) {
      const itemTwo = document.querySelector('.work-section > .active .work-section-item.item-two');
      if (itemTwo) {
        itemTwo.classList.remove('blur');
        setTimeout(() => itemTwo.classList.remove('send-to-back'), 260);
      }
    } else {
      const itemOne = document.querySelector('.work-section > .active .work-section-item.item-one');
      if (itemOne) {
        itemOne.classList.remove('blur');
        setTimeout(() => itemOne.classList.remove('send-to-back'), 260);
      }
    }
    workCounter.classList.add('active');
  };

  const onClickProy = (event: React.MouseEvent<HTMLDivElement>, id: Number) => {

    if (width < SMALL_DESKTOP_SIZE) {
      router.push(`/work/${id}`);
      return;
    }

    const currItem = (event.target as HTMLElement).closest('.work-section-item');
    const header = document.querySelector('.header');
    const footer = document.querySelector('.footer');

    if (currItem.classList.contains('item-one')) {
      const nextItem = document.querySelector('.work-section > .active > .work-section-item.item-two');
      if (nextItem) {
        nextItem.classList.add('change-view-opposite');
      }
    }

    if (currItem.classList.contains('item-two')) {
      const nextItem = document.querySelector('.work-section > .active > .work-section-item.item-one');
      if (nextItem) {
        nextItem.classList.add('change-view-opposite');
      }
    }

    currItem.classList.add('change-view');
    header.classList.remove('show');
    footer.classList.remove('show');

    setTimeout(() => {
      router.push(`/work/${id}`);
    }, 200);
  };

  const onWorkCounterClick = (event: React.MouseEvent<HTMLDivElement>) => {
    const arrow = event.target as HTMLElement;
    const arrowUp = document.querySelector('.work-counter .icon-up') as HTMLElement;
    const arrowDown = document.querySelector('.work-counter .icon-down') as HTMLElement;
    const activeElement = document.querySelector('.work-section > .active');
    const currentText = document.querySelector('.work-counter .current-text');
    let counter = parseInt((activeElement as HTMLElement).dataset.index, 10) + 1;

    activeElement.classList.remove('initial-state', 'initial-state-change');
    if (arrow.classList.contains('icon-down')) {
      const nextElement = activeElement.nextElementSibling;

      if (nextElement) {
        const indexElement = parseInt(nextElement.getAttribute('data-index'), 10);

        activeElement.classList.add('fade-out');
        activeElement.classList.remove('active');
        nextElement.classList.add('active');
        nextElement.classList.add('fade-in');
        counter = counter + 1;
        currentText.textContent = counter < 10 ? `0${counter}/` : `${counter}/`;
        arrowUp.style.display = 'block';
        if ((indexElement + 1) === groupedProjects?.length) arrowDown.style.display = 'none';
        setTimeout(() => {
          activeElement.classList.remove('fade-out', 'fade-in');
          activeElement.classList.remove('fade-in-opposite', 'fade-out-opposite');
        }, 260);
      }
    } else {
      const prevElement = activeElement.previousElementSibling;

      if (prevElement) {
        const indexElement = parseInt(prevElement.getAttribute('data-index'), 10);

        activeElement.classList.add('fade-out-opposite');
        activeElement.classList.remove('active');
        prevElement.classList.add('active');
        prevElement.classList.add('fade-in-opposite');
        arrowDown.style.display = 'block';
        counter = counter - 1;
        currentText.textContent = counter < 10 ? `0${counter}/` : `${counter}/`;
        if (indexElement === 0) arrowUp.style.display = 'none';
        setTimeout(() => {
          activeElement.classList.remove('fade-out-opposite', 'fade-in-opposite');
          activeElement.classList.remove('fade-in', 'fade-out');
        }, 260);
      }
    }
  };

  const cleanItems = () => {
    const currentItems = document.querySelectorAll('.work-section > .active > div');
    currentItems.forEach(item => item.classList.remove('blur', 'send-to-back'));
  }

  const onWheelWorkSection = (event: React.WheelEvent<HTMLDivElement>) => {
    const { deltaY } = event;
    const downButton = document.querySelector('.work-counter .icon-down') as HTMLElement;
    const upButton = document.querySelector('.work-counter .icon-up') as HTMLElement;

    if (deltaY < 0 && !activatedAnimation && upButton.style.display === 'none') {
      (document.querySelector('.header-logo') as HTMLElement).click();
      setActivatedAnimation(true);

      setTimeout(() => {
        setActivatedAnimation(false);
      }, 850);
    }

    if (deltaY > 0 && !activatedAnimation && downButton.style.display !== 'none') {
      cleanItems();
      downButton.click();
      setActivatedAnimation(true);

      setTimeout(() => {
        setActivatedAnimation(false);
      }, 850);
    }

    if (deltaY < 0 && !activatedAnimation && upButton.style.display !== 'none') {
      cleanItems();
      upButton.click();
      setActivatedAnimation(true);

      setTimeout(() => {
        setActivatedAnimation(false);
      }, 850);
    }
  }

  return (
    <div className="work-list">
      <WorkCounter current={1} total={{mobile: projects.length, desktop: groupedProjects?.length}} onClickPage={onWorkCounterClick}/>
      <section className="work-section-mobile">
        <div>
          {projects?.map((project, index) => (
            <Link href={`/work/${project.id}`} key={index}>
              <a className="work-section-mobile-item">
                <figure>
                  <div className="image" style={{backgroundImage: `url('${project?.imageUrl}')`}}></div>
                </figure>
                <figcaption>
                  <span className="icon">
                    <RightArrow />
                  </span>
                  <span className="text">
                    {project?.title}
                  </span>
                </figcaption>
              </a>
            </Link>
          ))}
        </div>
      </section>
      <div className="work-section" onWheel={onWheelWorkSection}>
        {groupedProjects?.map((group, indexGroup) => (
          <div className={`${indexGroup === 0 ? 'active' : ''}`} data-index={indexGroup} key={indexGroup}>
            {group.map((project: Project, index: number) =>(
              <div 
                className={`work-section-item ${index === 0 ? 'item-one' : 'item-two'}`} 
                key={index}
                data-id={project.id}
                onMouseEnter={onMouseEnter} 
                onMouseLeave={onMouseLeave}
                onClick={(event: React.MouseEvent<HTMLDivElement>) => onClickProy(event, project.id)}>
                <figure>
                  {index === 1 && <figcaption>
                    <span className="icon">
                      <RightArrow />
                    </span>
                    <span className="text">{project?.title}</span>
                  </figcaption>}
                  <div className="image-mask">
                    {indexGroup === 0 && index === 1 && <div className="work-section-gallery">
                      {projects && projects.length > 0 && projects.map((proj, innerIndex) => (
                        <div key={innerIndex} className={`work-section-gallery-item`} style={{backgroundImage: `url(${proj?.imageUrl})`}}></div>
                      ))}
                    </div>}
                    <div className="image-mask-inner">
                      <div className="img" style={{backgroundImage: `url(${project?.imageUrl})`}}>
                        <div className="img-inner" style={{backgroundImage: `url(${project?.imageUrl})`}}></div>
                        <div className="image-link">
                          <span>view project</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  {index === 0 && <figcaption>
                    <span className="icon">
                      <RightArrow />
                    </span>
                    <span className="text">{project?.title}</span>
                  </figcaption>}
                </figure>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
};

export default WorkList;