import messaging from "@react-native-firebase/messaging";
import axios from "axios";
import React, { useEffect, useRef, useState } from "react";
import {
  Alert,
  Linking,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import DeviceInfo from "react-native-device-info";
import { connect, ConnectedProps } from "react-redux";
import config from "../../config/config";
import Colors from "../../constants/colors";
import { getAuditFormData } from "../../store/actions/auditFormScreenActions";
import { getIncidentReportFormData } from "../../store/actions/incidentReportActions";
import { getInspectionFormData } from "../../store/actions/InspectionActions";
import { authenticate } from "../../store/actions/securityActions";
import { Spinner } from "../common";

interface RootState {
  userInfo: {
    loading: boolean;
    error: string;
  };
  offline: {
    online: boolean;
  };
}

const mapStateToProps = (state: RootState) => {
  return {
    userInfo: state.userInfo,
    offline: state.offline,
  };
};

const mapDispatchToProps = {
  authenticate,
  getIncidentReportFormData,
  getAuditFormData,
  getInspectionFormData,
};

const connector = connect(mapStateToProps, mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;

interface LoginFormProps extends PropsFromRedux {
  navigation: any;
}

async function registerAppWithFCM() {
  await messaging().registerDeviceForRemoteMessages();
}

async function requestUserPermission() {
  const settings = await messaging().requestPermission();
  if (settings) {
    // console.log('Permission settings:', settings);
  }
}

const LoginForm: React.FC<LoginFormProps> = ({
  navigation,
  userInfo,
  offline,
  authenticate,
}) => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const passwordRef = useRef<TextInput>(null);

  useEffect(() => {
    requestUserPermission();
  }, []);

 const postToken = async (token: string) => {
  try {
    // Await the promise to get the actual device ID string
    const deviceId = await DeviceInfo.getUniqueId();

    const formData = new FormData();
    formData.append("device", deviceId); // Now you're passing a string
    formData.append("token", token);
    
    await axios.post(
      `${config.apiserver}/api/v1/notifications/register-device-token`,
      formData
    );
  } catch (error) {
    console.log("token error=>", error);
  }
};

  const login = async () => {
    if (!offline.online) {
      Alert.alert(
        "Offline Alert",
        "App is offline in order to login you must have internet connection",
        [
          {
            text: "OK",
            onPress: () => {
              // console.log('OK Pressed')
            },
          },
        ],
        { cancelable: true }
      );
      return;
    }

    const formData = new FormData();
    formData.append("client_id", config.client_id);
    formData.append("client_secret", config.client_secret);
    formData.append("grant_type", "password");
    formData.append("username", username);
    formData.append("password", password);

    try {
      const data = await authenticate(formData, navigation);

      if (data) {
        const token = await messaging().getToken();
        await postToken(token);
        // navigation.replace('Home')
      }
    } catch (error) {
      console.log("something went wrong while authenticating", error);
    }
  };

  const handleForgotPassword = () => {
    if (offline.online) {
      Linking.openURL(`${config.apiserver}/user/password`);
    } else {
      alert("App is offline, you must have internet connection to reset password");
    }
  };

  const { loading, error } = userInfo;

  return (
    <View style={styles.container}>
      <TextInput
        contextMenuHidden={true}
        style={styles.input}
        placeholder="Username"
        keyboardType="email-address"
        placeholderTextColor="#BFBFBF"
        onChangeText={setUsername}
        value={username}
        onSubmitEditing={() => passwordRef.current?.focus()}
        returnKeyType="next"
      />
      <TextInput
        contextMenuHidden={true}
        ref={passwordRef}
        secureTextEntry={true}
        style={styles.input}
        placeholder="Password"
        placeholderTextColor="#BFBFBF"
        onChangeText={setPassword}
        value={password}
        onSubmitEditing={login}
        returnKeyType="done"
      />
      {error && error.length > 0 && (
        <Text numberOfLines={1} ellipsizeMode="tail" style={styles.errorTextStyle}>
          {error}
        </Text>
      )}

      {loading ? (
        <Spinner size="small" />
      ) : (
        <TouchableOpacity style={styles.buttonContainer} onPress={login}>
          <Text style={styles.buttonText}>Login</Text>
        </TouchableOpacity>
      )}

      <Text
        style={styles.forgotPasswordText}
        onPress={handleForgotPassword}
      >
        Forgot Password?
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
    justifyContent: "center",
    paddingHorizontal: 30,
  },
  input: {
    height: 40,
    borderColor: Colors.accentColor,
    borderBottomWidth: 0.5,
    marginBottom: 15,
    color: Colors.colorTextInput,
  },
  buttonContainer: {
    backgroundColor: Colors.accentColor,
    borderRadius: 5,
    height: 40,
    justifyContent: "center",
    marginTop: 10,
  },
  buttonText: {
    textAlign: "center",
    color: "#fff",
    fontWeight: "bold",
  },
  errorTextStyle: {
    fontSize: 12,
    alignSelf: "center",
    color: "red",
    marginBottom: 4,
  },
  forgotPasswordText: {
    textAlign: "right",
    padding: 4,
    textDecorationLine: "underline",
    marginVertical: 8,
    marginTop: 0,
    marginBottom: 10,
  },
});

export default connector(LoginForm);