import React, { type ReactElement, type ElementType, useState } from 'react';
import {
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  TextField,
  Typography,
} from '@mui/material';
import Slide from '@mui/material/Slide';
import type { TransitionProps } from '@mui/material/transitions';
import { CloseCircle } from 'iconsax-react';
import { Icon } from '@rkheftan/harmony-ui';
import { type SocialMediaDialogProps } from '@/features/profile/types/settingsType';
import { isEmail } from '@/utils/regexes/isEmail';

const MobileSlide = React.forwardRef(function MobileSlide(
  props: TransitionProps & { children: ReactElement<unknown, ElementType> },
  ref: React.Ref<unknown>,
) {
  return <Slide direction="up" ref={ref} {...props} />;
});

export default function SocialMediaDialog({
  open,
  onClose,
  t,
  emailInput,
  setEmailInput,
  fullScreen,
  verificationCode,
  setVerificationCode,
  isLoading,
  dialogStep,
  onSendCode,
  onConfirmEmail,
}: SocialMediaDialogProps) {
  const [emailError, setEmailError] = useState<string | undefined>();
  const [touched, setTouched] = useState(false);

  const validateEmail = (value: string) => {
    if (!value) {
      setEmailError(t('settingForm.thisFieldIsRequired'));
      return false;
    }
    if (!isEmail(value)) {
      setEmailError(t('settingForm.emailIsInvalid'));
      return false;
    }
    setEmailError(undefined);
    return true;
  };

  const handleSubmit: React.FormEventHandler<HTMLFormElement> = (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (isLoading) return;

    if (dialogStep === 'enterEmail') {
      setTouched(true);
      if (!validateEmail(emailInput)) return;
      onSendCode();
    } else {
      onConfirmEmail();
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullWidth
      fullScreen={fullScreen}
      maxWidth="xs"
      scroll="body"
      keepMounted
      TransitionComponent={fullScreen ? MobileSlide : undefined}
      PaperProps={{ sx: { mx: 1 } }}
    >
      <DialogTitle sx={{ p: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <IconButton onClick={onClose} disabled={isLoading}>
            <Icon Component={CloseCircle} size="large" color="primary.main" />
          </IconButton>
          <Box component="span" fontWeight="bold" fontSize={18}>
            {t('settingForm.addEmailButton')}
          </Box>
        </Box>
      </DialogTitle>

      <Box component="form" onSubmit={handleSubmit}>
        <DialogContent
          sx={{
            display: 'flex',
            flexDirection: 'column',
            gap: 2,
            px: { xs: 2, sm: 3 },
          }}
        >
          <Box>
            <Typography fontWeight="bold">
              {t('settingForm.newEmail')}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {t('settingForm.dialogHeader')}
            </Typography>
          </Box>

          <TextField
            fullWidth
            type="email"
            value={emailInput}
            onChange={(e) => {
              setEmailInput(e.target.value);
              if (touched) validateEmail(e.target.value);
            }}
            onBlur={() => {
              setTouched(true);
              validateEmail(emailInput);
            }}
            label={t('settingForm.email')}
            placeholder="abc@email.com"
            autoComplete="email"
            inputMode="email"
            sx={{ '& .MuiOutlinedInput-root': { borderRadius: 1 }, mt: 1 }}
            autoFocus={dialogStep === 'enterEmail'}
            disabled={isLoading || dialogStep === 'enterCode'}
            error={touched && !!emailError}
            helperText={touched && emailError ? emailError : ' '}
          />

          {dialogStep === 'enterCode' && (
            <TextField
              fullWidth
              type="text"
              value={verificationCode}
              onChange={(e) => setVerificationCode(e.target.value)}
              label={t('settingForm.verificationCode')}
              autoComplete="one-time-code"
              inputMode="numeric"
              sx={{ '& .MuiOutlinedInput-root': { borderRadius: 1 } }}
              autoFocus
              disabled={isLoading}
            />
          )}
        </DialogContent>

        <Box sx={{ px: 3, pb: 2 }}>
          <Button
            fullWidth
            sx={{ height: 48, textTransform: 'none', borderRadius: 1 }}
            variant="contained"
            type="submit"
            disabled={isLoading || (dialogStep === 'enterEmail' && !emailInput)}
          >
            {isLoading ? (
              <CircularProgress size={24} color="inherit" />
            ) : dialogStep === 'enterEmail' ? (
              t('settingForm.verificationCodeButton')
            ) : (
              t('settingForm.confirmAndSave')
            )}
          </Button>
        </Box>
      </Box>
    </Dialog>
  );
}
