import React, { useEffect } from 'react';
import {
  TextField,
  Box,
  Button,
  Switch,
  FormGroup,
  Typography,
  InputAdornment,
  IconButton,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { TickCircle, Edit2 } from 'iconsax-react';
import { Icon } from '@rkheftan/harmony-ui';
import { type EmailSectionProps } from '../../types/settingForm';
import { isNumeric } from '@/utils/regexes/isNumeric';
import { sanitizeLocalNumber } from '@/utils/regexes/sanitizeNumber';

const ADORN_W = 24;
const INPUT_H = 56;

export function EmailSection(props: EmailSectionProps) {
  const {
    showEmail,
    setShowEmail,
    email,
    setEmail,
    codeSent,
    verificationCode,
    setVerificationCode,
    buttonState,
    handleSendCode,
    handleVerifyCode,
    emailVerified,
    isVerifyingCode,
    isSendingCode,
    handleEditEmail,
    errors,
    touched,
    handleBlur,
    countdown,
  } = props;

  const { t } = useTranslation('completionForm');

  const handleToggleEmail = (e: React.ChangeEvent<HTMLInputElement>) => {
    setShowEmail(e.target.checked);
  };

  const handleVerificationCodeChange = (
    e: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const normalized = sanitizeLocalNumber(e.target.value);
    if (isNumeric(normalized) && normalized.length <= 4) {
      setVerificationCode(normalized);
    }
  };

  const formatTimerValue = () => {
    const m = String(Math.floor(countdown / 60)).padStart(2, '0');
    const s = String(countdown % 60).padStart(2, '0');
    return `${m}:${s}`;
  };

  useEffect(() => {
    if (buttonState !== 'counting') {
      setVerificationCode('');
    }
  }, [buttonState, setVerificationCode]);

  const showCodeSection =
    showEmail && codeSent && !emailVerified && buttonState === 'counting';

  return (
    <>
      <FormGroup>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Switch checked={showEmail} onChange={handleToggleEmail} />
          <Typography
            sx={{ color: showEmail ? 'primary.main' : 'text.primary' }}
          >
            {t('completion.determineEmail')}
          </Typography>
        </Box>
      </FormGroup>

      {showEmail && (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <Box
            sx={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: 2,
              justifyContent: { xs: 'center', sm: 'flex-start' },
            }}
          >
            <TextField
              label={t('completion.email')}
              variant="outlined"
              fullWidth
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onBlur={() => handleBlur('email')}
              disabled={isSendingCode || codeSent}
              error={touched.email && !!errors.email}
              helperText={touched.email && errors.email}
              sx={{
                flex: '1 1 260px',
                '& .MuiOutlinedInput-root': { height: INPUT_H },
              }}
              slotProps={{
                input: {
                  startAdornment: (
                    <InputAdornment position="start" sx={{ width: ADORN_W }}>
                      <Box
                        sx={{
                          width: ADORN_W,
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                      >
                        <Box
                          sx={{
                            alignItems: 'center',
                            visibility:
                              !isVerifyingCode && emailVerified
                                ? 'visible'
                                : 'hidden',
                          }}
                        >
                          <Icon
                            Component={TickCircle}
                            size="medium"
                            variant="Bold"
                            color="success.main"
                          />
                        </Box>
                      </Box>
                    </InputAdornment>
                  ),
                  endAdornment: (
                    <InputAdornment position="end" sx={{ width: ADORN_W }}>
                      <Box
                        sx={{
                          width: ADORN_W,
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                      >
                        <Box
                          sx={{ visibility: codeSent ? 'visible' : 'hidden' }}
                        >
                          <IconButton
                            onClick={handleEditEmail}
                            disabled={!codeSent}
                          >
                            <Icon
                              Component={Edit2}
                              color="primary.main"
                              size="medium"
                            />
                          </IconButton>
                        </Box>
                      </Box>
                    </InputAdornment>
                  ),
                },
              }}
            />

            {!isVerifyingCode &&
              !emailVerified &&
              (buttonState === 'counting' ? (
                <Typography
                  sx={{
                    minWidth: '140px',
                    width: { xs: '100%', sm: '156px' },
                    alignSelf: 'center',
                    textAlign: 'center',
                    lineHeight: `${INPUT_H}px`,
                    height: INPUT_H,
                  }}
                  color="primary"
                  variant="body1"
                >
                  {formatTimerValue()}
                </Typography>
              ) : (
                <Button
                  variant="text"
                  onClick={handleSendCode}
                  loading={isSendingCode}
                  sx={{
                    width: { xs: '100%', sm: '156px' },
                    alignSelf: 'center',
                    height: INPUT_H,
                  }}
                >
                  {t('completion.vericationCodeButton')}
                </Button>
              ))}
          </Box>

          {showCodeSection && (
            <Box
              sx={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: 2,
                justifyContent: { xs: 'center', sm: 'flex-start' },
                alignItems: 'stretch',
              }}
            >
              <TextField
                label={t('completion.verificationCode')}
                variant="outlined"
                type="text"
                value={verificationCode}
                onChange={handleVerificationCodeChange}
                sx={{
                  flex: '1 1 260px',
                  '& .MuiOutlinedInput-root': { height: INPUT_H },
                }}
                disabled={isVerifyingCode}
                onBlur={() => handleBlur('verificationCode')}
                error={touched.verificationCode && !!errors.verificationCode}
                helperText={touched.verificationCode && errors.verificationCode}
                inputProps={{
                  inputMode: 'numeric',
                  pattern: '[0-9]*',
                  maxLength: 4,
                }}
              />

              <Button
                variant="outlined"
                onClick={handleVerifyCode}
                loading={isVerifyingCode}
                sx={{
                  width: { xs: '100%', sm: '156px' },
                  alignSelf: 'stretch',
                  height: INPUT_H,
                }}
              >
                {t('completion.checkCodeButton')}
              </Button>
            </Box>
          )}
        </Box>
      )}
    </>
  );
}
