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

import Button, { ButtonShape, ButtonVariant } from '@/components/button/Button';
import { Tooltip } from '@/components/tooltip/Tooltip';
import { InfoIcon } from '@/icons';

export const InputWrapper = styled.div<{ textareaOpen: boolean }>`
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 0 16px;
  background-color: var(--color-background-tertiary);
  border-radius: 27px;
  display: flex;
  align-items: center;
  justify-content: stretch;
  gap: 4px;
  position: relative;
  height: 40px;
  z-index: ${({ textareaOpen }) => (textareaOpen ? 2 : 1)};
  transition: background-color 0.1s ease-in-out;
  .sub-lg & {
    cursor: pointer;
    &:hover {
      background-color: var(--color-background-glass-thick);
    }
    svg * {
      fill: var(--color-foreground-primary);
    }
  }
`;

export const TextInput = styled.input<{ doubleWidth?: boolean }>`
  height: 40px;
  background: transparent;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  border: none;
  outline: none;
  font-size: 14px;
  padding: 0 4px;
  color: var(--color-foreground-primary);
  flex-shrink: 1;
  min-width: ${({ doubleWidth }) => (doubleWidth ? '380px' : '162px')};
  .sub-lg & {
    min-width: ${({ doubleWidth }) => (doubleWidth ? '162px' : '0')};
    display: ${({ doubleWidth }) => (doubleWidth ? 'block' : 'none')};
  }
`;

export const Textarea = styled.textarea`
  padding: 8px 0;
  width: 100%;
  resize: none;
  overflow-y: scroll;
  flex-grow: 1;
  &:focus {
    outline: none;
  }
`;

const ExpandedHeader = styled.div`
  flex-grow: 0;
  display: flex;
  gap: 4px;
  align-items: center;

  svg * {
    fill: var(--color-foreground-primary);
  }
`;

const ExpandedFooter = styled.div`
  display: flex;
  gap: 4px;
  align-items: center;
  justify-content: space-between;
`;

const Title = styled.h2``;

const ExpandedInterface = styled.div`
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 8px;
  background-color: var(--color-background-tertiary);
  border: 1px solid var(--color-border-secondary);
  padding: 8px;
  width: 320px;
  pointer-events: auto;
  display: flex;
  flex-direction: column;
  justify-content: stretch;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
`;

const CharCount = styled.div`
  font-size: 14px;
  color: var(--color-foreground-inactive);
  padding: 0 8px;
`;

const ExpandingInput = ({
  doubleWidth,
  icon,
  value,
  setValue,
  tooltipLabel,
  charLimit,
  placeholder,
  textareaRows,
}: {
  doubleWidth?: boolean;
  icon: React.ReactNode;
  value: string;
  setValue: (value: string) => void;
  tooltipLabel?: React.ReactNode;
  charLimit?: number;
  placeholder?: string;
  textareaRows: number;
}) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const [textareaOpen, setTextareaOpen] = useState(false);

  const maxLength = doubleWidth ? 50 : 25;
  const shouldExpand = value.length > maxLength || value.includes('\n');

  useEffect(() => {
    if (shouldExpand && document.activeElement === inputRef.current) {
      setTextareaOpen(true);
    }
  }, [shouldExpand]);

  return (
    <InputWrapper
      textareaOpen={textareaOpen}
      onClick={() => {
        if (!inputRef.current?.checkVisibility()) {
          setTextareaOpen(true);
        }
      }}
    >
      {icon}
      <TextInput
        onMouseDown={(e) => {
          if (shouldExpand) {
            setTextareaOpen(true);
            e.preventDefault();
          }
        }}
        ref={inputRef}
        doubleWidth={doubleWidth}
        placeholder={placeholder}
        onFocus={(e) => {
          e.target.select();
          e.target.selectionStart = value.length;
          e.target.selectionEnd = value.length;
        }}
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
        onPaste={(e) => {
          const pastedText = e.clipboardData.getData('text');
          if (pastedText.includes('\n')) {
            e.preventDefault();
            setValue(pastedText);
            setTextareaOpen(true);
          }
        }}
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            setTextareaOpen(true);
          } else if (e.key === 'Escape') {
            const target = e.currentTarget;
            setTimeout(() => target.blur());
          }
        }}
        maxLength={charLimit}
      />
      {tooltipLabel && (
        <Tooltip label={tooltipLabel}>
          <InfoIcon />
        </Tooltip>
      )}
      {textareaOpen && (
        <ExpandedInterface>
          <ExpandedHeader>
            {icon}
            <Title>{placeholder}</Title>
          </ExpandedHeader>
          <Textarea
            rows={textareaRows}
            autoFocus
            onFocus={(e) => {
              e.target.select();
              e.target.selectionStart = value.length;
              e.target.selectionEnd = value.length;
            }}
            onBlur={() => {
              setTextareaOpen(false);
            }}
            onKeyDown={(e) => {
              if (e.key === 'Escape') {
                const target = e.currentTarget;
                setTimeout(() => target.blur());
              }
            }}
            value={value}
            onChange={(e) => setValue(e.currentTarget.value)}
          />
          <ExpandedFooter>
            <CharCount>
              {value.length}/{charLimit}
            </CharCount>
            <Button
              variant={ButtonVariant.Primary}
              shape={ButtonShape.Pill}
              onClick={() => setTextareaOpen(false)}
            >
              Done
            </Button>
          </ExpandedFooter>
        </ExpandedInterface>
      )}
    </InputWrapper>
  );
};

export default ExpandingInput;
