import {
  Box,
  Typography,
  TextField,
  Button,
  IconButton,
  InputAdornment,
  CircularProgress,
} from '@mui/material';
import { Edit2, TickCircle } from 'iconsax-react';
import { CountDownTimer } from '@/components/CountDownTimer';
import { CountryCodeSelector } from '../../CountryCodeSelector';
import { Icon } from '@rkheftan/harmony-ui';
import { type PhoneEditFormProps } from '@/features/profile/types/settingsType';
import { useState } from 'react';

export default function PhoneEditForm({
  phoneNumber,
  setPhoneNumber,
  countryCode,
  setCountryCode,
  verificationCode,
  setVerificationCode,
  isVerified,
  isVerifying,
  buttonState,
  setButtonState,
  handleSendCode,
  handleVerifyClick,
  error,
  inputError,
  handleBlur,
  textFieldRef,
  inputRef,
  phones,
  t,
}: PhoneEditFormProps) {
  const isValidPhoneNumber = (phone: string) => {
    const digitsOnly = phone.replace(/\D/g, '');
    return digitsOnly.length >= 8 && digitsOnly.length <= 15;
  };

  const [isSending, setIsSending] = useState(false);

  return (
    <>
      <Box sx={{ width: '100%' }}>
        <Box sx={{ mb: 2, mx: 3 }}>
          <Typography variant="h6">
            {t('settingForm.editPhoneNumber')}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {t('settingForm.phoneNumberText')}({phones.map((p) => p.withCode)})
            {t('settingForm.verb')}
          </Typography>
        </Box>
      </Box>

      <Box
        sx={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: 2,
          alignItems: 'center',
          mx: 3,
        }}
      >
        <TextField
          name="phoneNumber"
          label={t('settingForm.newPhoneNumber')}
          type="tel"
          value={phoneNumber}
          ref={textFieldRef}
          inputRef={inputRef}
          onBlur={handleBlur}
          error={inputError}
          helperText={inputError ? error : ''}
          onChange={(e) => setPhoneNumber(e.target.value)}
          sx={{ flex: '1 1 220px' }}
          placeholder="09123456789"
          InputProps={{
            endAdornment:
              buttonState === 'counting' ? (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    onClick={() => {
                      setButtonState('default');
                      setPhoneNumber('');
                      setVerificationCode('');
                    }}
                    edge="end"
                  >
                    <Icon
                      Component={Edit2}
                      color="primary.main"
                      variant="Bold"
                    />
                  </IconButton>
                </InputAdornment>
              ) : (
                <CountryCodeSelector
                  value={countryCode}
                  onChange={setCountryCode}
                  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"
            onClick={async () => {
              if (isValidPhoneNumber(phoneNumber)) {
                setIsSending(true);
                try {
                  await handleSendCode();
                } finally {
                  setIsSending(false);
                }
              }
            }}
            disabled={
              isSending ||
              buttonState === 'counting' ||
              phoneNumber.length === 0 ||
              !isValidPhoneNumber(phoneNumber)
            }
            sx={{
              minWidth: { xs: '100%', sm: 220 },
              color: 'primary.main',
              textTransform: 'none',
            }}
          >
            {isSending ? (
              <CircularProgress size={20} />
            ) : buttonState === 'counting' ? (
              <CountDownTimer
                initialSeconds={60}
                onComplete={() => setButtonState('default')}
              />
            ) : (
              t('settingForm.verificationCodeButton')
            )}
          </Button>
        )}
      </Box>

      {buttonState === 'counting' && !isVerified && (
        <Box
          sx={{
            display: 'flex',
            flexWrap: 'wrap',
            gap: 2,
            mt: 2,
            alignItems: 'center',
            mx: 3,
          }}
        >
          <TextField
            name="verificationCode"
            label={t('settingForm.verificationCode')}
            type="tel"
            value={verificationCode}
            onChange={(e) =>
              setVerificationCode(e.target.value.replace(/\D/g, ''))
            }
            sx={{ flex: '1 1 240px', minWidth: 0 }}
            placeholder={t('settingForm.verificationCode')}
          />

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