import UploadIcon from '@/icons/UploadV2.svg';
import { blue700, gray700, lightLine, newBlue, red500, standardGrey, yellow } from '@/styles/colors';
import styled from '@emotion/styled';
import { DetailedHTMLProps, FormEvent, HTMLAttributes, useCallback, useRef } from 'react';
import { BracketButton, StandardButton } from './Buttons';
import Tooltip from './Tooltip';

export const H1 = styled.h1`
  font-family: Montreal;
  letter-spacing: -3px;
  font-size: 48px;
  font-weight: 500;
  @media screen and (max-width: 860px) {
    font-size: 36px;
    letter-spacing: -2.6px;
  }
`;

export const Paragraph = styled.p`
  font-weight: 100;
  font-size: 18px;
  @media screen and (max-width: 800px) {
    font-size: 16px;
  }
`;

export const SectionTitle = styled.h4`
  font-size: 20px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;

  align-items: baseline;
`;

export const WidgetInput = styled.input<{ withError?: boolean }>`
  margin-top: 10px;
  background-color: ${lightLine};
  border: 2px solid ${({ withError }) => (withError ? red500 : 'transparent')};
  border-radius: 10px;
  padding: 10px;
  width: 100%;
  font-size: 15px;
  font-family: Montreal;
  &:hover,
  &:focus {
    background-color: #e5f3ff;
  }
  &:focus {
    outline: none;
    border-color: ${blue700};
  }
`;

export const OrLine = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  font-family: Architekt;
  color: ${gray700};
  margin: 20px 0;
  font-size: 14px;
  &:before,
  &:after {
    content: '';
    display: block;
    border-top: 1px solid currentColor;
    width: calc(50% - 40px);
    position: absolute;
  }
  &:before {
    left: 0;
  }
  &:after {
    right: 0;
  }
`;

const FileInputWrapper = styled.div`
  position: relative;
  border-radius: 10px;
  padding: 30px;
  margin-top: 20px;
  background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='10' ry='10' stroke='rgba(0,0,0,0.3)' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: ${lightLine};
  text-align: center;
  overflow: hidden;
  transition:
    background-image 0.2s ease,
    background-color 0.2s ease;
  &:hover {
    background-color: #e5f3ff;
    background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='10' ry='10' stroke='%23455eff' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
  }
`;

const FileInputIcon = styled.div`
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: ${yellow};
  color: ${standardGrey};
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
`;

export const LinkLike = styled.span`
  color: ${newBlue};
  cursor: pointer;
  text-decoration: underline;
`;

const FileTypes = styled.p`
  margin: 0;
  margin-top: 5px;
  padding: 0;
  font-size: 14px;
  color: ${gray700};
  font-family: Architekt;
`;

const HiddenFileInput = styled.input`
  position: absolute;
  top: 0;
  left: 0;
  transform: scale(10000);
  z-index: 2;
  opacity: 0;
  cursor: pointer;
`;

const Buttons = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
  @media screen and (max-width: 768px) {
    flex-direction: column;
    align-items: center;
  }
`;

const FileInput = ({
  children,
  ...otherProps
}: { children?: React.ReactNode[] | React.ReactNode } & DetailedHTMLProps<
  HTMLAttributes<HTMLInputElement>,
  HTMLInputElement
>) => {
  return (
    <FileInputWrapper>
      <HiddenFileInput type="file" accept="audio/*" {...otherProps} />
      {children}
    </FileInputWrapper>
  );
};

export const LearnMoreButton = styled(BracketButton)`
  font-size: 15px;
`;

export const StartButton = styled(StandardButton)<{ emphasized: boolean }>`
  border-radius: 0;
  background-color: ${({ emphasized }) => (emphasized ? yellow : '')};
  font-size: 15px;
  padding: 10px 20px;
  white-space: nowrap;
  &:hover:not(:disabled) {
    background-color: ${({ emphasized }) => (emphasized ? yellow : '')};
    opacity: ${({ emphasized }) => (emphasized ? 0.8 : undefined)};
  }
  &:disabled {
    opacity: 1;
    background-color: #e6e6e6;
    color: ${standardGrey};
  }
`;

export const UnderMessage = styled.div`
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  font-weight: 500;
  margin-top: 10px;
  font-size: 15px;
  text-align: center;
  color: black;
`;

export const Suffix = styled.span`
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 0;
  margin-left: 20px;
`;

export const LegalText = styled.p`
  font-size: 12px;
  padding-right: 20px;
  color: ${gray700};
`;

const DesktopOnly = styled.div`
  display: contents;
  @media screen and (max-width: 768px) {
    display: none;
  }
`;

const MobileOnly = styled.div`
  display: none;
  @media screen and (max-width: 768px) {
    display: contents;
  }
`;

const QuickstartWidget = ({
  setSourceUrl,
  sourceUrl,
  setFile,
  onSubmit,
  onStartFromScratch,
  onLearnMore,
  widgetHeading,
  widgetDescription,
  startFromScratchOptionShown = true,
}: {
  setSourceUrl: (url: string) => void;
  sourceUrl: string;
  setFile: (file: File | null) => void;
  onSubmit: () => void;
  onStartFromScratch: () => void;
  onLearnMore: () => void;
  widgetHeading: string;
  widgetDescription?: string;
  startFromScratchOptionShown?: boolean;
}) => {
  const handleInputChange = useCallback((e: FormEvent<HTMLInputElement>) => {
    const file = (e.target as HTMLInputElement)?.files?.[0];
    if (file) {
      setFile(file);
    }
  }, []);

  const hasFocusedRef = useRef(false);

  const mainInputRef = useCallback((node: HTMLInputElement | null) => {
    if (node && !hasFocusedRef.current) {
      hasFocusedRef.current = true;
      node.focus();
    }
  }, []);

  return (
    <>
      <H1>{widgetHeading}</H1>
      <Paragraph>
        {widgetDescription || (
          <>
            Create, edit, and remix with the most powerful pro-audio workstation on the internet. <br />
            <br />
            WavTool runs in your browser. No installation is required.
          </>
        )}
      </Paragraph>
      <DesktopOnly>
        <SectionTitle style={{ marginTop: 20 }}>
          Import a song to begin.
          {startFromScratchOptionShown && (
            <Suffix className="desktop-only">
              (or <LinkLike onClick={onStartFromScratch}>start empty project</LinkLike>)
            </Suffix>
          )}
        </SectionTitle>
        <FileInput onChange={handleInputChange}>
          <FileInputIcon>
            <img {...UploadIcon} />
          </FileInputIcon>
          <SectionTitle>
            Drag and Drop or&nbsp;<LinkLike>Choose a File</LinkLike>
          </SectionTitle>
          <FileTypes>.mp3 .wav .flac .ogg .m4a</FileTypes>
        </FileInput>
        <OrLine>Or</OrLine>
        <WidgetInput
          ref={mainInputRef}
          autoFocus
          placeholder="Enter a shareable URL from Suno, Udio, Dropbox, etc"
          onChange={(e) => setSourceUrl(e.currentTarget.value)}
          onKeyDown={(e) => e.key === 'Enter' && onSubmit()}
          value={sourceUrl}
        />
        <Buttons>
          <LegalText>
            By using this service, you affirm that you possess the legal rights to the source content and agree to
            comply with all applicable laws.
          </LegalText>
          <Tooltip message={'Enter a URL first'} immediate enabled={!sourceUrl}>
            <StartButton style={sourceUrl ? {} : { cursor: 'help' }} emphasized onClick={() => onSubmit()}>
              Import URL
            </StartButton>
          </Tooltip>
        </Buttons>
      </DesktopOnly>
      <MobileOnly>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: -10 }}>
          <LearnMoreButton onClick={onLearnMore}>Learn More</LearnMoreButton>
        </div>
      </MobileOnly>
    </>
  );
};

export default QuickstartWidget;
