import React, { useEffect, useState } from 'react';
import { View, Text, Image, TouchableOpacity, ImageBackground } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { useDispatch } from 'react-redux';
import { OtpInput } from "react-native-otp-entry";
import CustomButton from '../../../components/CustomButton';
import Background from '../../../components/Background';
import IMAGES from '../../../constants/Images';
import { GlobalTheme } from '../../../theme';
import { styles } from './style';
import { toastError, toastSuccess } from '../../../constants/Toast';
import Loader from '../../../constants/Loader';
import { ApiURL } from '../../../api/ApiConstant';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { setUser } from '../../../redux/slices/userSlice';
import axios from 'axios';
import { SafeAreaView } from 'react-native-safe-area-context';

const VerifyOTP = ({ navigation, route }) => {
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const [otp, setOTP] = useState('');
  const [timer, setTimer] = useState(300); // 5 minutes = 300 seconds
  const [showResend, setShowResend] = useState(false);

  const username = route.params.username;

  useEffect(() => {
    if (timer === 0) {
      setShowResend(true);
      return;
    }

    const interval = setInterval(() => {
      setTimer(prev => prev - 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [timer]);

  const formatTime = (secs) => {
    const minutes = Math.floor(secs / 60);
    const seconds = secs % 60;
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  };

  const handle_validate = () => {
    if (otp.length < 6) {
      toastError('Alert', "Please enter 6 digit PIN");
    } else {
      onSubmit();
    }
  }

  const resendOTP = 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('storeSearchApi====>', res);
      if (res?.SendOTP[0].OTP === '0' || res?.SendOTP[0].OTP === 0) {
        toastError("Alert", res?.SendOTP[0]?.Messages)
      } else {
        toastSuccess("Alert", res?.SendOTP[0]?.Messages)
        navigation.navigate('VerifyOTP', { username: username });
      }
      // console.log('getotpApi res==>', JSON.stringify(res?.SendOTP[0]));
      // setLoading(false)
    } catch (error) {
      // setLoading(false)
      console.log("❌ Filter API error:", error);
    }
  };

  const resend_OTP = () => {
    setTimer(300);
    setShowResend(false);
    toastSuccess('Resend OTP Successfully.')
    resendOTP();
  }

  const onSubmit = () => {
    setLoading(true)
    VerifyOTP();
    setTimeout(() => {
      setLoading(false)
    }, 100);
  }

  const VerifyOTP = async () => {
    try {
      const params = {
        "UserId": username,
        "OTP": otp
      }

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

      const response = await axios.request(config);
      const res = response.data || [];

      if (res?.AuthenticateOTP[0].Message == 'OTP is matched') {
        toastSuccess("Alert", res?.AuthenticateOTP[0]?.Message || "Alert", "Login Successfully.")
        await AsyncStorage.setItem('@Dabur_DNA_User', JSON.stringify(res?.AuthenticateOTP[0]));
        dispatch(setUser(res?.AuthenticateOTP[0]));
        navigation.reset({ index: 0, routes: [{ name: 'Welcome' }] })
      } else {
        toastError("Alert", res?.AuthenticateOTP[0]?.Message);
      }
    } catch (error) {
      // setLoading(false)
      console.log("❌ Filter API error:", error);
    }

  }

  return (
    <SafeAreaView style={styles.container}>
      <TouchableOpacity onPress={() => navigation.goBack()}>
        <View style={styles.backTextView}>
          <Image source={IMAGES.leftArrowIcon} style={styles.iconStyle} />
          <Text style={styles.backIconText}>Back</Text>
        </View>
      </TouchableOpacity>
      <KeyboardAwareScrollView keyboardShouldPersistTaps="handled" enableOnAndroid={true} style={styles.container} contentContainerStyle={{ justifyContent: 'center', flex: 1 }}>
        <View style={{ backgroundColor: GlobalTheme.colors.primary, height: 40 }} />
        <Image style={styles.appLogo} source={IMAGES.AuthTopBGNew} resizeMode='contain' />
        <View style={styles.card}>
          <View style={styles.titleContainer}>
            <Text style={styles.titleText}>Enter the OTP sent to your {"\n"} registered contact</Text>
          </View>
          <View style={{ marginTop: 50 }}>
            <OtpInput
              numberOfDigits={6}
              focusColor={GlobalTheme.colors.primary}
              autoFocus={false}
              hideStick={true}
              placeholder=""
              blurOnFilled={true}
              disabled={false}
              type="numeric"
              secureTextEntry={false}
              focusStickBlinkingDuration={500}
              // onFocus={() => console.log("Focused")}
              // onBlur={() => console.log("Blurred")}
              onTextChange={(text) => setOTP(text)}
              onFilled={(text) => {
                setOTP(text);
                console.log(`OTP is ${text}`);
              }}
              textInputProps={{
                accessibilityLabel: "One-Time Password",
              }}
              textProps={{
                accessibilityRole: "text",
                accessibilityLabel: "OTP digit",
                allowFontScaling: false,
              }}
              theme={{
                containerStyle: styles.container,
                pinCodeContainerStyle: styles.pinCodeContainer,
                pinCodeTextStyle: styles.pinCodeText,
                focusStickStyle: styles.focusStick,
                focusedPinCodeContainerStyle: styles.activePinCodeContainer,
                placeholderTextStyle: styles.placeholderText,
                filledPinCodeContainerStyle: styles.filledPinCodeContainer,
                disabledPinCodeContainerStyle: styles.disabledPinCodeContainer,
              }}
            />

          </View>
          <View style={{ marginTop: 100}}>
            <CustomButton onPress={handle_validate} title={'Verify'} style={styles.btnbg} textstyle={styles.btntext} />
          </View>

          <View style={{ alignItems: 'center', marginTop: 20 }}>
            {!showResend ? (
              <Text style={{ color: GlobalTheme.colors.darkGray }}>Resend OTP in {formatTime(timer)}</Text>
            ) : (
              <TouchableOpacity onPress={resend_OTP}>
                <Text style={styles.resendOTP} >
                  Resend OTP
                </Text>
              </TouchableOpacity>
            )}
          </View>

          <ImageBackground source={IMAGES.AuthBottomBG} style={styles.AuthBottomBG} >
            {/* <Image source={IMAGES.Logo} style={styles.footerImage} resizeMode="contain"/> */}
            <Text style={{ position : 'absolute', textAlign:'center', alignContent:'center',alignSelf:'center', bottom:0 , color : GlobalTheme.colors.gray}}> Copyright CPM India - 2025</Text>
           </ImageBackground>
        </View>

      </KeyboardAwareScrollView>
      <Loader visible={loading} />
    </SafeAreaView>
  );
};

export default VerifyOTP;
