import { KeyboardArrowDown } from '@mui/icons-material'
import {
  Autocomplete,
  BoxProps,
  Popper,
  TextField,
  alpha,
  styled,
} from '@mui/material'

export const StyledAutocomplete = styled(Autocomplete)(({ theme }) => ({
  '& .MuiAutocomplete-tag': {
    border: '1px solid #D1D1D1',
    background: '#F8F8F8',
    borderRadius: '5px',
    height: '38px',
    '& .MuiSvgIcon-root': {
      fontSize: '15px',
      marginLeft: '5px',
      fontWeight: 700,
      color: theme.palette.secondary.main,
      '&:hover': {
        color: alpha(theme.palette.secondary.main, 0.8),
      },
    },
  },
}))

export const StyledPopper = styled(Popper)(({ theme }) => ({
  minWidth: 'fit-content',
  '& .MuiPaper-root': {
    borderRadius: '10px',
    borderTopRightRadius: 0,
    borderTopLeftRadius: 0,
    boxShadow: '0px 4px 16px #0000000F',
    marginTop: '1px',
    '& .MuiAutocomplete-listbox': {
      minWidth: '240px',
      padding: '0px',
      '& .MuiAutocomplete-option': {
        padding: '15px',
        borderBottom: '1px solid rgba(18, 18, 18, 0.1)',
      },
    },
    '&::-webkit-scrollbar': {
      width: '0.5em',
      height: '0.5em',
    },

    '&::-webkit-scrollbar-thumb': {
      backgroundColor: 'rgba(0, 0, 0, 0.15)',
      borderRadius: '3px',

      '&:hover': {
        background: 'rgba(0, 0, 0, 0.2)',
      },
    },
  },
}))

type Props = {
  options: Array<{ label: string; value: any }>
  value: { label: string; value: any }
  onChange?: (value: any) => void
  containerProps?: BoxProps
}
export const SearchSingleSelect = ({ options, value, onChange }: Props) => {
  return (
    <StyledAutocomplete
      sx={{ legend: { display: 'none' } }}
      fullWidth
      multiple={false}
      getOptionLabel={(option: any) => option?.label || ''}
      options={options || []}
      value={value}
      onChange={(e, value) => {
        onChange(value)
      }}
      isOptionEqualToValue={(option: any, value: any) =>
        option?.value === value?.value
      }
      disableCloseOnSelect
      PopperComponent={StyledPopper}
      popupIcon={<KeyboardArrowDown />}
      renderInput={(params) => {
        return (
          <TextField
            inputRef={(input) => {
              if (input && value) {
                input.style.width = `${value.label?.length * 9}px`
              }
            }}
            InputProps={{
              ...params.InputProps,
              endAdornment: <>{params.InputProps.endAdornment}</>,
            }}
            sx={{ minWidth: '220px' }}
            {...params}
          />
        )
      }}
    />
  )
}
