import { useTranslation } from 'react-i18next';
import { Box, Button, Stack, Typography } from '@mui/material';
import { Edit2 } from 'iconsax-react';
import DigitInput from '@/components/DigitsInput';
import type { AuthType } from '../../types/authTypes';
import { useEffect, useState } from 'react';
import { AuthenticationCard } from '../AuthenticationCard';
import type {
  ConfirmForgetPassCodeRequest,
  SendForgetPassCodeRequest,
} from '../../types/userTypes';
import type { CountryCode } from '@/types/commonTypes';
import {
  confirmForgetPassCode,
  sendForgetPassCode,
} from '../../api/authorizationAPI';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';

interface ForgetPasswordOtpProps {
  forgetPasswordInfo: string;
  infoType: AuthType;
  countryCode: CountryCode;
  onEditInfo: () => void;
  onOTPVerified: (otpCode: string) => void;
}

export function ForgetPasswordOtp({
  forgetPasswordInfo,
  infoType,
  countryCode,
  onEditInfo,
  onOTPVerified,
}: ForgetPasswordOtpProps) {
  const [otpCode, setOtpCode] = useState<string>('');
  const [otpDigitInvalid, setOtpDigitInvalid] = useState<boolean>(false);
  const [isStatusSuccess, setIsStatusSuccess] = useState<boolean>();
  const { t } = useTranslation('authentication');
  const [resendTimer, setResendTimer] = useState<number>(120);
  const [canResend, setCanResend] = useState(false);
  const toast = useToast();
  const {
    loading: sendForgetPassCodeLoading,
    execute: sendForgetPassCodeCall,
  } = useApi(sendForgetPassCode);
  const {
    loading: confirmForgetPassCodeLoading,
    execute: confirmForgetPassCodeCall,
  } = useApi(confirmForgetPassCode);

  useEffect(() => {
    if (otpCode.length === 4) {
      handleVerifyOTP();
    }
  }, [otpCode]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (resendTimer > 0) {
      interval = setInterval(() => {
        setResendTimer((prev) => prev - 1);
      }, 1000);
    } else {
      setCanResend(true);
    }

    return () => clearInterval(interval);
  }, [resendTimer]);

  const handleResendOTPCode = async () => {
    const sendCodeRequest: SendForgetPassCodeRequest = {
      email: infoType === 'email' ? forgetPasswordInfo : undefined,
      phoneNumber:
        infoType === 'phone' ? countryCode + forgetPasswordInfo : undefined,
    };
    await sendForgetPassCodeCall(sendCodeRequest);

    setResendTimer(120);
    setCanResend(false);
  };

  const formatTime = (seconds: number) => {
    const min = Math.floor(seconds / 60);
    const sec = seconds % 60;
    return `${min}:${sec.toString().padStart(2, '0')}`;
  };

  const handleVerifyOTP = async () => {
    if (!otpCode || otpCode.length < 4) {
      setOtpDigitInvalid(true);
    } else {
      setOtpDigitInvalid(false);

      // Change setTimeout to api call
      const apiRequest: ConfirmForgetPassCodeRequest = {
        email: infoType === 'email' ? forgetPasswordInfo : undefined,
        phoneNumber:
          infoType === 'phone' ? countryCode + forgetPasswordInfo : undefined,
        code: otpCode,
      };

      const res = await confirmForgetPassCodeCall(apiRequest);

      if (!res) return;

      if (res.success) {
        setIsStatusSuccess(true);
        onOTPVerified(otpCode);
      } else {
        setIsStatusSuccess(false);
        toast({
          message: res.message,
          severity: 'error',
        });
      }
    }
  };

  return (
    <Stack alignItems="center">
      <AuthenticationCard>
        <Box
          component="form"
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            if (!confirmForgetPassCodeLoading) {
              void handleVerifyOTP();
            }
          }}
        >
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: 4,
              mb: 0.5,
            }}
          >
            <Typography variant="h5">
              {t('forgetPassword.forgetPassword')}
            </Typography>

            <Button
              variant="outlined"
              size="large"
              sx={{ textTransform: 'lowercase', width: 'auto' }}
              endIcon={<Icon Component={Edit2} />}
              onClick={onEditInfo}
            >
              {infoType === 'phone'
                ? countryCode + forgetPasswordInfo
                : forgetPasswordInfo}
            </Button>
          </Box>

          <Typography variant="body2" color="textSecondary" sx={{ mt: 1 }}>
            {infoType === 'email'
              ? t(
                  'forgetPassword.anEmailContainingARecoveryCodeHasBeenSentToThisEmailAddress',
                )
              : t(
                  'forgetPassword.anCodeContainingARecoveryCodeHasBeenSentToThisPhoneNumber',
                )}
          </Typography>

          <DigitInput
            error={otpDigitInvalid || isStatusSuccess === false}
            success={isStatusSuccess === true}
            onChange={(value) => setOtpCode(value)}
          />

          <Button type="submit" loading={confirmForgetPassCodeLoading}>
            {t('forgetPassword.confirm')}
          </Button>
        </Box>
      </AuthenticationCard>

      <Stack
        direction="row"
        sx={{
          justifyContent: 'center',
          alignItems: 'center',
          mt: 2.5,
        }}
      >
        <Typography variant="body1">{t('verify.resendCodeIn')}</Typography>

        <Typography
          variant="body1"
          sx={{ color: 'primary.main', marginInlineStart: 1 }}
        >
          {!canResend && `${formatTime(resendTimer)} ${t('verify.moreMinute')}`}
        </Typography>

        {canResend && (
          <Button
            variant="text"
            loading={sendForgetPassCodeLoading}
            sx={{ width: 'auto', p: 0 }}
            onClick={canResend ? handleResendOTPCode : undefined}
          >
            {t('verify.resendCode')}
          </Button>
        )}
      </Stack>
    </Stack>
  );
}
