import {
  Box,
  Typography,
  TextField,
  Button,
  IconButton,
  InputAdornment,
  CircularProgress,
} from '@mui/material';
import { Edit2, TickCircle } from 'iconsax-react';
import { CountDownTimer } from '@/components/CountDownTimer';
import { Icon } from '@rkheftan/harmony-ui';
import { useRef } from 'react';
import { useTranslation } from 'react-i18next';

type SocialEditFormProps = {
  email: string;
  setEmail: (v: string) => void;
  emails: { address: string }[];
  verificationCode: string;
  setVerificationCode: (v: string) => void;
  isVerified: boolean;
  isVerifying: boolean;
  isSendingCode: boolean;
  isCodeSent: boolean;
  setIsCodeSent: (v: boolean) => void;
  buttonState: 'default' | 'counting';
  setButtonState: (v: 'default' | 'counting') => void;
  handleSendCode: () => void;
  handleVerifyClick: () => void;
  handleBlur: (field: 'email' | 'verificationCode') => void;
  emailError?: string;
  verificationCodeError?: string;
};

export default function SocialEditForm({
  email,
  setEmail,
  emails,
  verificationCode,
  setVerificationCode,
  isVerified,
  isVerifying,
  isSendingCode,
  isCodeSent,
  setIsCodeSent,
  buttonState,
  setButtonState,
  handleSendCode,
  handleVerifyClick,
  handleBlur,
  emailError,
  verificationCodeError,
}: SocialEditFormProps) {
  const { t } = useTranslation('setting');

  const textFieldRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  return (
    <Box sx={{ px: { sm: 4, xs: 2 }, my: 4 }}>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6">
          {t('settingForm.editEmailOrGoogle')}
        </Typography>
        <Typography variant="body2" color="text.secondary">
          {t('settingForm.emailText', {
            email: emails.map((e) => e.address).join(', '),
          })}
        </Typography>
      </Box>

      <Box
        sx={{
          display: 'flex',
          gap: 2,
          alignItems: 'center',
          pb: 2,
          flexDirection: { xs: 'column', sm: 'row' },
        }}
      >
        <TextField
          fullWidth
          name="email"
          label={t('settingForm.newEmail')}
          type="email"
          value={email}
          ref={textFieldRef}
          inputRef={inputRef}
          onBlur={() => handleBlur('email')}
          error={!!emailError}
          helperText={emailError}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="abc@email.com"
          autoComplete="email"
          inputMode="email"
          disabled={isCodeSent}
          slotProps={{
            input: {
              endAdornment: isCodeSent ? (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    onClick={() => {
                      setButtonState('default');
                      setVerificationCode('');
                      setIsCodeSent(false);
                    }}
                    edge="end"
                  >
                    <Icon
                      Component={Edit2}
                      color="primary.main"
                      variant="Bold"
                    />
                  </IconButton>
                </InputAdornment>
              ) : undefined,
            },
          }}
        />

        {isVerified ? (
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              color: 'success.main',
            }}
          >
            <Icon Component={TickCircle} />
            <Typography>{t('settingForm.successButton')}</Typography>
          </Box>
        ) : (
          <Button
            variant="text"
            loading={isSendingCode}
            onClick={handleSendCode}
            sx={{ color: 'primary.main', width: { xs: '100%', sm: 208 } }}
            disabled={buttonState === 'counting'}
          >
            {buttonState === 'counting' ? (
              <CountDownTimer
                initialSeconds={60}
                onComplete={() => setButtonState('default')}
              />
            ) : (
              t('settingForm.verificationCodeButton')
            )}
          </Button>
        )}
      </Box>

      {isCodeSent && !isSendingCode && !isVerified && (
        <Box
          sx={{
            display: 'flex',
            gap: 2,
            alignItems: 'center',
            flexDirection: { xs: 'column', sm: 'row' },
            mb: 2,
            pt: 2,
          }}
        >
          <TextField
            fullWidth
            name="verificationCode"
            label={t('settingForm.verificationCode')}
            type="tel"
            value={verificationCode}
            error={!!verificationCodeError}
            helperText={verificationCodeError}
            onBlur={() => handleBlur('verificationCode')}
            onChange={(e) =>
              setVerificationCode(e.target.value.replace(/\D/g, ''))
            }
            placeholder={t('settingForm.verificationCode')}
            autoComplete="one-time-code"
            inputMode="numeric"
          />

          <Button
            variant="contained"
            onClick={handleVerifyClick}
            disabled={isVerifying || verificationCode.length === 0}
            sx={{ bgcolor: 'primary.main', width: { xs: '100%', sm: 200 } }}
          >
            {isVerifying ? (
              <CircularProgress size={20} />
            ) : (
              t('settingForm.checkCode')
            )}
          </Button>
        </Box>
      )}
    </Box>
  );
}
