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

import { CheckIcon, ChevronDownIcon, ChevronUpIcon, CopyIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { getClipDisplayTags, getClipFullTagsString } from '@/utils/clip';

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

const TagsContainer = styled.div`
  position: relative;
  overflow: visible;
`;

const PromptTags = styled.div`
  line-height: 1.3;
  color: var(--color-foreground-tertiary);
  text-align: left;
  white-space: pre-wrap;
  padding-right: 24px;
`;

const CopyIconButton = styled.button`
  position: absolute;
  top: -2px;
  right: 0;
  padding: 2px;
  border: none;
  background: none;
  cursor: pointer;
  color: var(--color-foreground-tertiary);

  &:hover {
    color: var(--color-foreground-secondary);
  }
`;

const CopyButton = ({ text, clipId }: { text: string; clipId: string }) => {
  const [showCheckmark, setShowCheckmark] = useState(false);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(text);
      logWebUserEvent({
        actionName: 'FocusedObjectPanelCopyStylesClicked',
        context: {
          clipId,
          styles: text,
        },
      });
      setShowCheckmark(true);
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      timeoutRef.current = setTimeout(() => setShowCheckmark(false), 2000);
    } catch (err) {
      console.error('Failed to copy to clipboard:', err);
    }
  };

  return (
    <CopyIconButton
      onClick={copyToClipboard}
      title='Copy styles to clipboard'
      aria-label='Copy styles to clipboard'
    >
      {showCheckmark ? (
        <CheckIcon className='h-4 w-4' />
      ) : (
        <CopyIcon className='h-4 w-4' />
      )}
    </CopyIconButton>
  );
};

const ControlLine = styled.div`
  margin-top: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  & + & {
    margin-top: 0;
  }
`;

const ControlKey = styled.span`
  color: white;
`;

const ControlValue = styled.span`
  color: var(--color-foreground-tertiary);
`;

const Bullet = styled.span`
  color: var(--color-foreground-tertiary);
  margin: 0 4px;
  &:before {
    content: '•';
  }
`;

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

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

  const expandedTags = getClipFullTagsString(clip);
  const collapsedTags = getClipDisplayTags(clip);
  const tags = expanded ? expandedTags : collapsedTags;
  const controls = {
    Weirdness: clip.metadata.control_sliders?.weirdness_constraint,
    'Style Influence': clip.metadata.control_sliders?.style_weight,
    'Audio Influence': clip.metadata.control_sliders?.audio_weight,
  };
  const controlEntries = Object.entries(controls).filter(
    ([, value]) => value !== undefined && value !== null
  );

  const remasterStrength = clip.metadata?.variation_category;

  return (
    <Subsection>
      <TagsContainer>
        <PromptTags>
          {tags || <span className='italic'>[no styles]</span>}
        </PromptTags>
        {tags && <CopyButton text={tags} clipId={clip.id} />}
      </TagsContainer>
      {controlEntries.length === 0 ? null : expanded ? (
        controlEntries.map(([key, value]) => (
          <ControlLine key={key}>
            <ControlKey>{key}</ControlKey>{' '}
            <ControlValue>{(value! * 100).toFixed(0)}%</ControlValue>
          </ControlLine>
        ))
      ) : (
        <ControlLine>
          {controlEntries.map(([key, value], index) => (
            <Fragment key={key}>
              {index > 0 && <Bullet />}
              <ControlKey>{key}</ControlKey>{' '}
              <ControlValue>{(value! * 100).toFixed(0)}%</ControlValue>
            </Fragment>
          ))}
        </ControlLine>
      )}
      {remasterStrength && (
        <ControlLine>
          <ControlKey>Remaster strength</ControlKey>{' '}
          <ControlValue>{remasterStrength}</ControlValue>
        </ControlLine>
      )}
      {(collapsedTags !== expandedTags ||
        controlEntries.length > 0 ||
        remasterStrength) && (
        <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>
  );
};
