import { useEffect, useState, createElement, Suspense, useMemo } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  ListItemIcon,
  Box,
  Typography,
  IconButton,
} from '@mui/material';
import dayjs from 'dayjs';
import { Close as CloseIcon } from '@mui/icons-material';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useMemoizedFn } from 'ahooks';
import ArrowDownwardIcon from '@arcblock/icons/lib/ArrowDown';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { DurationEnum, UserMetadata } from '../../../@types';
import { StatusItem } from '../status-selector/menu-item';
import { translations } from '../../libs/locales';
import DateTimeInput from './date-picker';
import { defaultButtonStyle, primaryButtonStyle } from '../user-info/utils';

const selectStyle = {
  padding: '8px 16px',
  borderRadius: '8px',
  '&:hover': {
    'fieldset.MuiOutlinedInput-notchedOutline': {
      borderColor: 'divider',
    },
  },
  'fieldset.MuiOutlinedInput-notchedOutline': {
    borderColor: 'divider',
    borderRadius: '8px',
  },
  '.MuiSelect-select': {
    padding: '0 !important',
    display: 'flex',
    alignItems: 'center',
  },
};
interface StatusDialogProps {
  open: boolean;
  onClose: () => void;
  data: Array<StatusItem>;
  selected: UserMetadata['status'];
  onSelect: (v: UserMetadata['status']) => void;
  timezone?: string;
}

export default function StatusDialog({
  open,
  onClose,
  data,
  selected,
  onSelect,
  timezone = undefined,
}: StatusDialogProps) {
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, _data = {}) => {
    return translate(translations, key, locale, 'en', _data);
  });

  const [status, setStatus] = useState(selected?.value || '');
  const [duration, setDuration] = useState(selected?.duration || '');
  const [customDate, setCustomDate] = useState(selected?.dateRange?.[1] || '');
  const [changed, setChanged] = useState(false);

  useEffect(() => {
    setStatus(selected?.value || '');
    setDuration(selected?.duration || '');
    setCustomDate(selected?.dateRange?.[1] || '');
  }, [selected]);

  const isValid = useMemo(() => {
    return status && duration;
  }, [status, duration]);

  const selectedStatus = data.find((item) => item.id === status);

  const handleQuickSettingClick = (item: StatusItem) => {
    onSelect({
      value: item.id,
      ...(item.duration ? { duration: item.duration as DurationEnum } : {}),
    });
    onClose();
  };

  const handleSubmit = (clean = false) => {
    if (clean) {
      onSelect(undefined);
    } else {
      const current = dayjs();
      onSelect({
        value: status,
        ...(duration ? { duration: duration as DurationEnum } : {}),
        ...(duration === DurationEnum.Custom && customDate
          ? { dateRange: [current.toDate(), dayjs(customDate).toDate()] }
          : {}),
      });
    }
    onClose();
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="xs"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: '8px',
        },
      }}>
      <DialogTitle sx={{ borderBottom: '1px solid', borderColor: 'divider' }}>
        <Typography variant="body1" sx={{ fontSize: '16px !important', mb: 0 }}>
          {t('profile.setStatus')}
        </Typography>
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{
            position: 'absolute',
            right: 8,
            top: 8,
            color: (theme) => theme.palette.grey[500],
          }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        <FormControl fullWidth sx={{ mt: 2 }}>
          <InputLabel size="small" sx={{ fontSize: '14px' }}>
            {t('profile.setStatus')}
          </InputLabel>
          <Select
            value={status}
            label={t('profile.setStatus')}
            onChange={(e) => {
              setStatus(e.target.value);
              setChanged(true);
            }}
            variant="outlined"
            // eslint-disable-next-line react/no-unstable-nested-components
            IconComponent={(props) => <ArrowDownwardIcon {...props} width={20} height={20} />}
            sx={selectStyle}>
            {data.map((item) => (
              <MenuItem key={item.id} value={item.id}>
                <Suspense fallback={null}>
                  {item.icon && (
                    <ListItemIcon style={{ minWidth: '24px' }}>
                      {createElement(item.icon, {
                        style: { fontSize: '16px', width: '16px', height: '16px' },
                      })}
                    </ListItemIcon>
                  )}
                  {item.name}
                </Suspense>
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        {!status ? (
          <Box sx={{ mt: '24px' }}>
            <Typography
              variant="body2"
              sx={{
                color: 'text.secondary',
              }}>
              {t('profile.quickSettings')}
            </Typography>
            {data.map((item) => (
              <Box
                key={item.id}
                onClick={() => handleQuickSettingClick(item)}
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '4px',
                  p: '4px',
                  cursor: 'pointer',
                  borderRadius: '8px',
                  '&:hover': {
                    bgcolor: 'action.hover',
                  },
                }}>
                <Suspense fallback={null}>
                  {item.icon && (
                    <ListItemIcon style={{ minWidth: '24px' }}>
                      {createElement(item.icon, {
                        style: { fontSize: '16px', width: '16px', height: '16px' },
                      })}
                    </ListItemIcon>
                  )}
                  {item.name}
                  {item.durationName && (
                    <Typography
                      variant="body2"
                      sx={{
                        color: 'text.secondary',
                      }}>
                      - {item.durationName}
                    </Typography>
                  )}
                </Suspense>
              </Box>
            ))}
          </Box>
        ) : (
          <FormControl fullWidth sx={{ mt: '24px' }}>
            <InputLabel size="small" sx={{ fontSize: '14px' }}>
              {t('profile.removeStatusAfter')}
            </InputLabel>
            <Select
              value={duration}
              label={t('profile.removeStatusAfter')}
              onChange={(e) => {
                const { value } = e.target;
                setDuration(value);
                if (value === DurationEnum.Custom) {
                  setCustomDate(dayjs().toDate());
                }
                setChanged(true);
              }}
              variant="outlined"
              // eslint-disable-next-line react/no-unstable-nested-components
              IconComponent={(props) => <ArrowDownwardIcon {...props} width={20} height={20} />}
              sx={selectStyle}>
              {selectedStatus?.children?.map((item) => (
                <MenuItem key={item.id} value={item.id}>
                  {item.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        )}
        {duration === DurationEnum.Custom && (
          <Box sx={{ mt: '24px' }}>
            <DateTimeInput
              value={customDate as Date}
              onChange={(e) => {
                setCustomDate(e);
                setChanged(true);
              }}
              label={t('profile.selectEndTime')}
              timezone={timezone}
              error={duration === DurationEnum.Custom && !customDate}
              helperText={duration === DurationEnum.Custom && !customDate ? t('profile.pleaseSelectTime') : undefined}
            />
          </Box>
        )}
      </DialogContent>
      <DialogActions sx={{ p: '16px 24px', borderTop: '1px solid', borderColor: 'divider' }}>
        {selected?.value && !changed ? (
          <Button
            sx={{ ...defaultButtonStyle, minWidth: '54px' }}
            size="small"
            variant="outlined"
            onClick={() => handleSubmit(true)}>
            {t('profile.cleanStatus')}
          </Button>
        ) : (
          <>
            <Button size="small" variant="outlined" sx={{ ...defaultButtonStyle, minWidth: '54px' }} onClick={onClose}>
              {t('common.cancel')}
            </Button>
            <Button
              sx={{
                ...primaryButtonStyle,
                minWidth: '54px',
                '&.Mui-disabled': {
                  backgroundColor: 'rgba(0, 0, 0, 0.12)',
                },
              }}
              disabled={!isValid}
              onClick={() => handleSubmit(false)}
              size="small"
              variant="outlined">
              {t('common.confirm')}
            </Button>
          </>
        )}
      </DialogActions>
    </Dialog>
  );
}
