import styled from '@emotion/styled';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';

import Button, { ButtonShape, ButtonVariant } from '@/components/button/Button';
import useDismount from '@/hooks/useDismount';
import {
  ArrowDownIcon,
  ArrowUpIcon,
  DownloadIcon,
  MicrophoneIcon,
  PauseIcon,
  PlayIcon,
  RemixIcon,
  StemsIcon,
  UploadIcon,
} from '@/icons';

import StudioLogo from '../StudioLogo';
import { useLogStudioWebUserEvent } from '../useLogStudioWebUserEvent';

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: 40px;
  max-width: 1280px;
  margin: 0 auto;
`;

const Header = styled.div`
  display: flex;
  flex-direction: column;
  gap: 12px;
  > svg {
    margin-left: -3px;
    margin-top: -4px;
    height: 40px;
    width: 330px;
  }
`;

const Subtitle = styled.p`
  font-size: 16px;
  color: var(--color-foreground-tertiary);
  max-width: 640px;
`;

const TutorialSection = styled.div`
  display: flex;
  justify-content: stretch;
  align-items: center;
  gap: 40px;
`;

const TutorialVideoWrapper = styled.div`
  background-color: black;
  aspect-ratio: 4/3;
  width: 720px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  object-fit-cover;
  position: relative;
  cursor: pointer;
`;

const VideoOverlay = styled.div<{ playing: boolean }>`
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition:
    opacity 0.2s ease-in-out,
    background-color 0.2s ease-in-out,
    color 0.2s ease-in-out;
  background-color: rgba(0, 0, 0, 0.35);
  color: rgba(255, 255, 255, 0.5);
  &:hover {
    color: rgba(255, 255, 255, 1);
  }

  ${({ playing }) =>
    playing &&
    `
      opacity: 0;
      background-color: rgba(0, 0, 0, 0.1);
      &:hover {
        opacity: 1;
        color: rgba(255, 255, 255, 1);
      }
    `}
`;

const TutorialList = styled.div`
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: space-between;
  gap: 16px;
`;

const TutorialButtons = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  min-height: 360px;
  gap: 8px;
`;

const Description = styled.p`
  font-size: 14px;
  color: var(--color-foreground-tertiary);
  line-height: 1.3;
`;

const tutorials: {
  title: string;
  description: string;
  videoUrl: string;
  icon: React.ReactNode;
}[] = [
  {
    title: 'Import Audio',
    description:
      'Drag and drop audio from a workspace, song details, or your local file system to start creating.',
    videoUrl: `https://cdn-o.suno.com/studio_sep_2025/suno%20studio%20mini%20tutorials-import%20audio.mp4`,
    icon: <UploadIcon />,
  },
  {
    title: 'Record Audio',
    description:
      'Select an audio input, arm the track, then press “record” (show Icon) to track audio directly onto the timeline.',
    videoUrl: `https://cdn-o.suno.com/studio_sep_2025/suno%20studio%20mini%20tutorials-record%20audio.mp4`,
    icon: <MicrophoneIcon />,
  },
  {
    title: 'Extract Stems',
    description:
      'Click on a song or double click on a clip header to see it in the details panel. Select “Extract Stems” to isolate each instrument.',
    videoUrl: `https://cdn-o.suno.com/studio_sep_2025/suno%20studio%20mini%20tutorials-split%20stems.mp4`,
    icon: <StemsIcon />,
  },
  {
    title: 'Add Instruments',
    description:
      'Click and drag to select a region of the timeline. Select an instrument, describe the sound, and click Create to add a new instrument part.',
    videoUrl: `https://cdn-o.suno.com/studio_sep_2025/suno%20studio%20mini%20tutorials-add%20instrument.mp4`,
    icon: <StemsIcon />,
  },
  {
    title: 'Remix Selection',
    description:
      'Select a region and drag it onto the create form to render it. Then use lyrics and styles to customize your remix.',
    videoUrl: `https://cdn-o.suno.com/studio_sep_2025/suno%20studio%20mini%20tutorials-remix%20section.mp4`,
    icon: <RemixIcon />,
  },
  {
    title: 'Export',
    description:
      'Select the “Full Song” option from the export menu to export your song to your Suno library, or select “Multitrack” to download a zip file with stems.',
    videoUrl: `https://cdn-o.suno.com/studio_sep_2025/suno%20studio%20mini%20tutorials-export.mp4`,
    icon: <DownloadIcon />,
  },
];

export default function OnboardingModalContent() {
  const logStudioWebUserEvent = useLogStudioWebUserEvent();

  const [activeTutorialIndex, setActiveTutorialIndex] = useState(0);
  const activeTutorial = useMemo(
    () => tutorials[activeTutorialIndex],
    [activeTutorialIndex]
  );
  const activeTutorialRef = useRef(activeTutorial);
  activeTutorialRef.current = activeTutorial;
  const [playing, setPlaying] = useState(false);
  const playingRef = useRef(playing);
  playingRef.current = playing;

  const videoRef = useRef<HTMLVideoElement>(null);
  const lastPlaybackStartTimeRef = useRef(0);
  const seekToZero = useCallback(() => {
    if (videoRef.current) {
      videoRef.current.currentTime = 0;
    }
  }, []);
  const pause = useCallback(() => {
    if (videoRef.current) {
      videoRef.current.pause();
    } else {
      console.error('No video element found');
    }
    setPlaying(false);
  }, []);
  const play = useCallback(() => {
    if (videoRef.current) {
      videoRef.current.play();
      setPlaying(true);
    } else {
      console.error('No video element found');
    }
  }, []);
  useEffect(() => {
    seekToZero();
  }, [activeTutorialIndex, seekToZero]);
  const receiveVideoRef = useCallback((video: HTMLVideoElement | null) => {
    videoRef.current = video;
    if (video) {
      const handlePlay = () => {
        lastPlaybackStartTimeRef.current = Date.now();
        setPlaying(true);
        logStudioWebUserEvent({
          actionName: 'StudioOnboardingModalVideoPlayed',
          context: {
            learnVideoSrc: video.src,
            learnVideoCurrentTime: video.currentTime,
            learnVideoTitle: activeTutorialRef.current.title,
          },
        });
      };
      const handlePause = () => {
        setPlaying(false);
        logStudioWebUserEvent({
          actionName: 'StudioOnboardingModalVideoPaused',
          context: {
            learnVideoSrc: video.src,
            learnVideoCurrentTime: video.currentTime,
            learnVideoLastPlayDurationSeconds:
              (Date.now() - lastPlaybackStartTimeRef.current) / 1000,
            learnVideoTitle: activeTutorialRef.current.title,
          },
        });
      };
      video.addEventListener('play', handlePlay);
      video.addEventListener('pause', handlePause);
      return () => {
        video.removeEventListener('play', handlePlay);
        video.removeEventListener('pause', handlePause);
      };
    }
  }, []);
  useDismount(() => {
    if (playingRef.current) {
      logStudioWebUserEvent({
        actionName: 'StudioOnboardingModalVideoPaused',
        context: {
          learnVideoSrc: videoRef.current?.src ?? 'UNKNOWN_SRC',
          learnVideoCurrentTime: videoRef.current?.currentTime ?? 0,
          learnVideoLastPlayDurationSeconds:
            (Date.now() - lastPlaybackStartTimeRef.current) / 1000,
          learnVideoTitle: activeTutorialRef.current.title,
        },
      });
    }
  }, 100);
  useEffect(() => {
    logStudioWebUserEvent({
      actionName: 'StudioOnboardingModalViewed',
      context: {},
    });
  }, []);
  return (
    <Wrapper>
      <Header>
        <StudioLogo />
        <Subtitle>
          Welcome to a new era of music production — one that matches your
          creativity, adapts to your sound, and pushes your ideas beyond what
          you imagined.
        </Subtitle>
      </Header>

      <TutorialSection>
        <TutorialList>
          <div>
            <Button
              shape={ButtonShape.Pill}
              icon={ArrowUpIcon}
              onClick={() => {
                setActiveTutorialIndex((prev) =>
                  prev === 0 ? tutorials.length - 1 : prev - 1
                );
              }}
            />
          </div>

          <TutorialButtons>
            {tutorials.map((t, i) => (
              <Button
                key={i}
                variant={ButtonVariant.Standard}
                active={i === activeTutorialIndex}
                className='max-w-[300px] rounded-[20px]'
                icon={i === activeTutorialIndex ? undefined : t.icon}
                onClick={() => {
                  seekToZero();
                  pause();
                  setActiveTutorialIndex(i);
                }}
              >
                <div className='flex flex-col items-start text-start'>
                  <div className='flex items-center gap-2 font-medium'>
                    {i === activeTutorialIndex && t.icon}
                    {t.title}
                  </div>
                  {i === activeTutorialIndex && (
                    <Description>{t.description}</Description>
                  )}
                </div>
              </Button>
            ))}
          </TutorialButtons>
          <div>
            <Button
              shape={ButtonShape.Pill}
              icon={ArrowDownIcon}
              onClick={() => {
                setActiveTutorialIndex((prev) =>
                  prev === tutorials.length - 1 ? 0 : prev + 1
                );
              }}
            />
          </div>
        </TutorialList>
        <TutorialVideoWrapper
          onClick={() => {
            if (playing) {
              pause();
            } else {
              play();
            }
          }}
        >
          <video src={activeTutorial.videoUrl} ref={receiveVideoRef} />
          <VideoOverlay playing={playing}>
            {playing ? (
              <PauseIcon className='h-12 w-12' />
            ) : (
              <PlayIcon className='h-12 w-12' />
            )}
          </VideoOverlay>
        </TutorialVideoWrapper>
      </TutorialSection>
    </Wrapper>
  );
}
