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 '../../../../components/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 ForgetPasswordInfoProps {
  forgetPasswordInfo: string;
  setForgetPasswordInfo: Dispatch<string>;
  infoType: AuthType;
  setInfoType: Dispatch<AuthType>;
  onVerifyOtp: (value: string) => void;
  countryCode: CountryCode;
  setCountryCode: Dispatch<CountryCode>;
}

export function ForgetPasswordInfo({
  forgetPasswordInfo,
  setForgetPasswordInfo,
  infoType,
  setInfoType,
  onVerifyOtp,
  countryCode,
  setCountryCode,
}: ForgetPasswordInfoProps) {
  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);
    }
    setForgetPasswordInfo(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(forgetPasswordInfo, 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(forgetPasswordInfo, infoType, false)) {
      const sendCodeRequest: SendForgetPassCodeRequest = {
        email: infoType === 'email' ? forgetPasswordInfo : undefined,
        phoneNumber:
          infoType === 'phone' ? countryCode + forgetPasswordInfo : undefined,
      };
      const res = await sendForgetPassCodeCall(sendCodeRequest);

      if (!res) return;

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

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

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

  return (
    <AuthenticationCard>
      <Stack component="form" onSubmit={handleSubmit} 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={forgetPasswordInfo}
        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} type="submit">
          {t('forgetPassword.confirm')}
        </Button>
      </Stack>
    </AuthenticationCard>
  );
}
