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

import ExpandableWrapper from '@/app/(root)/create/createV2/componentsQ3/ExpandableWrapper';
import { ChevronDownIcon, ChevronUpIcon } from '@/icons';

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '../button/Button';
import {
  ClipContextProvider,
  useClipContext,
  useNullableClipContext,
} from '../clipBrowser/ClipContext';
import { Subsection } from './common';

const SectionTitle = styled.div`
  font-size: 12px;
  line-height: 16px;
  color: var(--color-foreground-tertiary);
  text-align: left;
  margin-bottom: 4px;
`;

const LyricsDisplay = styled.div<{ oneLine?: boolean }>`
  line-height: 1.3;
  color: white;
  text-align: left;
  white-space: pre-wrap;
  font-size: 14px;
  ${({ oneLine }) =>
    oneLine &&
    'white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'}
`;

export default function LyricsSubsection() {
  const clip = useNullableClipContext();
  if (!clip) return null;
  return (
    <ClipContextProvider clip={clip}>
      <LyricsSubsectionContents />
    </ClipContextProvider>
  );
}

const LyricsSubsectionContents = function LyricsSubsectionContents() {
  const clip = useClipContext();
  const [expanded, setExpanded] = useState(false);

  const lyrics = clip.metadata.prompt?.trim() || '';
  const collapsedLyrics = useMemo(
    () => lyrics?.split('\n').join(' / ') || '',
    [lyrics]
  );

  if (collapsedLyrics === lyrics) {
    return (
      <Subsection>
        {lyrics && <SectionTitle>Lyrics</SectionTitle>}
        <LyricsDisplay>
          {lyrics || (
            <span className='text-[12px] text-foreground-tertiary italic'>
              [no lyrics]
            </span>
          )}
        </LyricsDisplay>
      </Subsection>
    );
  }

  return (
    <Subsection className='relative'>
      <SectionTitle>Lyrics</SectionTitle>
      <LyricsDisplay
        oneLine
        className={`pointer-events-none absolute top-9 right-4 left-4 z-100 transition-opacity duration-300 ${
          expanded ? 'opacity-0' : 'opacity-100'
        }`}
      >
        {collapsedLyrics}
      </LyricsDisplay>
      <ExpandableWrapper expanded={expanded} collapsible className='mb-2'>
        <LyricsDisplay>{lyrics}</LyricsDisplay>
      </ExpandableWrapper>
      {collapsedLyrics !== lyrics && (
        <Button
          variant={ButtonVariant.Tertiary}
          shape={ButtonShape.Rectangle}
          size={ButtonSize.Mini}
          className='mt-3 -mb-2 w-full border-t border-white/10 py-2 text-[12px]'
          onClick={() => setExpanded(!expanded)}
        >
          {expanded ? 'Show Less' : 'Show More'}
          {expanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
        </Button>
      )}
    </Subsection>
  );
};
