import React, { useState, useEffect } from 'react';
import { useRoute } from '@react-navigation/native';
import { Platform, View, TextInput, Text, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import GradientButton from '../components/gradientButton';
import LinearGradient from 'react-native-linear-gradient';
import CustomHeader from '../components/customHeader';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { customeButtons, customStyles, GetPageTheme } from "../styles/Global";
import Container from '../components/container';
import { MaterialCommunityIcons, AntDesign } from '../components/icons';
import { notify } from '../components/notify';
import { get_item } from '../components/localStorage';
import { METHODS, getMethodName } from '../constants/methodNames';
import { changepassword } from '../controller/functions';
import CustomLoader from '../components/CustomLoader';

function ChangePassword(props) {
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkTheme, route.name);
  const customeButton = customeButtons(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);

  const [state, setState] = useState({
    oldpassword: '',
    newpassword: '',
    confirmpassword: '',
    lengthCheck: false,
    uppercaseCheck: false,
    lowercaseCheck: false,
    numberCheck: false,
    specialCharCheck: false,
    invalidCharCheck: false
  });

  const [showOldPassword, setShowOldPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const validatePassword = (password) => {
    const lengthCheck = /^.{8,20}$/;
    const uppercaseCheck = /[A-Z]/;
    const lowercaseCheck = /[a-z]/;
    const numberCheck = /[0-9]/;
    const specialCharCheck = /[!@#$%\-_]/;
    const invalidCharCheck = /[^a-zA-Z0-9!@#$%\-_]/;

    const isLengthValid = lengthCheck.test(password);
    const isUppercaseValid = uppercaseCheck.test(password);
    const isLowercaseValid = lowercaseCheck.test(password);
    const isNumberValid = numberCheck.test(password);
    const isSpecialCharValid = specialCharCheck.test(password);
    const isInvalidCharPresent = invalidCharCheck.test(password);

    setState((prevState) => ({
      ...prevState,
      lengthCheck: isLengthValid,
      uppercaseCheck: isUppercaseValid,
      lowercaseCheck: isLowercaseValid,
      numberCheck: isNumberValid,
      specialCharCheck: isSpecialCharValid,
      invalidCharCheck: isInvalidCharPresent,
    }));

    return isLengthValid && isUppercaseValid && isLowercaseValid && isNumberValid && isSpecialCharValid && !isInvalidCharPresent;
  };

  const validate = () => {
    const { oldpassword, newpassword, confirmpassword } = state;

    if (!oldpassword.trim()) return false;
    if (!newpassword.trim()) return false;
    if (!validatePassword(newpassword)) return false;
    if (!confirmpassword.trim()) return false;
    if (newpassword !== confirmpassword) return false;

    return true;
  };

  const [submitButtonColor, setSubmitButtonColor] = useState(['#B2BEB5', '#A9A9A9', '#808080']);
  const [processing, setProcessing] = useState(false);

  const handleSubmit = () => {
    const { oldpassword, newpassword, confirmpassword } = state;

    if (!oldpassword.trim()) {
      notify('Please enter old password', 'SHORT');
      return;
    }

    if (!newpassword.trim()) {
      notify('Please enter new password', 'SHORT');
      return;
    }

    if (!validatePassword(newpassword)) {
      notify('New password must be 8-20 characters long and include uppercase, lowercase, numbers, and special characters (!, @, #, $, %, -, _) and no other special characters', 'SHORT');
      return;
    }

    if (!confirmpassword.trim()) {
      notify('Please enter confirm password', 'SHORT');
      return;
    }

    if (newpassword !== confirmpassword) {
      notify('New password and confirm password do not match', 'SHORT');
      return;
    }

    setSubmitButtonColor([PageTheme.$secondary_color_light, PageTheme.$gradient2, PageTheme.$primary_color]);

    ConfirmPassword();
    // Proceed with the password change logic
  };

  useEffect(() => {
    validatePassword(state.newpassword);
  }, [state.newpassword]);

  useEffect(() => {
    if (validate()) {
      setSubmitButtonColor([PageTheme.$secondary_color_light, PageTheme.$gradient2, PageTheme.$primary_color]);
    } else {
      setSubmitButtonColor(['#B2BEB5', '#A9A9A9', '#808080']);
    }
  }, [state.confirmpassword, state.newpassword]);

  const getValidationStatus = (check, input) => {
    if (!input.trim()) {
      return { color: '#000', icon: 'exclamationcircle', iconColor: '#000' };
    }
    return check
      ? { color: 'green', icon: 'checkcircle', iconColor: 'green' }
      : { color: 'red', icon: 'closecircle', iconColor: '#ff0000' };
  };

  const ValidationMessage = ({ check, message }) => {
    const status = getValidationStatus(check, state.newpassword);
    return (
      <View style={styles.validationMessage}>
        <AntDesign style={{ marginTop: 4 }} size={14} name={status.icon} color={status.iconColor} />
        <Text style={{ color: status.color }}> {message}</Text>
      </View>
    );
  };

  const ConfirmPassword = async () => {
    const { oldpassword, newpassword, confirmpassword } = state;
    setProcessing(true);

    let projectInfo = await get_item('projectInfo');
    let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    let baseurl = projectDetails.baseURL || '';

    const method_name = getMethodName(METHODS.CHANGEPASSWORD_METHOD);
    const url = baseurl + method_name;
    const data = { un: loginDetails?.UserId, oldp: oldpassword, newp: newpassword, confirmp: confirmpassword };
    console.log(url, data)
    await changepassword(url, data)
      .then(async (res) => {
        setProcessing(false);
        if (res != "Success") {
          notify(res, 'SHORT')
        }
        else if (res == "Success") {
          notify('Password change successfully.', 'SHORT');
          props.navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
        }
        else if (res.networkErr && res.error) {
          notify('Please connect to internet-' + res.error, 'SHORT');
        }
        else if (!res.false && res.error) {
          notify(res.error, 'SHORT');
        }

      })
      .catch((err) => {
        setProcessing(false);
        console.log('onPage change password error1', err);
      });

  }

  const handlePasswordChange = (val) => {
    const invalidCharCheck = /[^a-zA-Z0-9!@#$%\-_]/;

    if (invalidCharCheck.test(val)) {
      notify('Invalid character entered', 'SHORT');
    } else {
      setState({ ...state, newpassword: val });
    }
  };

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
      <CustomHeader {...props} showaddstore={true} title={'Change Password'} />
      {processing && <CustomLoader title="Changing password..." />}
      <ScrollView>
        <LinearGradient
          colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 0 }}
          style={customStyle.roundScrollWrapper}
        >
          <View style={[customStyle.pageContentWrapper, customStyle.vlPageWrapper, styles.pageContent]}>
            <View style={{ alignItems: 'center' }}>
              <View style={[customStyle.formGroup, customStyle.mt20]}>
                <TextInput
                  style={[customStyle.inputStyle, customStyle.pl40, customStyle.pr40]}
                  placeholder="Old Password"
                  autoComplete="off"
                  placeholderTextColor={PageTheme.$placeholder_color}
                  secureTextEntry={!showOldPassword}
                  value={state.oldpassword}
                  onChangeText={(val) => setState({ ...state, oldpassword: val })}
                />
                <MaterialCommunityIcons
                  style={customStyle.formInputLeftIcon}
                  size={16}
                  name="lock-outline"
                  color={PageTheme.$placeholder_color}
                />
                <TouchableOpacity
                  style={styles.eyeIcon}
                  onPress={() => setShowOldPassword(!showOldPassword)}
                >
                  <MaterialCommunityIcons
                    size={16}
                    name={showOldPassword ? 'eye-outline' : 'eye-off-outline'}
                    color={PageTheme.$placeholder_color}
                  />
                </TouchableOpacity>
              </View>
              <View style={[customStyle.formGroup, customStyle.mt10]}>
                <TextInput
                  style={[customStyle.inputStyle, customStyle.pl40, customStyle.pr40]}
                  placeholder="New Password"
                  autoComplete="off"
                  placeholderTextColor={PageTheme.$placeholder_color}
                  secureTextEntry={!showNewPassword}
                  value={state.newpassword}
                  onChangeText={(val) => handlePasswordChange(val)}
                />
                <MaterialCommunityIcons
                  style={customStyle.formInputLeftIcon}
                  size={16}
                  name="lock-outline"
                  color={PageTheme.$placeholder_color}
                />
                <TouchableOpacity
                  style={styles.eyeIcon}
                  onPress={() => setShowNewPassword(!showNewPassword)}
                >
                  <MaterialCommunityIcons
                    size={16}
                    name={showNewPassword ? 'eye-outline' : 'eye-off-outline'}
                    color={PageTheme.$placeholder_color}
                  />
                </TouchableOpacity>
              </View>
              <View style={[customStyle.formGroup, customStyle.mt10]}>
                <TextInput
                  style={[customStyle.inputStyle, customStyle.pl40, customStyle.pr40]}
                  placeholder="Confirm Password"
                  autoComplete="off"
                  placeholderTextColor={PageTheme.$placeholder_color}
                  secureTextEntry={!showConfirmPassword}
                  value={state.confirmpassword}
                  onChangeText={(val) => setState({ ...state, confirmpassword: val })}
                />
                <MaterialCommunityIcons
                  style={customStyle.formInputLeftIcon}
                  size={16}
                  name="lock-outline"
                  color={PageTheme.$placeholder_color}
                />
                <TouchableOpacity
                  style={styles.eyeIcon}
                  onPress={() => setShowConfirmPassword(!showConfirmPassword)}
                >
                  <MaterialCommunityIcons
                    size={16}
                    name={showConfirmPassword ? 'eye-outline' : 'eye-off-outline'}
                    color={PageTheme.$placeholder_color}
                  />
                </TouchableOpacity>
              </View>
            </View>

            <View style={{ marginTop: 20 }}>
              <ValidationMessage check={state.lengthCheck} message="Must be between 8 - 20 characters long." />
              <ValidationMessage check={state.uppercaseCheck} message="Must contain at least one uppercase character ( A-Z )" />
              <ValidationMessage check={state.lowercaseCheck} message="Must contain at least one lowercase character ( a-z )" />
              <ValidationMessage check={state.numberCheck} message="Must contain at least one number (0-9)" />
              <ValidationMessage check={state.specialCharCheck} message= {`Must contain at least one special character \n ( !  @  #  $  %  -   _  )`} />
              {state.invalidCharCheck && <ValidationMessage check={!state.invalidCharCheck} message="Contains invalid characters." />}
            </View>

            <View style={styles.footerView}>
              <TouchableOpacity
                onPress={handleSubmit}
                activeOpacity={0.6}
                style={customeButton.g_buttonStyle}
              >
                <LinearGradient
                  colors={submitButtonColor}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                  style={customeButton.g_linearGradient}
                >
                  <Text style={customeButton.g_textStyle}>Submit</Text>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          </View>
        </LinearGradient>
      </ScrollView>
    </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ChangePassword);

const styles = StyleSheet.create({
  pageContent: {
    backgroundColor: '#fff',
    paddingTop: 0,
  },
  validationMessage: {
    paddingHorizontal: 40,
    paddingTop: 10,
    flexDirection: 'row',
  },
  footerView: {
    marginTop: 20,
    alignItems: 'center',
  },
  eyeIcon: {
    position: 'absolute',
    right: 0,
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center'
  },
});
