import { useState, useEffect, useRef } from 'react';
import { MenuItem, Select, SelectChangeEvent, ListSubheader, TextField } from '@mui/material';
import { useDebounce, useMemoizedFn } from 'ahooks';
import { KeyboardArrowDown as KeyboardArrowDownIcon } from '@mui/icons-material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { translate } from '@arcblock/ux/lib/Locale/util';
import Empty from '@arcblock/ux/lib/Empty';
import { getTimezones } from './utils';
import { translations } from '../../libs/locales';

const timezones = getTimezones();

interface TimezoneSelectProps {
  value: string;
  onChange: (value: string) => void;
  disabled?: boolean;
  mode?: 'drawer' | 'self';
}

export function TimezoneSelect({ value, onChange, disabled = false, mode = 'self' }: TimezoneSelectProps) {
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const [timezoneData, setTimezoneData] = useState(timezones);
  const [searchText, setSearchText] = useState('');
  const debouncedValue = useDebounce(searchText, { wait: 500 });
  const inputRef = useRef<HTMLInputElement>(null);

  const searchTimezones = useMemoizedFn((v: string) =>
    v ? timezones.filter((tz) => tz.value.toLowerCase().includes(v.toLowerCase())) : timezones
  );

  useEffect(() => {
    const data = searchTimezones(debouncedValue);
    setTimezoneData(data ?? timezones);
    // 数据更新后重新聚焦到输入框
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
  }, [debouncedValue, searchTimezones]);

  return (
    <Select
      className={`timezone-select ${disabled ? 'disabled' : ''}`}
      value={value}
      onChange={(e: SelectChangeEvent) => onChange(e.target.value)}
      disabled={disabled}
      displayEmpty
      variant="outlined"
      // @ts-expect-error
      placeholder={t('profile.timezone')}
      // eslint-disable-next-line react/no-unstable-nested-components
      IconComponent={(props) => (
        <KeyboardArrowDownIcon
          {...props}
          sx={{ fontSize: 18, color: (theme) => `${theme.palette.text.secondary} !important` }}
        />
      )}
      MenuProps={{
        autoFocus: false,
        PaperProps: {
          style: {
            maxHeight: '400px',
          },
        },
        style: {
          zIndex: mode === 'drawer' ? 9999 : 1300,
        },
      }}
      sx={{
        width: '100%',
        '&:hover': {
          'fieldset.MuiOutlinedInput-notchedOutline': {
            borderColor: 'divider',
          },
        },
        'fieldset.MuiOutlinedInput-notchedOutline': {
          borderColor: 'divider',
        },
      }}>
      <ListSubheader>
        <TextField
          inputRef={inputRef}
          autoFocus
          value={searchText}
          placeholder={t('profile.timezone')}
          variant="outlined"
          size="small"
          fullWidth
          onChange={(event) => setSearchText(event.target.value)}
          onClick={(e) => e.stopPropagation()}
          onKeyDown={(e) => e.stopPropagation()}
          sx={{
            marginTop: '8px',
            '& .MuiOutlinedInput-root': {
              '& fieldset': {
                borderColor: 'divider',
                borderWidth: '1px',
              },
              '&:hover fieldset': {
                borderColor: 'divider',
              },
              '&.Mui-focused fieldset': {
                borderColor: 'divider',
              },
            },
          }}
        />
      </ListSubheader>
      {timezoneData.map((tz) => (
        <MenuItem key={tz.value} value={tz.value}>
          {tz.label}
        </MenuItem>
      ))}
      {timezoneData.length > 0 ? null : <Empty>{t('emptyContent')}</Empty>}
    </Select>
  );
}
