import { type KeyboardEvent, useEffect, useRef, useState } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import EditOutlined from '@material-hu/icons/material/EditOutlined';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { useLokaliseTranslation } from 'src/utils/i18n';

import FormImageMenu from './FormImageMenu';
import FormTextField from './FormTextField';

export type FormTitleProps = {
  name: string;
  iconName: string;
};

/**
 * @deprecated This component does not implement Hugo's design system.
 */
export const FormTitle = ({ name, iconName }: FormTitleProps) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('general');
  const { setValue } = useFormContext();

  const value = useWatch({ name });

  const [previousValue, setPreviousValue] = useState(value);
  const [editing, setEditing] = useState(false);

  const inputRef = useRef(null);

  useEffect(() => {
    if (editing) inputRef.current?.focus();
  }, [editing]);

  const saveTitle = () => {
    const actualValue = value || previousValue;
    setValue(name, actualValue);
    setEditing(false);
  };

  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key !== 'Enter') return;
    event.preventDefault();
    saveTitle();
  };

  const handleBlur = () => saveTitle();

  const handleEdit = () => {
    setEditing(true);
    setPreviousValue(value);
  };

  const FormIcon = () => (
    <FormImageMenu
      name={iconName}
      width={400}
      withArrow={false}
      sx={{
        '& .MuiIconButton-root': {
          p: 0.5,
          div: {
            width: '24px',
            height: '24px',
            img: {
              height: 'auto',
              width: '24px',
            },
            '& .MuiTypography-root': {
              fontSize: '24px',
              lineHeight: '24px',
            },
          },
        },
      }}
    />
  );

  return (
    <Stack
      sx={{
        gap: 1,
        width: '100%',
      }}
    >
      {editing && (
        <Stack
          sx={{
            flexDirection: 'row',
            gap: 1.5,
          }}
        >
          <FormIcon />
          <FormTextField
            name={name}
            inputRef={inputRef}
            onBlur={handleBlur}
            onKeyDown={handleKeyDown}
            variant="standard"
            fullWidth
            max={255}
            sx={{
              m: 0,
              input: {
                ...theme.typography.h5,
                p: 0,
                height: 'unset',
              },
              '& .MuiInput-root': {
                '&::before': { display: 'none' },
                '&::after': { display: 'none' },
              },
            }}
          />
        </Stack>
      )}
      {!editing && (
        <Stack
          sx={{
            flexDirection: 'row',
            gap: 1.5,
          }}
        >
          <FormIcon />
          <Typography
            variant="h5"
            sx={{
              display: '-webkit-box',
              overflow: 'hidden',
              WebkitBoxOrient: 'vertical',
              WebkitLineClamp: 3,
              textOverflow: 'ellipsis',
              wordWrap: 'break-word',
              flex: 1,
            }}
          >
            {value}
          </Typography>
          <IconButton
            onClick={handleEdit}
            aria-label={t('general:edit')}
            size="small"
            sx={{
              svg: {
                width: '24px',
                height: '24px',
              },
            }}
          >
            <EditOutlined />
          </IconButton>
        </Stack>
      )}
      <Divider
        sx={{
          borderColor: editing
            ? theme.palette.graphics?.neutralGraphic
            : undefined,
        }}
      />
    </Stack>
  );
};

export default FormTitle;
