
import React, { useEffect, useState } from 'react';
import { View, Text, Image, Platform, ImageBackground } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import IMAGES from '../../../constants/Images';
import { styles } from './style';
import { useDispatch } from 'react-redux';
import CustomTextInput from '../../../components/CustomTextInput';
import CustomButton from '../../../components/CustomButton';
import Loader from '../../../constants/Loader';
import { ApiURL } from '../../../api/ApiConstant';
import { toastError, toastSuccess } from '../../../constants/Toast';
import axios from 'axios';
import { SafeAreaView } from 'react-native-safe-area-context';
import { GlobalTheme } from '../../../theme';
import Geolocation from '@react-native-community/geolocation';


const Login = ({ navigation }) => {
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const [username, setUsername] = useState('');


  // geo loc
  useEffect(() => {
    Geolocation.getCurrentPosition(info => console.log("Location infoooo====>", JSON.stringify(info)));
  }, [])
  // end geo loc


  const onSubmit = () => {
    setLoading(true);
    getOTP();
  };

  const getOTP = async () => {
    try {
      const params = {
        "UserId": username
      };

      const config = {
        method: 'post',
        url: ApiURL.getotpApi,
        headers: {
          'api_key': '9a1f056fecb84eaf8eb4152dda22ab0501955c4f9bbe7daa8780740459fdde7a',
          'Content-Type': 'application/json'
        },
        data: params
      };

      const response = await axios.request(config);
      const res = response.data || [];
      console.log('OTP is ===> ', res?.SendOTP);
      if (res?.SendOTP[0].OTP === '0' || res?.SendOTP[0].OTP === 0) {
        setLoading(false);
        toastError("Alert", "Invalid User");
      } else {
        toastSuccess("Alert", res?.SendOTP[0]?.Messages);
        navigation.navigate('VerifyOTP', { username: username });
        setLoading(false);
      }
      // console.log('getotpApi res==>', JSON.stringify(res?.SendOTP[0]));
    } catch (error) {
      console.log("❌ OTP API error:", error);
      setLoading(false);
    }
  };
  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAwareScrollView keyboardShouldPersistTaps="handled" enableOnAndroid={true} contentContainerStyle={{ justifyContent: 'center', flexGrow: 1, marginTop: 0 }} style={styles.container}>
        <View style={{ backgroundColor: GlobalTheme.colors.primary, height: 40 }} />
        <Image style={styles.appLogo} source={IMAGES.AuthTopBGNew} resizeMode='contain' />
        <View style={styles.card}>
          <Text style={styles.loginTitle}>Login</Text>
          <CustomTextInput
            label="Username"
            placeholder="Enter username"
            value={username}
            onChangeText={setUsername}
            containerStyle={styles.inputWrapper}
          />
          <CustomButton onPress={() => onSubmit()} title={'Continue'} style={styles.btnbg} textstyle={styles.btntext} />
          <ImageBackground source={IMAGES.AuthBottomBG} style={styles.AuthBottomBG} >
            <Text style={{ position: 'absolute', textAlign: 'center', alignContent: 'center', alignSelf: 'center', bottom: 0, color: GlobalTheme.colors.gray }}> Copyright CPM India - 2025</Text>
            {/* <Image source={IMAGES.Logo} style={styles.footerImage} resizeMode="contain"/> */}
          </ImageBackground>
        </View>
      </KeyboardAwareScrollView>
      <Loader visible={loading} loadingtext={'Loading ...'} />
    </SafeAreaView>
  );
};

export default Login;

