import { Box, ButtonBase, Stack, Typography, useTheme } from '@mui/material';
import { type IconInterface, IconType } from '@src/types/icons';
import { IconChevronDown, IconChevronUp } from '@tabler/icons-react';

import { type IconPickerButtonProps } from './types';

const defaultRenderIcon = (icon: IconInterface) => {
  if (icon.type === IconType.IMAGE) {
    return (
      <Box
        component="img"
        src={icon.value}
        alt="icon"
        sx={{ width: 24, height: 24, objectFit: 'contain' }}
      />
    );
  }

  return (
    <Typography sx={{ fontSize: 24, lineHeight: '24px', color: 'initial' }}>
      {icon.value}
    </Typography>
  );
};

const IconPickerButton = ({
  value,
  open,
  onClick,
  buttonRef,
  disabled,
  sx,
  renderIcon,
}: IconPickerButtonProps) => {
  const { shape, palette } = useTheme();

  const ChevronIcon = open ? IconChevronUp : IconChevronDown;
  const render = renderIcon ?? defaultRenderIcon;

  return (
    <ButtonBase
      ref={buttonRef}
      onClick={onClick}
      disabled={disabled}
      disableRipple
      sx={[
        {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 1,
          px: 1.5,
          height: 56,
          minWidth: 80,
          borderRadius: `${shape.borderRadius}px`,
          borderColor: open
            ? palette.new.border.neutral.brand
            : palette.new.border.neutral.default,
          borderWidth: '1px',
          borderStyle: 'solid',
          backgroundColor: palette.new.background.elements.default,
          transition: 'border-color 0.25s ease',
          '&:hover': {
            borderColor: palette.new.border.neutral.brand,
          },
          '&:focus-visible': {
            borderColor: palette.new.border.neutral.brand,
          },
        },
        ...(Array.isArray(sx) ? sx : [sx]),
      ]}
    >
      <Stack sx={{ alignItems: 'center', justifyContent: 'center' }}>
        {value && render(value)}
      </Stack>
      <ChevronIcon size={20} />
    </ButtonBase>
  );
};

export default IconPickerButton;
