import {MyButton} from '@components/MyButton';
import {MyIconInput} from '@components/MyInput';
import {MyScreenContainer} from '@components/MyScreenContainer';
import {MyTitle} from '@components/MyTitle';
import {apiBackendRequest, makeRequest} from '@helper/request';
import {RootScreenNavigationProp} from '@navigation/navigation';
import {
  ContentContainer,
  navigateToHome,
} from '@navigation/registration/registration';
import {useNavigation} from '@react-navigation/native';
import {RootState, store} from '@redux/store';
import MyUserManager from '@user/MyUserManager';
import {useState} from 'react';
import {View} from 'react-native';
import {useSelector} from 'react-redux';
import {ToBase64} from '@helper/base64';
import showToast from '@components/MyToast';
import {useToast} from '@gluestack-ui/themed';

export function Login() {
  const lang = useSelector(
    (state: RootState) => state.appVariables.lang.registration,
  );
  const navigation = useNavigation<RootScreenNavigationProp>();
  const toast = useToast();

  const [isLoading, setIsLoading] = useState(false);
  const [accountName, setAccountName] = useState('anna');
  const [password, setPassword] = useState('testtesttest');

  const loginEnabled = accountName.length > 0 && password.length > 0;

  return (
    <MyScreenContainer
      style={{
        flexDirection: 'column',
      }}>
      <ContentContainer>
        <MyTitle text={lang.login.title} />

        <View style={{gap: 12}}>
          <MyIconInput
            text={lang.login.inputPhoneNumberOrAccountName}
            iconName="person"
            value={accountName}
            onChangeText={text => setAccountName(text)}
          />
          <MyIconInput
            text={lang.login.inputPassword}
            iconName="lock"
            secureTextEntry
            value={password}
            onChangeText={text => setPassword(text)}
          />

          <MyButton
            type="primary"
            isLoading={isLoading}
            text={lang.buttonLogin}
            style={{marginBottom: 20}}
            onPress={() => {
              setIsLoading(true);

              makeRequest({
                path: apiBackendRequest.LOGIN,
                request: {
                  AccountName: accountName,
                  Password: ToBase64(password),
                },
                response: {
                  XAuthorization: '',
                  Username: '',
                },
              })
                .then(resp => {
                  console.log('resp', resp);

                  MyUserManager.createNewMyUser(
                    accountName,
                    resp.response.Username,
                    resp.response.XAuthorization,
                  )
                    .then(async () => {
                      setIsLoading(false);
                      navigateToHome(navigation);
                    })
                    .catch(err => {
                      console.log('catch', err);
                    });
                })
                .catch(reason => {
                  console.log('reason', reason);
                  setIsLoading(false);

                  let text =
                    store.getState().appVariables.lang.registration
                      .signUpStepAccountName.signUpError[
                      reason.status as number
                    ];

                  showToast(toast, {
                    title: 'Failed',
                    variant: 'solid',
                    action: 'error',
                    description: text,
                    isClosable: true,
                  });
                });
            }}
            disabled={!loginEnabled}
          />
        </View>
      </ContentContainer>
    </MyScreenContainer>
  );
}
