import { AudioPlaybackContext } from '@/lib/useAudioPlayback';
import { gray300, gray400, gray600, lightLine, white, yellow } from '@/styles/colors';
import { BELOW_W_768, maxMainContentWidth, paddedMainContentWidth } from '@/styles/dimensions';
import styled from '@emotion/styled';
import { useRouter } from 'next/router';
import { Dispatch, SetStateAction, useContext, useEffect, useRef, useState } from 'react';
import PauseIcon from '../icons/Pause.svg';
import PlayIcon from '../icons/Play.svg';

const Wrapper = styled.div<{ isOverflown: boolean | null }>`
  padding: 20px 0;
  background: ${(props) =>
    props.isOverflown
      ? `linear-gradient(90deg, ${lightLine} 0%, ${lightLine} 80%, rgba(0, 0, 0, 0.3) 100%);`
      : lightLine};
`;

const MadeWithWavToolText = styled.div`
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  font-size: 3rem;
  margin: 2rem;
`;

const ScrollContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow-x: auto;
  overflow-y: hidden;
  width: ${paddedMainContentWidth};

  @media screen and (${BELOW_W_768}) {
    width: 100vw;
  }
`;

const BlockContainer = styled.div`
  width: 300px;
  height: 350px;
  display: inline-block;
  margin: 0 10px;
  padding: 30px 20px;
`;
const Artwork = styled.div<{ url?: string }>`
  width: 200px;
  aspect-ratio: 1/1;
  background: ${gray600};
  margin-bottom: 8px;
  position: relative;
  background-image: url(${(props) => props.url});
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
`;
const Logo = styled.img`
  position: absolute;
  width: 75%;
  height: 75%;
`;
const TrackName = styled.h2`
  font-size: 2.5rem;
  font-weight: bold;
  display: inline-block;
  background: white;
  margin: 0.5rem 0;
`;
const ArtistName = styled.a<{ hasLink: boolean }>`
  font-size: 1.4rem;
  display: inline-block;
  background: white;
  font-family: Architekt;
  color: ${gray400};
  text-decoration: none;
  transition: all 0.3s;
  ${(props) =>
    props.hasLink &&
    `
  cursor: pointer;

  &:hover {
    background: ${gray300};
    color: ${white};

    svg {
      fill: ${white};
    }
  }
  `}
`;
const Play = styled.div<{ hover: boolean }>`
  opacity: 0.8;
  width: 80px;
  height: 80px;
  background: ${white};
  border-radius: 128px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: transform 0.3s;
  ${(props) => props.hover && `transform: scale(1.2);`}
`;
const RemixThisButton = styled.button`
  font-family: Architekt;
  position: absolute;
  top: 0;
  right: 0;
  background: ${yellow};
  border: none;
  padding: 0.5rem 1rem;
  cursor: pointer;
  z-index: 3;
  transition:
    background 0.3s,
    color 0.3s;

  &:hover {
    background: ${gray300};
    color: ${white};
  }
`;

const ExternalLinkIconSvg = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 30 30"
    width="16px"
    height="16px"
    style={{ margin: '0 4px', transition: 'all 0.3s' }}
  >
    <path d="M 25.980469 2.9902344 A 1.0001 1.0001 0 0 0 25.869141 3 L 20 3 A 1.0001 1.0001 0 1 0 20 5 L 23.585938 5 L 13.292969 15.292969 A 1.0001 1.0001 0 1 0 14.707031 16.707031 L 25 6.4140625 L 25 10 A 1.0001 1.0001 0 1 0 27 10 L 27 4.1269531 A 1.0001 1.0001 0 0 0 25.980469 2.9902344 z M 6 7 C 4.9069372 7 4 7.9069372 4 9 L 4 24 C 4 25.093063 4.9069372 26 6 26 L 21 26 C 22.093063 26 23 25.093063 23 24 L 23 14 L 23 11.421875 L 21 13.421875 L 21 16 L 21 24 L 6 24 L 6 9 L 14 9 L 16 9 L 16.578125 9 L 18.578125 7 L 16 7 L 14 7 L 6 7 z" />
  </svg>
);

const Block = ({
  name,
  artist,
  imgUrl,
  onClick,
  remixUrl,
  isPlaying,
  artistLink,
}: {
  name: string;
  artist: string;
  onClick: () => void;
  isPlaying: boolean;
  imgUrl?: string;
  remixUrl?: string;
  artistLink?: string;
}) => {
  const router = useRouter();
  const [hover, setHover] = useState(false);
  const blockRef = useRef<HTMLDivElement>(null);
  const remixThisRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    const handleMouseEnter = () => setHover(true);
    const handleMouseLeave = () => setHover(false);
    const handleRemixThisMouseEnter = () => setHover(false);
    const handleRemixThisMouseLeave = () => setHover(true);

    const block = blockRef.current;
    const remixThisButton = remixThisRef.current;
    remixThisButton?.addEventListener('mouseenter', handleRemixThisMouseEnter);
    remixThisButton?.addEventListener('mouseleave', handleRemixThisMouseLeave);
    block?.addEventListener('mouseenter', handleMouseEnter);
    block?.addEventListener('mouseleave', handleMouseLeave);
    return () => {
      remixThisButton?.removeEventListener('mouseenter', handleRemixThisMouseEnter);
      remixThisButton?.removeEventListener('mouseleave', handleRemixThisMouseLeave);
      block?.removeEventListener('mouseenter', handleMouseEnter);
      block?.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, []);

  return (
    <BlockContainer>
      <Artwork url={imgUrl} onClick={onClick} ref={blockRef}>
        {!imgUrl && <Logo src="/images/square-logo-white.svg" />}
        <Play hover={hover}>
          {isPlaying ? (
            <img {...PauseIcon} style={{ width: 48, height: 48 }} />
          ) : (
            <img {...PlayIcon} style={{ width: 48, height: 48, transform: 'translateX(6px)' }} />
          )}
        </Play>
        {!!remixUrl && (
          <RemixThisButton
            ref={remixThisRef}
            onClick={(e) => {
              e.stopPropagation();
              router.push(remixUrl);
            }}
          >
            Remix This
          </RemixThisButton>
        )}
      </Artwork>
      <div>
        <TrackName>{name}</TrackName>
      </div>
      <div>
        <ArtistName hasLink={!!artistLink} href={artistLink} target="_blank">
          {artist}
          {!!artistLink && <ExternalLinkIconSvg />}
        </ArtistName>
      </div>
    </BlockContainer>
  );
};

export interface TrackInfo {
  name: string;
  artist: string;
  audioUrl: string;
  imgUrl?: string;
  remixUrl?: string;
  artistLink?: string;
}

export const showcaseTracks: TrackInfo[] = [
  {
    name: 'Back!',
    artist: 'Guy Akimoto',
    audioUrl: '/audio/Back.mp3',
    imgUrl: '/images/artwork/back.jpeg',
    remixUrl: 'https://wavtool.com/remix/redirect/93706d1a-463d-4eb2-94a8-76f7017ffc1f',
  },
  {
    name: 'Velvet Dream',
    artist: 'David Kapusi',
    imgUrl: '/images/artwork/velvet-dream.jpg',
    audioUrl: '/audio/David_Kapusi.mp3',
    // remixUrl: 'https://app.wavtool.com/project/59556ae7-ecdf-40a9-a5e5-4dc803f97a11', // project has VST and other dependencies + is very heavy
    artistLink: 'https://youtube.com/@davidkapusi?si=PvZ3hMXIy3OUvy6z',
  },
  {
    name: 'My Wave',
    artist: 'Khanchi',
    audioUrl: '/audio/My_Wave.mp3',
    imgUrl: '/images/artwork/my-wave.jpg',
    remixUrl: 'https://wavtool.com/remix/redirect/a246b240-9ef7-4101-b1d0-de583d59d269',
  },
  {
    name: 'Surfing With AI',
    artist: 'Mateusz Drozd',
    audioUrl: '/audio/Mateusz_Drozd.mp3',
    imgUrl: '/images/artwork/surfing-with-ai-24.jpeg',
    remixUrl: 'https://wavtool.com/remix/redirect/65052fab-e65f-41cb-9fe1-c12d11a1da67',
  },
  {
    name: 'This Time',
    artist: 'Guy Akimoto',
    audioUrl: '/audio/This_Time.mp3',
  },
];

const MadeWithWavTool = ({
  selectedTrack,
  setSelectedTrack,
}: {
  selectedTrack?: TrackInfo;
  setSelectedTrack: Dispatch<SetStateAction<TrackInfo | undefined>>;
}) => {
  const audioPlayback = useContext(AudioPlaybackContext);
  const containerRef = useRef<HTMLDivElement>(null);
  const [isOverflown, setIsOverflown] = useState(false);

  useEffect(() => {
    const calculateIsOverflown = () => {
      if (!containerRef.current) return;
      setIsOverflown(containerRef.current.scrollWidth > Math.min(maxMainContentWidth, window.innerWidth - 2 * 48));
    };
    calculateIsOverflown();
    window.addEventListener('resize', calculateIsOverflown);
    return () => {
      window.removeEventListener('resize', calculateIsOverflown);
    };
  }, []);

  return (
    <Wrapper isOverflown={isOverflown}>
      <MadeWithWavToolText>
        Made with
        <img src="/images/wordmark-black.svg" height={32} width={118} alt="WavTool Logo" />
      </MadeWithWavToolText>
      <ScrollContainer ref={containerRef}>
        {showcaseTracks.map((track) => {
          const isCurrentTrack = track.name === selectedTrack?.name;
          return (
            <Block
              isPlaying={isCurrentTrack && audioPlayback.playing}
              key={track.name}
              imgUrl={track.imgUrl}
              name={track.name}
              artist={track.artist}
              artistLink={track.artistLink}
              remixUrl={track.remixUrl}
              onClick={() => {
                if (isCurrentTrack) {
                  if (audioPlayback.playing) {
                    audioPlayback.stop();
                  } else {
                    audioPlayback.play();
                  }
                } else setSelectedTrack(track);
              }}
            />
          );
        })}
      </ScrollContainer>
    </Wrapper>
  );
};

export default MadeWithWavTool;
