// import PropTypes from 'prop-types';
import {
  Box,
  CircularProgress,
  IconButton,
  InputAdornment,
  MenuItem,
  Select,
  TextField,
  Typography,
} from '@mui/material';
import { useCreation, useMemoizedFn, useReactive } from 'ahooks';
import noop from 'lodash/noop';
import isUrl from 'is-url';
import { Icon } from '@iconify/react';
import CloseRoundedIcon from '@iconify-icons/material-symbols/close-rounded';
import CheckIcon from '@iconify-icons/material-symbols/check';
import SendRoundedIcon from '@iconify-icons/material-symbols/send-rounded';
import EditSquareOutlineRoundedIcon from '@iconify-icons/material-symbols/edit-square-outline-rounded';
import DeleteOutlineRoundedIcon from '@iconify-icons/material-symbols/delete-outline-rounded';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';

import { translations } from '../libs/locales';
import { WebhookItemData, WebhookItemProps, WebhookType } from '../../@types';

export default function WebhookItem({
  onTest = noop,
  onDelete = noop,
  onSave = noop,
  onCancel = noop,
  type = 'slack',
  url = '',
  edit = false,
}: WebhookItemProps) {
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const currentState = useReactive<
    WebhookItemData & {
      edit: boolean;
      error: string;
      loading: boolean;
    }
  >({
    type: type || 'slack',
    url: url || '',
    edit: edit ?? false,
    error: '',
    loading: false,
  });

  const checkUrl = useMemoizedFn(() => {
    if (!currentState.url) {
      currentState.error = t('common.required');
      return false;
    }
    if (!isUrl(currentState.url)) {
      currentState.error = t('common.invalid');
      return false;
    }
    currentState.error = '';
    return true;
  });

  const handleClose = useMemoizedFn(() => {
    currentState.edit = false;
    currentState.url = url || '';
    currentState.type = type || 'slack';
    currentState.error = '';
    currentState.loading = false;
    onCancel();
  });

  // eslint-disable-next-line @typescript-eslint/naming-convention
  const _onTest = useMemoizedFn(async (data) => {
    currentState.loading = true;
    await onTest(data);
    currentState.loading = false;
  });

  const onSubmit = useMemoizedFn((fn: (params: WebhookItemData) => void) => {
    return () => {
      if (checkUrl()) {
        fn({
          type: currentState.type,
          url: currentState.url,
        });
      }
    };
  });

  const inputAdornment = useCreation(() => {
    if (currentState.error) {
      return (
        <Typography component="span" color="error">
          {currentState.error}
        </Typography>
      );
    }

    if (currentState.edit) {
      if (currentState.loading) {
        return <CircularProgress size={16} />;
      }

      return (
        <IconButton
          size="small"
          onClick={onSubmit(_onTest)}
          sx={{
            mr: -1,
          }}>
          <Icon icon={SendRoundedIcon} />
        </IconButton>
      );
    }
    return null;
  }, [currentState.error, currentState.edit, currentState.loading]);

  return (
    <Box
      sx={{
        display: 'flex',
        gap: 1.5,
        width: '100%',
        alignItems: {
          xs: 'flex-start',
          md: 'center',
        },
        flexDirection: {
          xs: 'column',
          md: 'row',
        },
      }}>
      <Select
        sx={{
          borderRadius: 1,
          '&.Mui-disabled': {
            backgroundColor: 'grey.50',
          },
        }}
        disabled={!currentState.edit || currentState.loading}
        size="small"
        value={currentState.type}
        onChange={(e) => {
          currentState.type = e.target.value as WebhookType;
        }}>
        <MenuItem value="api">{t('webhook.url')}</MenuItem>
        <MenuItem value="slack">{t('webhook.slack')}</MenuItem>
      </Select>
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 0.5,
          width: '100%',
        }}>
        <TextField
          sx={{
            flex: 1,
            '.MuiInputBase-root': {
              borderRadius: 1,
              '&.Mui-disabled': {
                backgroundColor: 'grey.50',
              },
            },
          }}
          disabled={!currentState.edit || currentState.loading}
          fullWidth
          size="small"
          required
          value={currentState.url}
          onChange={(e) => {
            currentState.url = e.target.value;
            checkUrl();
          }}
          error={!!currentState.error}
          slotProps={{
            input: {
              endAdornment: <InputAdornment position="end">{inputAdornment}</InputAdornment>,
            },
          }}
        />

        <Box sx={{ display: 'flex', gap: 0.5 }}>
          {currentState.edit ? (
            <>
              <IconButton
                color="success"
                onClick={onSubmit((...args) => {
                  onSave(...args);
                  currentState.edit = false;
                })}
                sx={{
                  borderRadius: 1,
                  border: '1px solid',
                  borderColor: 'grey.200',
                }}>
                <Icon icon={CheckIcon} />
              </IconButton>
              <IconButton
                color="error"
                onClick={handleClose}
                sx={{
                  borderRadius: 1,
                  border: '1px solid',
                  borderColor: 'grey.200',
                }}>
                <Icon icon={CloseRoundedIcon} />
              </IconButton>
            </>
          ) : (
            <>
              <IconButton
                onClick={() => {
                  currentState.edit = true;
                }}
                sx={{
                  borderRadius: 1,
                  border: '1px solid',
                  borderColor: 'grey.200',
                }}>
                <Icon icon={EditSquareOutlineRoundedIcon} />
              </IconButton>
              <IconButton
                color="error"
                onClick={() => {
                  onDelete({
                    type: currentState.type,
                    url: currentState.url,
                  });
                }}
                sx={{
                  borderRadius: 1,
                  border: '1px solid',
                  borderColor: 'grey.200',
                }}>
                <Icon icon={DeleteOutlineRoundedIcon} />
              </IconButton>
            </>
          )}
        </Box>
      </Box>
    </Box>
  );
}
