'use client';

import { useGateValue } from '@statsig/react-bindings';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { FAQ } from '@/app/(root)/account/AuraSubscriptions/FAQ';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ContestFooter from '@/components/contest/ContestFooter';
import ContestHero from '@/components/contest/ContestHero';
import RemixCTA from '@/components/contest/RemixCTA';
import SubmissionCountdown from '@/components/contest/SubmissionCountdown';
import VideoHighlightSection from '@/components/contest/VideoHighlightSection';
import {
  ContestSection,
  getSectionVisibility,
} from '@/components/contest/util';
import Link from '@/components/link/Link';
import NavigationBar from '@/components/navigationBar/NavigationBar';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import { ContestSchema } from '@/hooks/useContestClip';
import logWebUserEvent, {
  logHookWebGeneralEvent,
} from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';

import { ContestLandingPageData } from '../../collab/[contest_id]/landingTransform';

export type SunoContestPageProps = {
  contest: ContestSchema;
  contestClip: Clip | null;
  landingData: ContestLandingPageData;
};

const SunoContestPage: React.FC<SunoContestPageProps> = observer(
  ({ contest, contestClip, landingData }) => {
    const { session, clips } = useStores();

    const isTablet = useBreakpointMd();
    const [showPage, setShowPage] = useState(false);
    const showPageGate = useGateValue('hooks-creator-challenge-landing-page');

    const isStaff = session.isStaff;
    const isMobile = !isTablet;

    const sections = landingData.sections;
    const heroContent = landingData.heroContent;
    const remixCtaContent = landingData.remixCtaContent;
    const contestTimeline = landingData.contestTimeline;
    const videoContent = landingData.videoContent;
    const faqItems = landingData.faqContent;

    useEffect(() => {
      if (showPageGate) {
        setShowPage(true);
      } else {
        setShowPage(false);
      }
    }, [showPageGate]);

    useEffect(() => {
      if (contestClip) {
        clips.updateClips([contestClip]);
      }
    }, [contestClip]);

    useEffect(() => {
      if (!contest?.id) return;
      logWebUserEvent({
        actionName: 'PageViewed',
        componentContext: 'contest',
        principalObjectType: 'contest',
        principalObjectValue: contest.id,
        context: { slug: (contest as any).slug ?? undefined },
      });
    }, [contest?.id, (contest as any)?.slug]);

    if (!showPage) {
      return (
        <div className='flex h-screen w-full scale-[0.5] items-center justify-center bg-background-primary opacity-50'>
          <div className='flex items-center gap-1'>
            {[...Array(15)].map((_, i) => (
              <div
                key={i}
                className='w-1 animate-waveform rounded-full bg-primary md:w-2'
                style={{
                  height: '20px',
                  animation: `waveform ${Math.floor(Math.random() * 1000) + 500}ms ease-in-out infinite`,
                  animationDelay: `${Math.random() * 0.5}s`,
                }}
              />
            ))}
          </div>
        </div>
      );
    }

    return (
      <div className='scrollbar-hide w-full overflow-scroll bg-background-primary pb-[10px]'>
        <div className='fixed top-0 right-0 left-0 z-50 h-[90px] w-full p-[20px]'>
          <NavigationBar
            contestId={contest.id}
            contestSlug={(contest as any).slug ?? undefined}
            lockUpText=''
          />
        </div>
        {getSectionVisibility(sections, ContestSection.Hero, isStaff) && (
          <ContestHero
            contest={contest}
            contestClip={contestClip}
            title={heroContent.title ?? ''}
            description={heroContent.description ?? ''}
            {...(heroContent.heroBackgroundVideo
              ? {
                  heroBackgroundVideo:
                    isMobile && heroContent.heroBackgroundVideoMobile
                      ? heroContent.heroBackgroundVideoMobile
                      : heroContent.heroBackgroundVideo,
                }
              : {
                  heroBackgroundImage:
                    isMobile && heroContent.heroBackgroundImageMobile
                      ? heroContent.heroBackgroundImageMobile
                      : (heroContent.heroBackgroundImage ?? ''),
                })}
            remixCount={undefined}
            start={contestTimeline.contest_submissions_start}
            end={contestTimeline.contest_submissions_end}
            remixLabel={'Hook Contest'}
            showRemixCount={false}
            gradientClassName='pointer-events-none absolute inset-x-0 bottom-0 z-[1] h-1/2 md:h-[85%] bg-[linear-gradient(180deg,rgba(16,16,18,0)_12.26%,#101012_72.56%)]'
            titleClassName='max-w-[800px]'
            contestLabel='Contest'
            primaryCTA={
              <Button
                variant={ButtonVariant.Aura}
                size={ButtonSize.Large}
                shape={ButtonShape.Pill}
                style={{ padding: '10px 15px' }}
                onClick={() => {
                  logHookWebGeneralEvent({
                    actionName: 'CreateHookClicked',
                    context: {
                      hookId: '',
                      recommendationItemId: '',
                      entryPoint: 'contest',
                    },
                  });
                  window.open('/hooks/create', '_blank');
                }}
              >
                Create a Hook
              </Button>
            }
            secondaryCTA={
              <Link href={`/hooks`} target='_blank'>
                <Button
                  variant={ButtonVariant.Secondary}
                  size={ButtonSize.Large}
                  shape={ButtonShape.Pill}
                  style={{ padding: '10px 15px' }}
                  onClick={() => {}}
                >
                  View Hooks
                </Button>
              </Link>
            }
          />
        )}
        {getSectionVisibility(sections, ContestSection.RemixCTA, isStaff) && (
          <RemixCTA
            deadlineText={remixCtaContent.deadlineText ?? ''}
            headlineTop={remixCtaContent.headlineTop ?? ''}
            subheader={remixCtaContent.subheader ?? ''}
            remixLabel={remixCtaContent.remixLabel ?? ''}
            backgroundImageUrl={heroContent.heroBackgroundImage ?? ''}
            subheaderClassName='max-w-[400px]'
            clipId={contestClip?.id}
            contestId={contest.id}
            contestSlug={(contest as any).slug ?? undefined}
            primaryCTA={
              <Button
                variant={ButtonVariant.Aura}
                size={ButtonSize.Large}
                shape={ButtonShape.Pill}
                style={{ padding: '10px 15px' }}
                onClick={() => {
                  logHookWebGeneralEvent({
                    actionName: 'CreateHookClicked',
                    context: {
                      hookId: '',
                      recommendationItemId: '',
                      entryPoint: 'contest',
                    },
                  });
                  window.open('/hooks/create', '_blank');
                }}
              >
                Create a Hook
              </Button>
            }
          />
        )}
        {getSectionVisibility(
          sections,
          ContestSection.VideoHighlight,
          isStaff
        ) && (
          <VideoHighlightSection
            headline={videoContent.videoHeadline ?? ''}
            subheader={videoContent.videoSubheader ?? ''}
            videoSrc={
              videoContent.videoSrc ?? heroContent.heroBackgroundVideo ?? ''
            }
            className='bg-transparent'
          />
        )}
        {getSectionVisibility(sections, ContestSection.FAQ, isStaff) && (
          <div className='mx-auto mt-[100px] flex max-w-[2560px] flex-col gap-6 px-[20px] md:flex-row'>
            <div className='flex-1'>
              <div className='px-0'>
                <FAQ
                  items={faqItems}
                  headerClassName='bg-background-primary pl-0 hover:bg-background-primary'
                  className='w-full max-w-none pt-0'
                  contentClassName='bg-background-primary px-0 pl-0 pr-0'
                  title='How does it work?'
                  subheader=''
                  titleClassName='text-left text-[28px] font-medium not-italic leading-[32px] pt-0 md:text-[60px] md:leading-[54px]'
                />
              </div>
            </div>
            <div className='flex w-[260px]'>
              <SubmissionCountdown
                start={
                  new Date('2025-09-08T12:00:00Z').toISOString() ?? undefined
                }
                end={
                  new Date('2025-09-17T23:59:59Z').toISOString() ?? undefined
                }
                judgingStart={undefined}
                judgingEnd={undefined}
                winnersDate={
                  new Date('2025-09-24T23:59:59Z').toISOString() ?? undefined
                }
                clipId={contestClip?.id}
                contestId={contest.id}
                contestSlug={(contest as any).slug ?? undefined}
                primaryCTA={
                  <Button
                    variant={ButtonVariant.Primary}
                    size={ButtonSize.Large}
                    shape={ButtonShape.Pill}
                    className='w-full'
                    style={{ padding: '10px 15px' }}
                    onClick={() => {
                      logHookWebGeneralEvent({
                        actionName: 'CreateHookClicked',
                        context: {
                          hookId: '',
                          recommendationItemId: '',
                          entryPoint: 'contest',
                        },
                      });
                      window.open('/hooks/create', '_blank');
                    }}
                  >
                    Create Your Own Hook
                  </Button>
                }
              />
            </div>
          </div>
        )}
        <ContestFooter />
      </div>
    );
  }
);

export default SunoContestPage;
