import { useTranslation } from 'react-i18next';

import {
  InputAdornment,
  MenuItem,
  Select,
  useFormControl,
  useTheme,
} from '@mui/material';
import { IconAlertCircle, IconChevronDown } from '@tabler/icons-react';

import { getBorderColor } from '../../utils';

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

const CustomSelect = ({
  value,
  onChange,
  inputRef,
  placeholder,
  options,
  renderOption,
  renderValue,
  allowClear,
  disabled = false,
  MenuProps,
  success = false,
  hideErrorAdornment = false,
}: CustomSelectProps) => {
  const { focused, error } = useFormControl() || {};
  const theme = useTheme();
  const { t } = useTranslation('material_hu_only');

  const label = options.find(o => o.value === value)?.label || '';

  return (
    <Select
      value={value || ''}
      onChange={e => onChange(e.target.value)}
      inputRef={inputRef}
      displayEmpty={true}
      MenuProps={MenuProps}
      renderValue={() => {
        if (!value) return placeholder;
        if (renderValue) return renderValue({ value, label });
        if (renderOption) return renderOption({ value, label });
        return label;
      }}
      IconComponent={IconChevronDown}
      endAdornment={
        error &&
        !hideErrorAdornment && (
          <InputAdornment
            position="end"
            sx={{ pr: theme.spacing(0.5) }}
          >
            <IconAlertCircle
              size={20}
              color={theme.palette.new.text.feedback.error}
            />
          </InputAdornment>
        )
      }
      sx={{
        color: !value
          ? theme.palette.new.text.neutral.lighter
          : theme.palette.new.text.neutral.default,
        '.MuiSelect-icon': {
          mr: error && !hideErrorAdornment ? theme.spacing(4) : '0',
          top: '50%',
          transform: 'translateY(-50%)',
          right: theme.spacing(2),
        },
        '& fieldset': {
          borderColor: getBorderColor(theme, focused, error, success, !!value),
          borderWidth: '1px !important',
        },
        backgroundColor: disabled
          ? theme.palette.new.background.elements.disabled
          : theme.palette.new.background.elements.default,
      }}
    >
      {allowClear && (
        <MenuItem
          key="clear"
          value=""
        >
          <em>{t('hu_inputs.select')}</em>
        </MenuItem>
      )}
      {options.map(option => (
        <MenuItem
          key={option.value}
          value={option.value}
        >
          {renderOption ? renderOption(option) : option.label}
        </MenuItem>
      ))}
    </Select>
  );
};

export type { CustomSelectProps };

export default CustomSelect;
