import { getSocketContext } from '@/lib/getSocketContext';
import trackAnalyticsEvent from '@/lib/trackAnalyticsEvent';
import { AccountContext } from '@/lib/useAccount';
import useStorageBackedState from '@/lib/useStorageBackedState';
import { dark, darkLine, gray200, gray300, gray400, gray700, gray800, lightSmoke, yellow } from '@/styles/colors';
import { UserRole } from '@/types';
import { css, keyframes } from '@emotion/react';
import styled from '@emotion/styled';
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import checkCircleIcon from '../icons/CheckCircle.svg';
import AuthWidget from './AuthWidget';
import { BracketButton, MainButton } from './Buttons';
import ErrorModal from './ErrorModal';
import LoadingTerminal, { LoadingLine } from './LoadingTerminal';
import QuickstartWidget, { StartButton } from './QuickstartWidget';
import { AuthModalState } from './auth/AuthModal';

const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL;
const APP_URL = process.env.NEXT_PUBLIC_APP_URL;

const LogoWrapper = styled.div`
  position: absolute;
  top: 20px;
  left: 50%;
  margin-left: -50px;
  width: 100px;
  img {
    width: 100%;
    height: auto;
  }
`;

const Container = styled.div<{ active: boolean }>`
  position: ${(props) => (props.active ? 'fixed' : 'absolute')};
  top: 0;
  height: 100vh;
  height: 100svh;
  min-height: 840px;
  width: 100svw;
  background: ${(props) => (props.active ? gray200 : 'none')};
  z-index: ${(props) => (props.active ? 14 : 13)};
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  align-items: center;
  transition: background 0.5s;
  @media screen and (max-width: 768px) {
    flex-direction: column;
    overflow: scroll;
    justify-content: flex-end;
    min-height: 0;
    max-height: 800px;
    .desktop-only {
      display: none;
    }
  }
`;

const QuickstartContainer = styled.div`
  max-width: 580px;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 10px;
  @media screen and (max-width: 768px) {
    width: 100%;
    max-width: none;
    flex: 0;
    height: auto;
    padding: 0;
  }
`;

const WidgetWrapper = styled.div`
  flex-shrink: 0;
  border-radius: 10px;
  background-color: white;
  padding: 30px;
  max-width: 580px;
  width: 100%;
  min-height: 610px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: stretch;
  @media screen and (max-width: 768px) {
    padding: 20px;
    max-width: none;
    border-radius: 0;
    min-height: 0;
    border-bottom: 1px solid ${darkLine};
  }
`;

const DetailsContainer = styled.div`
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  @media screen and (max-width: 768px) {
    height: auto;
  }
`;

const DetailsSection = styled.div`
  width: 400px;
  @media screen and (max-width: 960px) {
    width: 300px;
  }
`;

const MetadataSpacer = styled.div`
  margin-bottom: 4rem;
`;

const fadeUp = keyframes`
0% { opacity: 0; transform: translateY(20px); }
100% { opacity: 1; transform: translateY(0); }
`;
const MetadataContainer = styled.div`
  display: flex;
  flex-direction: column;
  background: ${gray400};
  padding: 20px;
  gap: 1rem;
  animation: ${fadeUp} 0.5s ease;
  border-radius: 8px;
`;
const TitleContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 1rem;
  color: ${gray800};
  p {
    margin: 0;
  }
`;

const SourceContainer = styled.div`
  color: ${gray700};
`;

const ExtractionIcon = styled.div`
  height: 30px;
  width: 30px;
  img {
    height: 100%;
    width: 100%;
  }
`;
const UploaderChannelContainer = styled.div`
  height: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
`;

const QuickstartSection = styled.div`
  width: 450px;
  padding: 3rem;
  background: white;
  border-radius: 8px;
  transition: height 0.3s;
`;
const InputContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 1rem 0 0;
`;
const MainInput = styled.input`
  flex: 1;
  height: 40px;
  border: none;
  width: 100%;
  background: white;
  border: 1px solid ${darkLine};
  border-radius: 12px 0 0 12px;
  width: 80%;
  color: ${dark};
  font-size: 1.5rem;
  padding: 1rem;

  &:active,
  &:focus {
    border: 1px solid ${dark};
    outline: none;
  }
`;
const SubmitButton = styled(MainButton)`
  width: 70px;
  height: 40px;
  padding: 0;
  font-size: 1.5rem;
  border-radius: 0 12px 12px 0;

  &:disabled {
    opacity: 1;
  }
`;
const LegalDisclaimer = styled.p`
  text-align: center;
  font-size: 1.2rem;
  color: ${lightSmoke};
`;

const pulseBackground = keyframes`
  0% {
    background-color: ${gray400};
  }
  50% {
    background-color: ${gray300};
  }
  100% {
    background-color: ${gray400};
  }
`;

const QuickStartCompleteButton = styled(StartButton)<{ error?: boolean }>`
  width: 100%;
  font-weight: 900;
  :disabled {
    background-color: ${(props) => (props.error ? gray400 : '')};
    opacity: ${(props) => (props.error ? 1 : 0)};
    color: ${(props) => (props.error ? yellow : '')};
    animation: ${(props) =>
      props.error
        ? css`
            ${pulseBackground} 2s infinite
          `
        : ''};
  }
`;

const LoggedInStateWrapper = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  color: white;
  opacity: 0.4;
`;

const LoggedInMessage = styled.p`
  text-align: center;
  font-size: 24px;
  margin: 0;
  padding: 0;
`;

const LoggedInState = ({ doneImporting }: { doneImporting?: boolean }) => {
  return (
    <LoggedInStateWrapper>
      <img {...checkCircleIcon} />
      <LoggedInMessage>
        You're signed in.
        <br />
        {doneImporting ? 'Your project is ready!' : 'Preparing your project...'}
      </LoggedInMessage>
    </LoggedInStateWrapper>
  );
};

const Quickstart = ({
  setAuthModalOpen,
  widgetHeading,
  widgetDescription,
  startFromScratchOptionShown = true,
  skillToOpen = '',
}: {
  setAuthModalOpen: (mode: AuthModalState) => void;
  widgetHeading: string;
  widgetDescription?: string;
  startFromScratchOptionShown?: boolean;
  skillToOpen?: string;
}) => {
  const router = useRouter();
  const cancelledRef = useRef(false);
  const account = useContext(AccountContext).account;
  const loggedIn = ![undefined, null, UserRole.LoggedOut].includes(account?.role);
  const [flowState, setFlowState] = useState<'initial' | 'importing'>('initial');
  const [sourceUrl, setSourceUrl] = useState('');
  const [loadingLines, setLoadingLines] = useState<LoadingLine[]>([]);
  const [creatingProject, setCreatingProject] = useState(false);
  const [projectRedirectData, setProjectRedirectData] = useState<{
    stems: any;
    bpm: number;
    duration: number;
    skillToOpen: string;
  }>();
  const [urlParseErrorModal, setUrlParseErrorModal] = useState(false);
  const [durationErrorModal, setDurationErrorModal] = useState(false);
  const [showLegalModal, setShowLegalModal] = useState(false);
  const legalModalPromiseRef = useRef<{ promise: Promise<void>; resolve: () => void; reject: () => void } | null>(null);
  const [agreedToLegal, setAgreedToLegal] = useStorageBackedState(false, `quickstart-legal-agreement-may-23-2024`);
  const [videoMetadata, setVideoMetadata] = useState<{
    title: string;
    duration: number;
    track: string;
    artist: string;
    channel: string;
    uploader: string;
    extractor: 'TikTok' | 'youtube';
  }>();

  const fileRef = useRef<File | null>(null);

  const handleStartFromScratch = useCallback(() => {
    trackAnalyticsEvent({
      name: 'Landing Button Clicked',
      properties: {
        text: 'start empty project',
        location: 'Quickstart',
      },
    });
    if (APP_URL && loggedIn) {
      window.location.href = APP_URL;
    } else {
      setAuthModalOpen('register');
    }
  }, [loggedIn]);

  const sourceHostname = useMemo(() => {
    try {
      let result = new URL(sourceUrl).hostname;
    } catch (e) {
      return null;
    }
  }, [sourceUrl]);

  const createProjectRedirect = (
    stems: { [key: string]: string },
    bpm: number,
    duration: number,
    skillToOpen: string
  ) => {
    const file = fileRef.current;
    trackAnalyticsEvent({
      name: 'Opened Quickstart Project',
      properties: {
        type: file ? 'file' : 'url',
        url: sourceUrl || null,
        urlHostname: sourceHostname || null,
        fileName: file?.name || null,
        fileExtension: file?.name.split('.').pop() || null,
        fileType: file?.type || null,
        fileSize: file?.size || null,
        bpm,
        roundBPM: bpm ? Math.round(bpm) : null,
        duration,
      },
    });
    setCreatingProject(true);
    setTimeout(() => {
      const stemJSON = JSON.stringify(stems);
      router.push(
        `${SERVER_URL}/auth/redirect?stems=${stemJSON}&bpm=${bpm}&duration=${duration}&skillToOpen=${skillToOpen}`
      );
    }, 750);
  };

  const getMetadataMutation = useMutation({
    mutationFn: async (url: string) => {
      setLoadingLines([{ text: 'Fetching metadata', progress: 0 }]);
      return await fetch(`${SERVER_URL}/api/quickstart/metadata`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url }),
      });
    },
    onSuccess: async (data) => {
      setLoadingLines([{ text: 'Fetching metadata', progress: 1 }]);
      const videoMetadata = await data?.json();
      if (videoMetadata.success === false) return setUrlParseErrorModal(true);
      const cleanData = {
        ...videoMetadata,
        title:
          sourceUrl.includes('suno') && videoMetadata.title.endsWith(' (1)')
            ? videoMetadata.title.slice(0, -4)
            : videoMetadata.title,
      };
      setVideoMetadata(cleanData);
      if (!['suno.com', 'udio.com'].find((x) => sourceUrl.toLowerCase().includes(x))) {
        let resolve: () => void;
        let reject: () => void;
        const promise = new Promise<void>((res, rej) => {
          resolve = res;
          reject = rej;
        });
        legalModalPromiseRef.current = {
          promise,
          resolve: () => {
            resolve();
            legalModalPromiseRef.current = null;
          },
          reject: () => {
            reject();
            legalModalPromiseRef.current = null;
          },
        };
      }
      if (!agreedToLegal && legalModalPromiseRef.current) {
        setShowLegalModal(true);
        await legalModalPromiseRef.current.promise;
      }

      submitUrlMutation.mutate({ url: sourceUrl, name: cleanData?.title });
    },
  });

  const submitUrlMutation = useMutation({
    mutationFn: async ({ url, name }: { url: string; name: string }) =>
      new Promise<{ success: boolean; stems: { [key: string]: string }; bpm: number; duration: number }>(
        (resolve, reject) => {
          if (cancelledRef.current) return;
          console.log('submitting url', url, name);
          const socket = getSocketContext();
          console.log('got socket context!');
          socket.emit('message', { service: 'quickstart', action: 'rip', payload: { url, name, withStems: true } });
          let lastProgress: LoadingLine[] = [];
          let ignoreProgress = false;
          socket.on('progress', (message) => {
            if (cancelledRef.current) return;
            if (ignoreProgress) return;
            console.log('progress', message);
            lastProgress = message;
            setLoadingLines([{ text: 'Fetching metadata', progress: 1 }, ...message]);
          });
          socket.once('final', (message: any) => {
            if (cancelledRef.current) return;
            ignoreProgress = true;
            if (message.error) {
              console.log('error', message);
              reject(new Error(message.error));

              setLoadingLines([
                { text: 'Fetching metadata', progress: 1 },
                ...lastProgress.map((line) => ({ ...line, progress: 1 })),
                { text: 'Unable to complete', progress: 0 },
              ]);
            } else {
              setLoadingLines([
                { text: 'Fetching metadata', progress: 1 },
                ...lastProgress.map((line) => ({ ...line, progress: 1 })),
                { text: 'Preparing Project', progress: 0 },
              ]);
              resolve(message as { success: boolean; stems: { [key: string]: string }; bpm: number; duration: number });
            }
          });
        }
      ),
    onSuccess: async (data) => {
      if (cancelledRef.current) return;
      const { success, stems, bpm, duration } = data;
      if (success === false) return setUrlParseErrorModal(true);
      if (success && !!stems) {
        setTimeout(() => {
          setCreatingProject(false);
          setProjectRedirectData({ stems, bpm, duration, skillToOpen });
          trackAnalyticsEvent({
            name: 'Finished Quickstart Import',
            properties: {
              type: 'url',
              url: sourceUrl,
              urlHostname: new URL(sourceUrl).hostname,
              fileName: null,
              fileExtension: null,
              fileType: null,
              fileSize: null,
              bpm,
              roundBPM: bpm ? Math.round(bpm) : null,
              duration,
            },
          });
          setLoadingLines((prev) => prev.map((l) => ({ ...l, progress: 1 })));
        }, 500);
      }
    },
    onError: async (error) => {
      return setUrlParseErrorModal(true);
    },
  });

  const submitUploadedUUIDMutation = useMutation({
    mutationFn: async (uuid: string) =>
      new Promise<{ success: boolean; stems: { [key: string]: string }; bpm: number; duration: number }>(
        (resolve, reject) => {
          if (cancelledRef.current) return;
          setLoadingLines([{ text: 'Uploading', progress: 0.99 }]);
          console.log('submitting uuid', uuid, name);
          const socket = getSocketContext();
          console.log('got socket context!');
          socket.emit('message', {
            service: 'quickstart',
            action: 'uploaded',
            payload: { uuid, withStems: true },
          });
          let lastProgress: LoadingLine[] = [];
          let ignoreProgress = false;
          socket.on('progress', (message) => {
            if (cancelledRef.current) return;
            if (ignoreProgress) return;
            console.log('progress', message);
            lastProgress = message;
            setLoadingLines([{ text: 'Uploading', progress: 1 }, ...message]);
          });
          socket.once('final', (message: any) => {
            if (cancelledRef.current) return;
            ignoreProgress = true;
            if (message.error) {
              console.log('error', message);
              reject(new Error(message.error));

              setLoadingLines([
                { text: 'Uploading', progress: 1 },
                ...lastProgress.map((line) => ({ ...line, progress: 1 })),
                { text: 'Unable to complete', progress: 0 },
              ]);
            } else {
              setLoadingLines([
                { text: 'Uploading', progress: 1 },
                ...lastProgress.map((line) => ({ ...line, progress: 1 })),
                { text: 'Preparing Project', progress: 0 },
              ]);
              resolve(message as { success: boolean; stems: { [key: string]: string }; bpm: number; duration: number });
            }
          });
        }
      ),
    onSuccess: async (data) => {
      if (cancelledRef.current) return;
      const { success, stems, bpm, duration } = data;
      if (success === false) return setUrlParseErrorModal(true);
      if (success && !!stems) {
        setTimeout(() => {
          setCreatingProject(false);
          setProjectRedirectData({ stems, bpm, duration, skillToOpen });
          const file = fileRef.current;
          trackAnalyticsEvent({
            name: 'Finished Quickstart Import',
            properties: {
              type: 'file',
              url: null,
              urlHostname: null,
              fileName: file?.name || null,
              fileExtension: file?.name.split('.').pop() || null,
              fileType: file?.type || null,
              fileSize: file?.size || null,
              bpm,
              roundBPM: bpm ? Math.round(bpm) : null,
              duration,
            },
          });
          setLoadingLines((prev) => prev.map((l) => ({ ...l, progress: 1 })));
        }, 500);
      }
    },
    onError: async (error) => {
      return setUrlParseErrorModal(true);
    },
  });

  useEffect(() => {
    const onPopState = () => {
      if (flowState === 'importing') {
        cancelledRef.current = true;
        setFlowState('initial');
        resetState();
      }
    };
    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, [flowState]);

  const startImporting = useCallback(() => {
    history.pushState({ importing: true }, '', '/');
    setFlowState('importing');
  }, []);

  const handleSubmitUrl = (url: string = sourceUrl) => {
    fileRef.current = null;
    if (url) {
      trackAnalyticsEvent({
        name: 'Started Quickstart Import',
        properties: {
          type: 'url',
          url: url,
          urlHostname: new URL(url).hostname,
          fileName: null,
          fileExtension: null,
          fileType: null,
          fileSize: null,
        },
      });
      cancelledRef.current = false;
      startImporting();
      getMetadataMutation.mutate(url);
    }
  };

  const resetState = useCallback(() => {
    setDurationErrorModal(false);
    setUrlParseErrorModal(false);
    getMetadataMutation.reset();
    submitUrlMutation.reset();
    setCreatingProject(false);
    setVideoMetadata(undefined);
    setFileUploading(false);
    setLoadingLines([]);
  }, []);

  const [fileUploading, setFileUploading] = useState(false);

  const handleSetFile = useCallback((file: File | null) => {
    fileRef.current = file;
    if (file) {
      trackAnalyticsEvent({
        name: 'Started Quickstart Import',
        properties: {
          type: 'file',
          url: null,
          urlHostname: null,
          fileName: file.name,
          fileExtension: file.name.split('.').pop() || null,
          fileType: file.type,
          fileSize: file.size,
        },
      });

      cancelledRef.current = false;
      startImporting();
      setFileUploading(true);
      setLoadingLines([{ text: 'Uploading', progress: 0 }]);
      var formdata = new FormData();
      formdata.append('file', file);
      var request = new XMLHttpRequest();
      request.upload.addEventListener(
        'progress',
        (e) => {
          setLoadingLines([{ text: 'Uploading', progress: Math.min(0.99, e.loaded / e.total) }]);
        },
        false
      );
      request.addEventListener(
        'load',
        (e) => {
          setFileUploading(false);
          const sampleUUID = (e.currentTarget as XMLHttpRequest)?.responseText;
          submitUploadedUUIDMutation.mutate(sampleUUID);
        },
        false
      );
      request.addEventListener(
        'error',
        (e) => {
          setFileUploading(false);
          console.error('error', e);
          setLoadingLines([
            { text: 'Uploading', progress: 1 },
            { text: 'Error uploading file', progress: 0 },
          ]);
        },
        false
      );
      request.addEventListener(
        'abort',
        (e) => {
          setFileUploading(false);
          console.error('abort', e);
          setLoadingLines([
            { text: 'Uploading', progress: 1 },
            { text: 'Upload aborted', progress: 0 },
          ]);
        },
        false
      );
      request.open('POST', SERVER_URL + '/api/quickstart/upload');
      request.send(formdata);
    }
  }, []);

  const isAnythingLoading =
    fileUploading ||
    getMetadataMutation.isLoading ||
    submitUrlMutation.isLoading ||
    submitUploadedUUIDMutation.isLoading ||
    !!videoMetadata ||
    creatingProject;

  const notLoggedIn = account?.role === UserRole.LoggedOut;

  useEffect(() => {
    if (flowState === 'importing') {
      document.body.style.overflow = 'hidden';
      const handleBeforeUnload = () => {
        return 'Are you sure? Your import will be cancelled.';
      };
      window.onbeforeunload = handleBeforeUnload;
      return () => {
        window.onbeforeunload = null;
      };
    } else {
      document.body.style.overflow = 'auto';
    }
  }, [flowState]);

  const wrapperRef = useRef<HTMLDivElement>(null);

  const hasRunQuickstartRef = useRef(false);

  useEffect(() => {
    const href = window.location.href;
    if (hasRunQuickstartRef.current) return;
    hasRunQuickstartRef.current = true;
    if (window.innerWidth < 768) return;
    if (href.includes('quickstart_url=')) {
      const url = new URL(href).searchParams.get('quickstart_url');
      if (url) {
        setSourceUrl(url);
        handleSubmitUrl(url);
      }
    }
  }, []);

  const importSource = sourceHostname ? sourceHostname : fileRef.current?.name;

  return (
    <Container active={flowState === 'importing'} ref={wrapperRef}>
      <LogoWrapper>
        <img src="/images/wordmark.svg" height={36} width={36} alt="WavTool Logo" />
      </LogoWrapper>
      <QuickstartContainer>
        <WidgetWrapper
          style={
            loggedIn && flowState === 'importing'
              ? { backgroundColor: 'transparent', minHeight: 0, boxShadow: 'none' }
              : undefined
          }
        >
          {flowState === 'importing' ? (
            loggedIn ? (
              <LoggedInState doneImporting={!!projectRedirectData} />
            ) : (
              <AuthWidget />
            )
          ) : (
            <QuickstartWidget
              widgetHeading={widgetHeading}
              widgetDescription={widgetDescription}
              setFile={handleSetFile}
              sourceUrl={sourceUrl}
              setSourceUrl={setSourceUrl}
              onSubmit={handleSubmitUrl}
              onStartFromScratch={handleStartFromScratch}
              startFromScratchOptionShown={startFromScratchOptionShown}
              onLearnMore={() => {
                window.scrollTo({
                  top: (wrapperRef.current?.getBoundingClientRect()?.height || window.innerHeight) - 48,
                  behavior: 'smooth',
                });
              }}
            />
          )}
        </WidgetWrapper>
      </QuickstartContainer>
      <DetailsContainer className={flowState === 'importing' ? '' : 'desktop-only'}>
        <DetailsSection>
          <MetadataSpacer>
            {videoMetadata && (
              <MetadataContainer>
                {['TikTok', 'youtube'].includes(videoMetadata.extractor) ? (
                  <TitleContainer>
                    <ExtractionIcon>
                      {videoMetadata.extractor === 'TikTok' && <img src="/images/tiktok-logo.png" />}
                      {videoMetadata.extractor === 'youtube' && <img src="/images/youtube-logo.png" />}
                    </ExtractionIcon>
                    <UploaderChannelContainer>
                      <strong>{videoMetadata.uploader}</strong>
                      {videoMetadata.extractor === 'TikTok' && <p>{videoMetadata.channel}</p>}
                    </UploaderChannelContainer>
                  </TitleContainer>
                ) : importSource ? (
                  <SourceContainer>
                    Importing from <strong>{importSource}</strong>
                  </SourceContainer>
                ) : null}
                <TitleContainer>
                  <p>
                    {(videoMetadata.title || '').length > 70
                      ? `${videoMetadata.title.slice(0, 70)}...`
                      : videoMetadata.title}
                  </p>
                </TitleContainer>
                {!!videoMetadata.track && !!videoMetadata.artist && (
                  <TitleContainer>
                    <p>
                      🔊 {videoMetadata.track} - {videoMetadata.artist}
                    </p>
                  </TitleContainer>
                )}
              </MetadataContainer>
            )}
          </MetadataSpacer>
          {loadingLines.length > 0 && (
            <LoadingTerminal
              title="Importing Song..."
              lines={loadingLines}
              maxLines={6}
              done={!isAnythingLoading}
              color={gray800}
            />
          )}
          {urlParseErrorModal && (
            <ErrorModal
              onClick={() => history.back()}
              message={
                <span style={{ color: 'white', textAlign: 'center' }}>
                  {sourceUrl.toLowerCase().includes('suno.com') ? (
                    <>
                      This song is missing, private, or still processing. <br />
                      Please allow up to five minutes for Suno to generate the full song, and try again.
                    </>
                  ) : (
                    <>
                      This song or video is unsupported.
                      <br />
                      Please try again with a different file or URL.
                    </>
                  )}
                  <BracketButton style={{ color: 'white', margin: '0 auto -5px auto' }}>Go Back</BracketButton>
                </span>
              }
            />
          )}
          {durationErrorModal && (
            <ErrorModal
              onClick={() => history.back()}
              message={
                <span style={{ color: 'white', textAlign: 'center' }}>
                  This song or video is too long.
                  <BracketButton style={{ color: 'white', margin: '0 auto -5px auto' }}>Go Back</BracketButton>
                </span>
              }
            />
          )}
          {flowState === 'importing' && (
            <QuickStartCompleteButton
              emphasized={true}
              error={!!(notLoggedIn && !!projectRedirectData)}
              onClick={() => {
                if (!!projectRedirectData) {
                  const { stems, bpm, duration, skillToOpen } = projectRedirectData;
                  window.onbeforeunload = null;
                  createProjectRedirect(stems, bpm, duration, skillToOpen);
                }
              }}
              disabled={notLoggedIn || !projectRedirectData}
            >
              {!projectRedirectData ? 'Preparing...' : ''}
              {notLoggedIn && !!projectRedirectData ? '⚠️ Log In or Sign Up to Continue' : ''}
              {!notLoggedIn && !!projectRedirectData ? 'Go to Project' : ''}
            </QuickStartCompleteButton>
          )}
        </DetailsSection>
      </DetailsContainer>
    </Container>
  );
};

export default Quickstart;
