/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import styled from '@emotion/styled';
import { truncate } from 'lodash-es';
import { useEffect, useState } from 'react';

import { EditIcon } from '@/icons';

const Wrapper = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  font-size: 16px;
  gap: 12px;
`;

const ImageWrapper = styled.div`
  width: 48px;
  height: 48px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
`;

const TitleWrapper = styled.div`
  flex-grow: 1;
  input {
    background-color: transparent;
    border: none;
    outline: none;
    color: var(--color-foreground-primary);
    padding: 0;
    border-bottom: 1px solid var(--color-border-primary);
    width: 100%;
    font-size: 16px;
  }
`;

export default function StudioObjectTitleRow({
  image,
  title,
  setTitle,
}: {
  image?: React.ReactNode;
  title: string;
  setTitle?: (name: string) => void;
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [localTitle, setLocalTitle] = useState(title);

  useEffect(() => {
    setLocalTitle(title);
  }, [title]);

  return (
    <Wrapper className={image ? '' : '-my-1'}>
      {image && <ImageWrapper>{image}</ImageWrapper>}
      <TitleWrapper>
        {isEditing && setTitle ? (
          <input
            autoFocus
            type='text'
            className='w-full grow'
            value={localTitle}
            placeholder='Enter a Name'
            onChange={(e) => setLocalTitle(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                setIsEditing(false);
                setTitle(localTitle);
              } else if (e.key === 'Escape') {
                setLocalTitle(title);
                setIsEditing(false);
              }
            }}
            onBlur={() => {
              setIsEditing(false);
              setTitle(localTitle);
            }}
          />
        ) : (
          <span
            onClick={setTitle ? () => setIsEditing(true) : undefined}
            className={setTitle ? 'group cursor-pointer hover:underline' : ''}
          >
            {truncate(localTitle, { length: 50 }) || (
              <span className='opacity-50'>[Untitled]</span>
            )}{' '}
            {setTitle && (
              <EditIcon className='-mt-1 ml-1 inline-block opacity-50 group-hover:opacity-100' />
            )}
          </span>
        )}
      </TitleWrapper>
    </Wrapper>
  );
}
