import { Button, Stack, TextField, Typography } from '@mui/material';
import { useRef, useState, type Dispatch } from 'react';
import { useTranslation } from 'react-i18next';
import { isNumeric } from '@/utils/regexes/isNumeric';
import type { AuthType } from '../../types/authTypes';
import { isEmail } from '@/utils/regexes/isEmail';
import { AuthenticationCard } from '../AuthenticationCard';
import { CountryCodeSelector } from '../CountryCodeSelector';
import type { CountryCode } from '@/types/commonTypes';
import { sendForgetPassCode } from '../../api/authorizationAPI';
import type { SendForgetPassCodeRequest } from '../../types/userTypes';
import { isPhoneNumber } from '@/utils/regexes/isValidPhoneNumber';
import { useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
import { replacePersianWithRealNumbers } from '@/utils/replacePersianWithRealNumbers';

export interface ForgettedPasswordInfoProps {
  forgettedPasswordInfo: string;
  setForgettedPasswordInfo: Dispatch<string>;
  infoType: AuthType;
  setInfoType: Dispatch<AuthType>;
  onVerifyOtp: (value: string) => void;
  countryCode: CountryCode;
  setCountryCode: Dispatch<CountryCode>;
}

export function ForgettedPasswordInfo({
  forgettedPasswordInfo,
  setForgettedPasswordInfo,
  infoType,
  setInfoType,
  onVerifyOtp,
  countryCode,
  setCountryCode,
}: ForgettedPasswordInfoProps) {
  const { t } = useTranslation('authentication');
  const textFieldRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [error, setError] = useState<string>();
  const [touched, setTouched] = useState<boolean>(false);
  const inputError: boolean = touched && !!error;
  const toast = useToast();
  const {
    loading: sendForgetPassCodeLoading,
    execute: sendForgetPassCodeCall,
  } = useApi(sendForgetPassCode);

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    let newValue = event.target.value;
    newValue = replacePersianWithRealNumbers(newValue);
    if (newValue.startsWith('09')) {
      newValue = newValue.substring(1);
    }
    setForgettedPasswordInfo(newValue);

    // If the new value contains only digits (or is empty), it's a phone number
    if (isNumeric(newValue)) {
      setInfoType('phone');
    } else {
      setInfoType('email');
    }
  };

  const handleBlur = () => {
    setTouched(true);
    validateInput(forgettedPasswordInfo, infoType);
  };

  const validateInput = (
    value: string,
    authType: AuthType,
    setErrors: boolean = true,
  ) => {
    if (!value) {
      if (setErrors) setError(t('loginForm.thisFieldIsRequired'));
      return false;
    } else if (authType === 'email' && !isEmail(value)) {
      if (setErrors) setError(t('loginForm.emailIsInvalid'));
      return false;
    } else if (authType === 'phone' && !isPhoneNumber(countryCode, value)) {
      if (setErrors) setError(t('loginForm.phoneNumberIsInvalid'));
      return false;
    } else {
      if (setErrors) setError(undefined);
      return true;
    }
  };

  const handleSubmit = async () => {
    if (validateInput(forgettedPasswordInfo, infoType, false)) {
      const sendCodeRequest: SendForgetPassCodeRequest = {
        email: infoType === 'email' ? forgettedPasswordInfo : undefined,
        phoneNumber:
          infoType === 'phone'
            ? countryCode + forgettedPasswordInfo
            : undefined,
      };
      const res = await sendForgetPassCodeCall(sendCodeRequest);

      if (!res) return;

      if (!res.success) {
        toast({
          message: res.message,
          severity: 'error',
        });
      }

      onVerifyOtp(forgettedPasswordInfo);
    } else {
      inputRef.current?.focus();
      validateInput(forgettedPasswordInfo, infoType);
    }
  };

  const showAdornment =
    infoType === 'phone' && forgettedPasswordInfo.length > 0;

  return (
    <AuthenticationCard>
      <Stack spacing={1}>
        <Typography variant="h5">
          {t('forgetPassword.forgetPassword')}
        </Typography>
        <Typography variant="body2" color="text.secondary">
          {t(
            'forgetPassword.pleaseEnterYourMobileNumberEmailToRecoverYourPassword',
          )}
        </Typography>
      </Stack>

      <TextField
        ref={textFieldRef}
        inputRef={inputRef}
        label={t('loginForm.emailOrPhoneLabel')}
        value={forgettedPasswordInfo}
        onChange={handleInputChange}
        onBlur={handleBlur}
        error={inputError}
        helperText={inputError ? error : ''}
        autoFocus
        slotProps={{
          htmlInput: { dir: 'auto', sx: { lineHeight: 1.5 } },
          input: {
            endAdornment: (
              <CountryCodeSelector
                value={countryCode}
                onChange={setCountryCode}
                show={showAdornment}
                menuAnchor={textFieldRef.current}
                onCloseFocusRef={inputRef}
              />
            ),
          },
        }}
        sx={{ my: 4, mb: 8 }}
      />

      <Stack spacing={2}>
        <Button loading={sendForgetPassCodeLoading} onClick={handleSubmit}>
          {t('forgetPassword.confirm')}
        </Button>
      </Stack>
    </AuthenticationCard>
  );
}
