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

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import Modal from '@/components/modal/Modal';
import { staticAssetUrl } from '@/utils/staticAssetUrl';

interface WelcomeEditModalProps {
  onClose: () => void;
}

/*
  The modal is largely visual, so we lean on tailwind utility classes for
  layout / colours and use emotion styled wrappers for the few elements that
  benefit from positional styling (e.g. gradient overlays, absolute centring).
*/

const Container = styled.div`
  position: relative;
  width: 560px;
  height: 635px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  border-radius: 32px;
  overflow: hidden;
  background: #141416;
  border: 0.5px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 26px;
`;

const GradientOverlay = styled.div`
  position: absolute;
  inset: 0;
  background: linear-gradient(180deg, rgba(37, 32, 32, 0) 51.38%, #252020 100%);
  z-index: 0;
`;

const TopMedia = styled.div`
  position: relative;
  width: 100%;
  height: 340px;
  background: #000;
  overflow: hidden;
  flex-shrink: 0;
`;

const ProgressTrack = styled.div`
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 100px;
  overflow: hidden;
`;

const ProgressFilled = styled.div`
  height: 100%;
  background: #d9d9d9;
  width: 0%;
`;

const Headline = styled.div`
  font-family: 'PP Editorial New', serif;
  font-weight: 300;
  font-size: 36px;
  line-height: 40px;
  letter-spacing: -0.04em;
  color: #ffffff;
  text-align: center;
  width: 340px;
`;

const SubHeadline = styled.div`
  font-family: 'PP Neue Montreal', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  text-align: center;
  color: #faf7f5;
`;

export default function WelcomeEditModal({ onClose }: WelcomeEditModalProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const progressRef = useRef<HTMLDivElement>(null);
  const [buttonEnabled, setButtonEnabled] = useState(false);
  const videoEndedRef = useRef(false);

  useEffect(() => {
    const video = videoRef.current;
    const progressEl = progressRef.current;
    if (!video || !progressEl) return;

    let rafId: number;
    const update = () => {
      if (videoEndedRef.current) {
        return; // keep bar filled
      }
      if (video.duration) {
        const ratio = video.currentTime / video.duration;
        progressEl.style.width = `${ratio * 100}%`;

        // Check if we've reached the end for the first time
        if (ratio >= 0.99 && !videoEndedRef.current) {
          progressEl.style.width = '100%';
          cancelAnimationFrame(rafId);
          videoEndedRef.current = true;
          setButtonEnabled(true);
          return;
        }
      }
      rafId = requestAnimationFrame(update);
    };

    rafId = requestAnimationFrame(update);

    return () => {
      cancelAnimationFrame(rafId);
    };
  }, []);

  // Escape hatch: enable after 10s regardless
  useEffect(() => {
    const id = setTimeout(() => {
      setButtonEnabled(true);
    }, 5000);
    return () => clearTimeout(id);
  }, []);

  return (
    <Modal
      onClose={onClose}
      width={560}
      disablePadding
      showCloseButton={true}
      contentWrapperClasses='overflow-visible p-0'
      wrapperClasses='overflow-visible max-h-none'
      className='backdrop-blur-[5px]'
      disableOutsideClick
    >
      <Container>
        {/* Gradient overlay on top of the entire container */}
        <GradientOverlay />

        {/* Top media / video placeholder */}
        <TopMedia>
          <video
            ref={videoRef}
            src={staticAssetUrl('studio/welcome_edit_modal.mp4')}
            autoPlay
            loop
            muted
            playsInline
            className='h-full w-full translate-y-[-10px] scale-[1.05] object-cover'
          />
          <ProgressTrack>
            <ProgressFilled ref={progressRef} />
          </ProgressTrack>
        </TopMedia>

        {/* Headline & sub text */}
        <div className='flex flex-col items-center gap-2 px-4'>
          <Headline>Welcome To The New Suno Song Editor</Headline>
          <SubHeadline>
            Make a selection to start editing.
            <br />
            Rearrange, rewrite, and make your music uniquely yours.
          </SubHeadline>
        </div>

        {/* CTA button */}
        <div className='flex w-full flex-col items-center px-4'>
          <Button
            size={ButtonSize.Medium}
            variant={ButtonVariant.Primary}
            shape={ButtonShape.Pill}
            className='h-12 w-[352px]'
            disabled={!buttonEnabled}
            onClick={onClose}
          >
            {buttonEnabled ? 'Try now' : 'Preparing Editor...'}
          </Button>
        </div>
      </Container>
    </Modal>
  );
}
