import React, { useState, type ChangeEvent } from 'react';
import { Box, Typography, Button, TextField, IconButton } from '@mui/material';
import { Edit, Refresh, TickCircle } from 'iconsax-react';
import { useTranslation } from 'react-i18next';
import { CardContainer } from '@/components/CardContainer';
import { CountDownTimer } from '@/components/CountDownTimer';
import { Toast } from '@/components/Toast';

export function PhoneNumber() {
  const { t } = useTranslation('profileSetting');
  const [isEditing, setIsEditing] = useState(false);
  const [phoneNumber, setPhoneNumber] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [showToast, setShowToast] = useState(false);
  const [buttonState, setButtonState] = useState<'default' | 'counting'>(
    'default',
  );
  const [isVerifying, setIsVerifying] = useState(false);
  const [isVerified, setIsVerified] = useState(false);

  const [phones, setPhone] = useState([
    { phone: '09123456789', time: '۱ ماه پیش', withCode: '+989123456789' },
  ]);

  const toggleEdit = () => {
    setIsEditing((prev) => {
      const enteringEditMode = !prev;
      if (enteringEditMode) {
        setPhoneNumber('');
        setVerificationCode('');
        setIsVerified(false);
        setButtonState('default');
        setShowToast(false);
      }
      return enteringEditMode;
    });
  };

  const handlePhoneNumberChange = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/\D/g, '');
    setPhoneNumber(value);
  };

  const handleVerificationCodeChange = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/\D/g, '');
    setVerificationCode(value);
  };

  const handleSendCode = () => {
    if (!phoneNumber) return;
    setButtonState('counting');
    setIsVerified(false);
  };

  const handleVerifyCode = () => {
    setIsVerifying(true);
    setTimeout(() => {
      setIsVerifying(false);
      setIsVerified(true);
      setShowToast(true);
      const newPhone = '+98' + phoneNumber.slice(1);
      setPhone([
        { phone: phoneNumber, time: 'چند ثانیه پیش', withCode: newPhone },
      ]);
    }, 1500);
  };

  const handleVerifyClick = () => {
    if (!verificationCode || isVerifying) return;
    handleVerifyCode();
    setTimeout(() => setShowToast(true), 1600);
  };

  return (
    <Box sx={{ backgroundColor: 'background.paper' }}>
      <CardContainer
        title={t('settingForm.titlePhoneNumber')}
        subtitle={t('settingForm.descriptionPhoneNumber')}
        highlighted={isEditing}
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            {isEditing && (
              <Button
                variant="text"
                onClick={toggleEdit}
                size="large"
                sx={{
                  color: 'primary.main',
                  textTransform: 'none',
                  width: '43px',
                }}
              >
                {t('settingForm.rejectButton')}
              </Button>
            )}
            <Button
              onClick={toggleEdit}
              size="large"
              variant="outlined"
              sx={{
                textTransform: 'none',
                border: '1px solid',
                borderColor: 'primary.main',
                borderRadius: '4px',
                bgcolor: isEditing ? 'primary.main' : 'background.paper',
                color: isEditing ? 'primary.contrastText' : 'primary.main',
                width: { xs: '100%', sm: isEditing ? '85px' : '161px' },
                whiteSpace: 'nowrap',
              }}
            >
              {isEditing
                ? t('settingForm.saveButton')
                : t('settingForm.editPhoneNumber')}
            </Button>
          </Box>
        }
      >
        {isEditing ? (
          <Box sx={{ px: { xs: 2, sm: 4 }, bgcolor: 'background.paper' }}>
            <Box sx={{ mb: 2 }}>
              <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
              sx={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: 2,
                alignItems: 'center',
              }}
            >
              <TextField
                name="phoneNumber"
                label={t('settingForm.newPhoneNumber')}
                type="tel"
                value={phoneNumber}
                onChange={handlePhoneNumberChange}
                sx={{ flex: '1 1 240px', minWidth: 0 }}
                placeholder="09123456789"
                inputProps={{ dir: 'rtl', style: { textAlign: 'right' } }}
                InputProps={{
                  endAdornment:
                    buttonState === 'counting' ? (
                      <IconButton
                        size="small"
                        onClick={() => {
                          setButtonState('default');
                          setPhoneNumber('');
                        }}
                        sx={{ mr: 1 }}
                      >
                        <Edit size="24" color="#64B5F6" />
                      </IconButton>
                    ) : null,
                }}
              />

              {isVerified ? (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <TickCircle
                    size="24"
                    style={{ color: '#43A047' }}
                    variant="Bold"
                  />
                  <Typography sx={{ color: 'success.main' }}>
                    {t('settingForm.successButton')}
                  </Typography>
                </Box>
              ) : (
                <Button
                  variant="text"
                  onClick={handleSendCode}
                  disabled={
                    buttonState === 'counting' || phoneNumber.length === 0
                  }
                  sx={{
                    textTransform: 'none',
                    minWidth: { xs: '100%', sm: 170 },
                    color: 'primary.main',
                    height: 56,
                  }}
                >
                  {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',
                }}
              >
                <TextField
                  name="verificationCode"
                  label={t('settingForm.verificationCode')}
                  type="tel"
                  value={verificationCode}
                  onChange={handleVerificationCodeChange}
                  sx={{ flex: '1 1 240px', minWidth: 0 }}
                  placeholder={t('settingForm.verificationCode')}
                  inputProps={{ dir: 'rtl', style: { textAlign: 'right' } }}
                />

                <Button
                  variant="contained"
                  onClick={handleVerifyClick}
                  disabled={isVerifying || verificationCode.length === 0}
                  sx={{
                    textTransform: 'none',
                    minWidth: { xs: '100%', sm: 170 },
                    bgcolor: 'primary.main',
                    height: 56,
                  }}
                >
                  {isVerifying ? (
                    <Box
                      component="span"
                      sx={{
                        display: 'flex',
                        animation: 'spin 1s linear infinite',
                        '@keyframes spin': {
                          '0%': { transform: 'rotate(0deg)' },
                          '100%': { transform: 'rotate(360deg)' },
                        },
                      }}
                    >
                      <Refresh size="20" color="white" />
                    </Box>
                  ) : (
                    t('settingForm.checkCode')
                  )}
                </Button>
              </Box>
            )}

            <Toast
              color="success"
              open={showToast}
              onClose={() => setShowToast(false)}
            >
              {t('settingForm.successfulChangePhone')}
            </Toast>
          </Box>
        ) : (
          <Box sx={{ px: { xs: 2, sm: 4 } }}>
            {phones.map((item, index) => (
              <Box
                key={index}
                sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  py: 2,
                  width: '100%',
                }}
              >
                <Typography variant="h6" color="text.primary">
                  {item.phone}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  {item.time}
                </Typography>
              </Box>
            ))}
          </Box>
        )}
      </CardContainer>
    </Box>
  );
}
