import { useRef, useState } from 'react';
import { Controller, type FieldValues, useFormContext } from 'react-hook-form';

import { type EmojiClickData } from 'emoji-picker-react/dist/types/exposedTypes';
import { useModal } from '@material-hu/hooks/useModal';
import { IconChevronRight } from '@material-hu/icons/tabler';
import ClickAwayListener from '@material-hu/mui/ClickAwayListener';
import Divider from '@material-hu/mui/Divider';
import FormControl, {
  type FormControlProps,
} from '@material-hu/mui/FormControl';
import Grow from '@material-hu/mui/Grow';
import IconButton from '@material-hu/mui/IconButton';
import Paper from '@material-hu/mui/Paper';
import Popper from '@material-hu/mui/Popper';
import Stack from '@material-hu/mui/Stack';
import Tab from '@material-hu/mui/Tab';
import Tabs from '@material-hu/mui/Tabs';

import CroppingModal from '@material-hu/components/composed-components/CroppingModal';

import { usePublicIcons } from 'src/hooks/usePublicIcons';
import { type Icon, IconTypes } from 'src/types/icons';
import { createLocalUrl } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormImageMenuIcon from 'src/components/FormInputs/FormImageMenuIcon';

import Picker from '../dashboard/reactions/Picker';

import FormImageSelect from './FormImageSelect';

const RECOMMENDED_WIDTH = 1000;
const RECOMMENDED_HEIGHT = 1000;

type Props = FormControlProps & {
  name: string;
  width?: number;
  selectorHandler?: (icon: { value: string; type: IconTypes }) => void;
  defaultIcon?: Icon;
  disabled?: boolean;
  withArrow?: boolean;
};

/**
 * @deprecated This component does not implement Hugo's design system.
 */
function FormImageMenu({
  name,
  width = 514,
  selectorHandler,
  defaultIcon,
  disabled = false,
  withArrow = true,
  ...formControlProps
}: Props) {
  const { control, setValue } = useFormContext();
  const { t } = useLokaliseTranslation('web_only');
  const [currentTab, setCurrentTab] = useState(0);
  const [open, setOpen] = useState(false);

  const anchorRef = useRef<HTMLButtonElement>(null);

  const { icons } = usePublicIcons();

  const handleToggle = () => {
    setOpen(prevOpen => !prevOpen);
  };

  const handleClose = (event: Event | React.SyntheticEvent) => {
    if (
      event.target instanceof Node &&
      anchorRef.current?.contains(event.target)
    ) {
      return;
    }
    setOpen(false);
  };

  const onEmojiClick = (emojiObject: EmojiClickData) => {
    setValue(name, { value: emojiObject.emoji, type: IconTypes.EMOJI });
    if (selectorHandler)
      selectorHandler({ value: emojiObject.emoji, type: IconTypes.EMOJI });
    setOpen(false);
  };

  const {
    modal: croppingModal,
    showModal: showCroppingModal,
    closeModal,
  } = useModal(
    CroppingModal,
    { fullWidth: true, maxWidth: 'md' },
    {
      cancelLabel: t('general:cancel'),
      saveLabel: t('general:save'),
      onSave: file => {
        const src = createLocalUrl(file);
        setValue(name, { value: src, type: IconTypes.IMAGE, file });
      },
      onClose: () => closeModal(),
      recommendedWidth: RECOMMENDED_WIDTH,
      recommendedHeight: RECOMMENDED_HEIGHT,
      title: t('form_inputs.crop_icon'),
    },
  );

  const formImageSelect = (
    <FormImageSelect
      name={name}
      options={icons}
      upload={file => showCroppingModal({ file })}
      closePopup={handleClose}
      selectorHandler={icon => {
        selectorHandler?.(icon);
      }}
    />
  );

  const emojis = (
    <Picker
      height={270}
      onEmojiClick={onEmojiClick}
    />
  );

  const tabs = [
    { label: t('form_inputs.icons'), component: formImageSelect },
    { label: t('form_inputs.emojis'), component: emojis },
  ];

  const { component } = tabs[currentTab];

  const renderImageIcon = (field: FieldValues) => (
    <FormImageMenuIcon icon={!defaultIcon ? field.value : defaultIcon} />
  );

  return (
    <FormControl
      {...formControlProps}
      sx={{
        display: 'block',
        ...formControlProps?.sx,
      }}
    >
      {croppingModal}
      <Controller
        control={control}
        name={name}
        render={({ field }) => (
          <Stack
            sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}
          >
            {withArrow ? (
              <Stack
                sx={{
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 2,
                }}
              >
                {renderImageIcon(field)}
                <IconButton
                  disabled={disabled}
                  onClick={handleToggle}
                  ref={anchorRef}
                >
                  <IconChevronRight size={24} />
                </IconButton>
              </Stack>
            ) : (
              <IconButton
                disabled={disabled}
                onClick={handleToggle}
                ref={anchorRef}
              >
                {renderImageIcon(field)}
              </IconButton>
            )}
            <ClickAwayListener onClickAway={handleClose}>
              <Popper
                open={open}
                anchorEl={anchorRef.current}
                transition
                placement="bottom-start"
                sx={{ zIndex: 10000 }}
              >
                {({ TransitionProps }) => (
                  <Grow
                    {...TransitionProps}
                    style={{
                      transformOrigin: 'top left',
                    }}
                  >
                    <Paper
                      sx={{
                        width,
                        '& .MuiFormGroup-root': {
                          width: '100%',
                          p: 2,
                        },
                      }}
                    >
                      <Tabs
                        value={currentTab}
                        onChange={(_, val) => {
                          setCurrentTab(val);
                        }}
                        variant="scrollable"
                        sx={{
                          px: 2,
                          pt: 2,
                          '& .MuiTabs-flexContainer': {
                            gap: 0.5,
                          },
                          '& .MuiTab-root': {
                            textTransform: 'none',
                            borderRadius: theme => theme.shape.borderRadiusM,
                          },
                          '& .Mui-selected': {
                            backgroundColor: theme =>
                              theme.palette.new.background.layout.default,
                          },
                        }}
                      >
                        {tabs.map(tab => (
                          <Tab
                            sx={{
                              minWidth: 'fit-content',
                            }}
                            key={tab.label}
                            label={tab.label}
                            disableRipple
                          />
                        ))}
                      </Tabs>
                      <Divider sx={{ mx: 2 }} />
                      {component}
                    </Paper>
                  </Grow>
                )}
              </Popper>
            </ClickAwayListener>
          </Stack>
        )}
      />
    </FormControl>
  );
}

export default FormImageMenu;
