import { Box, Button, Paper, TextField, Typography } from '@mui/material';
import parsePhoneNumberFromString from 'libphonenumber-js';
import React, { useRef, useState, type Dispatch } from 'react';
import { useTranslation } from 'react-i18next';
import { CountryCodeSelector } from './CountryCodeSelector';
import { AuthenticationCard } from './AuthenticationCard';

export interface CompleteSignUpProps {
  email: string;
  value: string;
  setValue: Dispatch<string>;
  onCompleteSignUp: (countryCode: string, value: string) => void;
}

export const CompleteSignUp = ({
  email,
  value,
  setValue,
  onCompleteSignUp,
}: CompleteSignUpProps) => {
  const { t } = useTranslation('authentication');
  const [countryCode, setCountryCode] = useState('+98');
  const [error, setError] = useState<string>();
  const textFieldRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [touched, setTouched] = useState<boolean>(false);
  const inputError: boolean = touched && !!error;

  const isPhoneValid = (code: string, phone: string) => {
    const phoneNumber = parsePhoneNumberFromString(code + phone);

    return phoneNumber && phoneNumber.isValid();
  };

  const handleBlur = () => {
    setTouched(true);

    if (!value) {
      setError(t('loginForm.thisFieldIsRequired'));
    }
    if (!isPhoneValid(countryCode, value)) {
      setError(t('loginForm.phoneNumberIsInvalid'));
    } else {
      setError(undefined);
    }
  };

  const handleCompleteSignUp = () => {
    if (!value) {
      setError(t('loginForm.thisFieldIsRequired'));
      inputRef.current?.focus();
    }
    if (!isPhoneValid(countryCode, value)) {
      setError(t('loginForm.phoneNumberIsInvalid'));
      inputRef.current?.focus();
    } else {
      setError(undefined);
      onCompleteSignUp(countryCode, value);
    }
  };

  return (
    <AuthenticationCard>
      <Typography variant="h5" sx={{ mb: 0.5 }}>
        {t('completeSignUp.completeSignUp')}
      </Typography>

      <Typography variant="body2" color="textSecondary" sx={{ mt: 1, mb: 2 }}>
        {t(
          'completeSignUp.emailHasBeenSuccessfullyVerifiedPleaseEnterYourContactNumberToContinue',
          { email },
        )}
      </Typography>

      <TextField
        ref={textFieldRef}
        inputRef={inputRef}
        label={t('completeSignUp.phoneNumber')}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        onBlur={handleBlur}
        error={inputError}
        helperText={inputError ? error : ''}
        autoFocus
        slotProps={{
          htmlInput: { dir: 'auto', sx: { lineHeight: 1.5, paddingX: 0 } },
          input: {
            endAdornment: (
              <CountryCodeSelector
                value={countryCode}
                onChange={setCountryCode}
                show={true}
                menuAnchor={textFieldRef.current}
                onCloseFocusRef={inputRef}
              />
            ),
          },
        }}
        sx={{ my: 4 }}
      />

      <Button onClick={handleCompleteSignUp}>
        {t('verify.confirmAndContinue')}
      </Button>
    </AuthenticationCard>
  );
};
