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

import FormCheckbox from '@design-system/Checkbox/Checkbox/form';
import Chips from '@design-system/Chip';
import FormSearch from '@design-system/Inputs/Search/form';
import MenuItem from '@design-system/Menu/components/MenuItem';
import Title from '@design-system/Title';
import { useTheme } from '@mui/material';
import ClickAwayListener from '@mui/material/ClickAwayListener';
import Paper from '@mui/material/Paper';
import Popper from '@mui/material/Popper';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';

import {
  type CheckboxAutocompleteOption,
  type CheckboxAutocompleteProps,
} from './types';

export const CheckboxAutocomplete = ({
  name,
  label,
  options,
  disabled = false,
  uncheckedDisabled = false,
  searchLoading = false,
  searchDisabled = false,
  searchEmpty = false,
  searchLoadingTitle,
  searchEmptyTitle,
  helperText,
}: CheckboxAutocompleteProps) => {
  const [anchorEl, setAnchorEl] = useState<HTMLDivElement | null>(null);
  const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
  const showMenu = !searchDisabled && Boolean(anchorEl);

  const { palette } = useTheme();

  type FormValues = { [name]: CheckboxAutocompleteOption[] };
  const { setValue, control } = useFormContext<FormValues>();

  const selected = useWatch({ name, control });

  useEffect(() => {
    if (searchDisabled) setAnchorEl(null);
  }, [searchDisabled]);

  const handleSearchFocus = () => {
    const container = document.querySelector(
      '#checkbox-autocomplete-search-input',
    ) as HTMLDivElement;
    const input = document.querySelector(
      '#checkbox-autocomplete-search-input .MuiInputBase-root',
    ) as HTMLDivElement;

    setAnchorEl(input);
    setContainerEl(container);
  };

  const isChecked = (option: CheckboxAutocompleteOption) => {
    if (!selected || !option) return false;
    return option.checked || selected.some(v => v.id === option.id);
  };

  const isDisabled = (option: CheckboxAutocompleteOption) => {
    if (!option) return false;
    return option.disabled || (uncheckedDisabled && !isChecked(option));
  };

  const handleDelete = (option: CheckboxAutocompleteOption) =>
    setValue(
      name,
      selected.filter(v => v.id !== option.id),
    );

  const handleAdd = (option: CheckboxAutocompleteOption) =>
    setValue(name, [...selected, { ...option, checked: true }]);

  const handleToggle = (option: CheckboxAutocompleteOption) =>
    isChecked(option) ? handleDelete(option) : handleAdd(option);

  const handleClickAway = (event: Event) => {
    if (anchorEl?.contains(event.target as Node)) return;
    setAnchorEl(null);
  };

  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (event.key === 'Escape' || event.key === 'Tab') {
      setAnchorEl(null);
    }
  };

  const isMenuOverflow = (height: number) => {
    if (!containerEl || !height) return false;

    const menuTop = containerEl.offsetHeight + containerEl.offsetTop;
    const menuBottom = menuTop + height;
    const parentEl = containerEl.offsetParent as HTMLElement;
    const parentHeight = parentEl.offsetHeight;

    return menuBottom > parentHeight;
  };

  const getMenuHeight = () => {
    const itemHeight = 75.6;
    const maxHeight = itemHeight * 5;
    const minHeight = itemHeight * 3;
    return !isMenuOverflow(maxHeight) ? maxHeight : minHeight;
  };

  return (
    <Stack
      onKeyDown={handleKeyDown}
      sx={{
        gap: 2,
        p: 2,
        borderRadius: 2,
        backgroundColor: palette.hugoBackground?.neutralBg,
      }}
    >
      <Stack id="checkbox-autocomplete-search-input">
        <FormSearch
          name="search"
          inputProps={{
            disabled: searchDisabled,
            loading: searchLoading,
            label,
            helperText,
            autoFocus: true,
            onFocus: handleSearchFocus,
          }}
        />
      </Stack>
      <Popper
        open={showMenu}
        anchorEl={anchorEl}
        modifiers={[
          {
            name: 'preventOverflow',
            enabled: true,
            options: {
              altAxis: true,
              altBoundary: true,
              padding: 8,
            },
          },
        ]}
        sx={{
          zIndex: 2000,
          width: anchorEl?.clientWidth,
          maxHeight: getMenuHeight(),
        }}
      >
        <ClickAwayListener onClickAway={handleClickAway}>
          <Paper
            sx={{
              maxHeight: getMenuHeight(),
              overflow: 'auto',
            }}
          >
            {(searchLoading || searchEmpty) && (
              <Stack sx={{ p: 2 }}>
                {searchLoading && (
                  <Title
                    variant="S"
                    title={searchLoadingTitle}
                  />
                )}
                {searchEmpty && (
                  <Title
                    variant="S"
                    title={searchEmptyTitle}
                  />
                )}
              </Stack>
            )}
            {options?.map(option => (
              <MenuItem
                key={option.id}
                onClick={() => handleToggle(option)}
                disabled={isDisabled(option)}
                sx={{
                  '&.Mui-disabled': {
                    opacity: 'unset',
                  },
                }}
              >
                <FormCheckbox
                  name={`options.${name}.${option.id}`}
                  checkBoxProps={{
                    label: option.label,
                    description: option.description,
                    checked: isChecked(option),
                    disabled: isDisabled(option),
                  }}
                />
                <Typography
                  variant="globalXS"
                  sx={{
                    alignSelf: 'flex-start',
                    ml: 'auto',
                    color: palette.textColors?.neutralTextDisabled,
                  }}
                >
                  {option.info}
                </Typography>
              </MenuItem>
            ))}
          </Paper>
        </ClickAwayListener>
      </Popper>
      <Stack
        sx={{
          flexDirection: 'row',
          flexWrap: 'wrap',
          gap: 1,
        }}
      >
        {selected.map(option => (
          <Chips
            key={option.id}
            label={option.label}
            onDelete={() => handleDelete(option)}
            disabled={disabled}
          />
        ))}
      </Stack>
    </Stack>
  );
};

export default CheckboxAutocomplete;
