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 { type PhoneEditFormProps } from '@/features/profile/types/settingsType';
import { useRef } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { CountryCodeSelector } from '@/components/CountryCodeSelector';
import { LTRTypography } from '@/components/common/LTRTypography';

export default function PhoneEditForm({
  phoneNumber,
  setPhoneNumber,
  countryCode,
  setCountryCode,
  verificationCode,
  setVerificationCode,
  isVerified,
  isVerifying,
  isSendingCode,
  isCodeSent,
  setIsCodeSent,
  buttonState,
  setButtonState,
  handleSendCode,
  handleVerifyClick,
  handleBlur,
  phones,
  phoneNumberError,
  verificationCodeError,
}: PhoneEditFormProps) {
  const { t, i18n } = 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.editPhoneNumber')}</Typography>
        <Typography variant="body2" color="text.secondary">
          <Trans
            i18nKey="settingForm.phoneNumberText"
            ns="setting"
            values={{
              phoneNumber: phones.map((p) => p.withCode).join(', '),
            }}
            components={{
              1: <LTRTypography as="span" />,
            }}
          />
        </Typography>
      </Box>
      <Box
        sx={{
          display: 'flex',
          gap: 2,
          alignItems: 'center',
          pb: 2,
          flexDirection: { xs: 'column', sm: 'row' },
        }}
      >
        <TextField
          fullWidth
          name="phoneNumber"
          label={t('settingForm.newPhoneNumber')}
          disabled={isCodeSent}
          type="tel"
          value={phoneNumber}
          ref={textFieldRef}
          inputRef={inputRef}
          onBlur={() => handleBlur('phoneNumber')}
          error={!!phoneNumberError}
          helperText={phoneNumberError}
          onChange={(e) => setPhoneNumber(e.target.value)}
          placeholder="09123456789"
          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>
              ) : (
                i18n.dir() === 'rtl' && (
                  <CountryCodeSelector
                    value={countryCode}
                    onChange={setCountryCode}
                    show={true}
                    disabled={isCodeSent}
                    menuAnchor={textFieldRef.current}
                    onCloseFocusRef={inputRef}
                  />
                )
              ),
              startAdornment: i18n.dir() === 'ltr' && (
                <CountryCodeSelector
                  value={countryCode}
                  onChange={setCountryCode}
                  disabled={isCodeSent}
                  show={true}
                  menuAnchor={textFieldRef.current}
                  onCloseFocusRef={inputRef}
                />
              ),
            },
          }}
        />

        {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 },
            }}
          >
            {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')}
          />

          <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>
  );
}
