import styled from '@emotion/styled';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useLocalStorage } from 'usehooks-ts';

import {
  ExtendRightIcon,
  EyeSlashIcon,
  PlusIcon,
  SectionIcon,
} from '@/icons/generated';
import { staticAssetUrl } from '@/utils/staticAssetUrl';

import Button, { ButtonShape, ButtonVariant } from '../button/Button';

const ButtonWrapper = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
`;

const LearnIcon = () => (
  <div className='flex h-5 w-5 -translate-y-px scale-[110%] items-center justify-center'>
    <svg
      width='19'
      height='19'
      viewBox='0 0 19 19'
      fill='none'
      xmlns='http://www.w3.org/2000/svg'
      className='-translate-x-[0.5px] -translate-y-[0.5px] transform'
    >
      <path
        d='M14 14.498C14 15.589 13.4074 16.5935 12.4531 17.1221L11.9072 17.4248C10.0987 18.4265 7.90134 18.4265 6.09277 17.4248L5.54688 17.1221C4.59256 16.5935 4 15.589 4 14.498V13.4531L7.9668 15.7373C8.58449 16.0929 9.34422 16.0929 9.96191 15.7373L14 13.4121V14.498Z'
        fill='#A3A3A3'
      />
      <path
        d='M8.08143 4.17702C8.72692 3.78336 9.53923 3.78734 10.1808 4.18732L16.6547 8.22315C17.2957 8.62275 17.2793 9.5615 16.6247 9.93839L10.0331 13.7334C9.41532 14.0891 8.65499 14.0891 8.03726 13.7334L1.46185 9.94772C0.803485 9.56868 0.791539 8.62289 1.44012 8.22734L8.08143 4.17702Z'
        fill='#A3A3A3'
      />
      <path d='M16 9.03516V12.5352' stroke='#A3A3A3' strokeLinecap='round' />
    </svg>
  </div>
);

interface LearnSectionCardProps {
  videoUrl: string;
  title: string;
  description: React.ReactNode;
  isPlaying: boolean;
  onEnded: () => void;
  index: number;
  onHover: (index: number) => void;
  onUnhover: () => void;
}

const LearnSectionCard: React.FC<LearnSectionCardProps> = ({
  videoUrl,
  title,
  description,
  isPlaying,
  onEnded,
  index,
  onHover,
  onUnhover,
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.play();
      } else {
        videoRef.current.pause();
        videoRef.current.currentTime = 0;
      }
    }
  }, [isPlaying]);

  return (
    <div
      className='group relative w-[156px] shrink-0 rounded-md bg-white/12'
      onMouseEnter={() => onHover(index)}
      onMouseLeave={onUnhover}
    >
      <video
        ref={videoRef}
        src={videoUrl}
        className='h-[90%] w-[156px] w-auto object-cover transition-opacity duration-200 group-hover:opacity-0'
        muted
        loop={false}
        playsInline
        onEnded={onEnded}
      />
      <div className='absolute right-0 bottom-0 left-0 mt-1 px-4 py-4 text-center text-sm text-white transition-opacity duration-200 group-hover:opacity-0'>
        {title}
      </div>
      <div className='absolute inset-0 flex items-center justify-center px-4 py-4 text-center text-xs text-white opacity-0 transition-opacity duration-200 group-hover:opacity-100'>
        {description}
      </div>
    </div>
  );
};

const learnSectionsData: LearnSectionCardProps[] = [
  {
    videoUrl: staticAssetUrl('studio/learn_replace.mp4'),
    title: 'Change lyrics or melodies',
    description: (
      <span>
        Try new lyrics or melodies by picking a clip or section.
        <br />
        <br />
        Hit the{' '}
        <span className='inline-flex items-center'>
          <Button
            variant={ButtonVariant.Aura}
            shape={ButtonShape.Pill}
            icon={<SectionIcon className='h-[0.8em] w-[0.8em]' />}
            className='inline-flex h-[1em] w-[1em] translate-y-px cursor-default justify-center'
          />
        </span>{' '}
        button to quick-replace, or use the left panel to tweak lyrics and
        style—then click Replace Section.
      </span>
    ),
    isPlaying: false,
    onEnded: () => {},
    index: 0,
    onHover: () => {},
    onUnhover: () => {},
  },
  {
    videoUrl: staticAssetUrl('studio/learn_add_section.mp4'),
    title: 'Add a new section',
    description: (
      <span>
        Add a section by clicking the{' '}
        <span className='inline-flex items-center'>
          <Button
            variant={ButtonVariant.Standard}
            shape={ButtonShape.Pill}
            icon={<PlusIcon className='h-[0.8em] w-[0.8em]' />}
            className='inline-flex h-[1em] w-[1em] translate-y-px cursor-default justify-center'
          />
        </span>{' '}
        above any section boundary.
        <br />
        <br />
        Then set the lyrics and style in the left panel.
      </span>
    ),
    isPlaying: false,
    onEnded: () => {},
    index: 1,
    onHover: () => {},
    onUnhover: () => {},
  },
  {
    videoUrl: staticAssetUrl('studio/learn_extend_song.mp4'),
    title: 'Extend your song',
    description: (
      <span>
        Add more to your track by clicking the{' '}
        <span className='inline-flex items-center'>
          <Button
            variant={ButtonVariant.DarkPrimary}
            shape={ButtonShape.Rounded}
            icon={<ExtendRightIcon className='h-[0.8em] w-[0.8em]' />}
            className='inline-flex h-[1em] w-[1em] translate-y-px cursor-default justify-center'
          />
        </span>{' '}
        on the right.
      </span>
    ),
    isPlaying: false,
    onEnded: () => {},
    index: 2,
    onHover: () => {},
    onUnhover: () => {},
  },
  {
    videoUrl: staticAssetUrl('studio/learn_rearrange_song.mp4'),
    title: 'Rearrange your song',
    description: (
      <>
        Click on the top region of any audio clip to select it.
        <br />
        <br />
        Then drag and drop it anywhere else on the timeline.
      </>
    ),
    isPlaying: false,
    onEnded: () => {},
    index: 3,
    onHover: () => {},
    onUnhover: () => {},
  },
  {
    videoUrl: staticAssetUrl('studio/learn_extract_stems.mp4'),
    title: 'Extract stems',
    description: (
      <>
        Split your song into separate instrument tracks.
        <br />
        <br />
        Then, remix or download them.
      </>
    ),
    isPlaying: false,
    onEnded: () => {},
    index: 4,
    onHover: () => {},
    onUnhover: () => {},
  },
];

export default function LearnWindow() {
  const [learnOpen, setLearnOpen] = useLocalStorage(
    'edit-v3-learn-open-may-30-2025',
    true
  );
  const [isVisible, setIsVisible] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [currentPlayingIndex, setCurrentPlayingIndex] = useState(0);
  const [isHovering, setIsHovering] = useState(false);
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);

  useEffect(() => {
    if (learnOpen) {
      setIsVisible(true);
      setTimeout(() => {
        setIsAnimating(true);
      }, 50);
    } else {
      setIsAnimating(false);
      setTimeout(() => {
        setIsVisible(false);
      }, 200);
    }
  }, [learnOpen]);

  const handleVideoEnded = useCallback(() => {
    if (!isHovering) {
      setCurrentPlayingIndex((prev) => (prev + 1) % learnSectionsData.length);
    }
  }, [isHovering]);

  const handleCardHover = useCallback((index: number) => {
    setIsHovering(true);
    setHoveredIndex(index);
  }, []);

  const handleCardUnhover = useCallback(() => {
    setIsHovering(false);
    if (hoveredIndex !== null) {
      setCurrentPlayingIndex(hoveredIndex);
    }
    setHoveredIndex(null);
  }, [hoveredIndex]);

  return (
    <div
      id='learn-window'
      className={`@container relative flex h-[248px] w-[814px] flex-col overflow-hidden rounded-lg transition-all duration-500 ${learnOpen ? 'pointer-events-auto' : 'pointer-events-none'}`}
    >
      <div
        className={`absolute h-full w-full bg-black p-1 transition-all duration-400 ${
          isAnimating ? '' : 'translate-x-full'
        }`}
      ></div>
      <ButtonWrapper>
        <Button
          className={`pointer-events-auto cursor-pointer text-[#A3A3A3] transition-all duration-400 ${
            isAnimating
              ? 'bg-white/0 delay-10' // subtle delay to account for distance from screen edge
              : 'translate-x-[calc(100cqw-100%)] bg-white/10'
          }`}
          shape={ButtonShape.Pill}
          icon={<LearnIcon />}
          onClick={() => {
            setLearnOpen((prev) => !prev);
          }}
        >
          Learn
        </Button>
      </ButtonWrapper>
      <Button
        variant={ButtonVariant.Glass}
        icon={<EyeSlashIcon className='scale-[110%]' />}
        className={`absolute top-0 right-[2px] cursor-pointer text-[#A3A3A3] transition-all duration-400 ${
          isAnimating ? '' : 'translate-x-[calc(100cqw-100%)] bg-white/10'
        }`}
        onClick={() => {
          setLearnOpen(false);
        }}
      >
        Hide Tips
      </Button>

      {isVisible && (
        <div
          className={`mx-2 flex h-[200px] origin-right gap-1 overflow-y-hidden transition-all duration-400 @max-[280px]:flex-nowrap @max-[280px]:overflow-x-auto ${
            isAnimating ? 'translate-x-0' : 'translate-x-full'
          }`}
        >
          {learnSectionsData.map((section, index) => (
            <LearnSectionCard
              key={section.title}
              title={section.title}
              description={section.description}
              videoUrl={section.videoUrl}
              isPlaying={!isHovering && index === currentPlayingIndex}
              onEnded={handleVideoEnded}
              index={index}
              onHover={handleCardHover}
              onUnhover={handleCardUnhover}
            />
          ))}
        </div>
      )}
    </div>
  );
}
