import {
  Button,
  ButtonSize,
  Colors,
  KeyboardAwareScrollView,
  LoaderScreen,
  Text,
  TextField,
  TextFieldRef,
  View,
} from "react-native-ui-lib";
import React, { useEffect, useRef, useState } from "react";
import { useSignIn } from "@/hooks/firebase/useSignIn";
import {
  Dimensions,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
} from "react-native";
import Toast from "react-native-toast-message";
import KeyboardManager from "react-native-keyboard-manager";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import * as Device from "expo-device";
import { DeviceType } from "expo-device";

if (Platform.OS === "ios") KeyboardManager.setEnableAutoToolbar(true);

const firebaseAuthErrors: { [key: string]: string } = {
    'auth/invalid-email': 'Please enter a valid email address',
    'auth/user-disabled': 'This account has been disabled. Please contact support',
    'auth/user-not-found': 'No account found with this email address',
    'auth/wrong-password': 'Incorrect password. Please try again',
    'auth/email-already-in-use': 'An account with this email already exists',
    'auth/operation-not-allowed': 'This login method is not enabled. Please contact support',
    'auth/weak-password': 'Password should be at least 6 characters',
    'auth/invalid-credential': 'Invalid login credentials. Please try again',
    'auth/network-request-failed': 'Network error. Please check your internet connection',
    'auth/too-many-requests': 'Too many failed login attempts. Please try again later',
    'auth/invalid-login-credentials': 'Invalid email or password. Please try again',
};

const SignInPage = () => {
  const [email, setEmail] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const passwordRef = useRef<TextFieldRef>(null);

  const isTablet: boolean = Device.deviceType === DeviceType.TABLET;
  const [isPortrait, setIsPortrait] = useState(() => {
    const dim = Dimensions.get("screen");
    return dim.height >= dim.width;
  });

  useEffect(() => {
    const subscription = Dimensions.addEventListener("change", ({ screen }) => {
      setIsPortrait(screen.height >= screen.width);
    });

    return () => subscription.remove();
  }, []);

  const getTopPadding = () => {
    if (Device.deviceType === DeviceType.TABLET) {
      return isPortrait ? "50%" : "15%";
    }
    return "20%"; // non-tablet case, regardless of orientation
  };

  const { mutateAsync: signIn, error, isError, isLoading } = useSignIn();

  const router = useRouter();

    const handleSignIn = async () => {
        try {
            await signIn({ email, password });
            Toast.show({
                type: "success",
                text1: "Login successful!",
            });
        } catch (error: any) {
            const errorCode = error?.code || 'unknown-error';

            const errorMessage = firebaseAuthErrors[errorCode] || 'An unexpected error occurred. Please try again';

            Toast.show({
                type: "error",
                text1: "Error logging in",
                text2: errorMessage,
            });
        }
    };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <KeyboardAwareScrollView
        contentContainerStyle={{
          flexGrow: 1,
          alignItems: isTablet ? "center" : undefined,
        }}
        enableOnAndroid
      >
        <View
          style={{
            flex: 1,
            padding: 21,
            paddingBottom: 45,
            paddingTop: isLoading ? "20%" : getTopPadding(),
            width: isLoading ? "100%" : isTablet ? 629 : undefined,
          }}
        >
          <View gap-13 width={"100%"} marginB-20>
            <Text style={{ fontSize: 40, fontFamily: "Manrope_600SemiBold" }}>
              Jump back into Cally
            </Text>
            <Text color={"#919191"} style={{ fontSize: 20 }}>
              Please enter your details.
            </Text>
          </View>

          <KeyboardAvoidingView
            style={{ width: "100%", flex: 1 }}
            contentContainerStyle={{ justifyContent: "center" }}
            keyboardVerticalOffset={Platform.OS === "ios" ? 50 : 200}
            behavior={Platform.OS === "ios" ? "padding" : "height"}
          >
            <TextField
              placeholder="Email"
              keyboardType={"email-address"}
              returnKeyType={"next"}
              textContentType={"emailAddress"}
              defaultValue={email}
              onChangeText={setEmail}
              style={styles.textfield}
              autoComplete={"email"}
              autoCorrect={false}
              onSubmitEditing={() => {
                // Move focus to the description field
                passwordRef.current?.focus();
              }}
            />
            <TextField
              ref={passwordRef}
              placeholder="Password"
              textContentType={"oneTimeCode"}
              value={password}
              onChangeText={setPassword}
              secureTextEntry
              style={styles.textfield}
              autoCorrect={false}
            />
          </KeyboardAvoidingView>

          {isTablet ? <View /> : <View flexG />}

          <Button
            label="Log in"
            marginT-50
            labelStyle={{
              fontFamily: "PlusJakartaSans_600SemiBold",
              fontSize: 16,
            }}
            onPress={handleSignIn}
            style={{ marginBottom: 20, height: 50 }}
            backgroundColor="#fd1775"
          />

            {isError && (
                <Text center style={{ marginBottom: 20 }}>
                    {firebaseAuthErrors[error?.code] || 'An unexpected error occurred. Please try again'}
                </Text>
            )}

          <View row centerH marginB-5 gap-5>
            <Text style={styles.jakartaLight}>Don't have an account?</Text>
            <Button
              onPress={() => router.replace("/(unauth)/sign_up")}
              label="Sign Up"
              labelStyle={[
                styles.jakartaMedium,
                { textDecorationLine: "none", color: "#fd1575" },
              ]}
              link
              size={ButtonSize.xSmall}
              padding-0
              margin-0
              text70
              left
              color="#fd1775"
            />
          </View>

          {/*<View row centerH marginB-5 gap-5>*/}
          {/*    <Text text70>Forgot your password?</Text>*/}
          {/*    <Button*/}
          {/*        onPress={() => router.replace("/(unauth)/sign_up")}*/}
          {/*        label="Reset password"*/}
          {/*        labelStyle={[*/}
          {/*            styles.jakartaMedium,*/}
          {/*            {textDecorationLine: "none", color: "#fd1575"},*/}
          {/*        ]}*/}
          {/*        link*/}
          {/*        size={ButtonSize.xSmall}*/}
          {/*        padding-0*/}
          {/*        margin-0*/}
          {/*        text70*/}
          {/*        left*/}
          {/*        avoidInnerPadding*/}
          {/*        color="#fd1775"*/}
          {/*    />*/}
          {/*</View>*/}

          {isLoading && (
            <LoaderScreen
              overlay
              message={"Signing in..."}
              containerStyle={{ width: Dimensions.get('screen').width }}
              backgroundColor={Colors.white}
              color={Colors.grey40}
            />
          )}
        </View>
      </KeyboardAwareScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  textfield: {
    backgroundColor: "white",
    marginVertical: 10,
    padding: 30,
    height: 45,
    borderRadius: 50,
    fontFamily: "PlusJakartaSans_300Light",
  },
  jakartaLight: {
    fontFamily: "PlusJakartaSans_300Light",
    fontSize: 16,
    color: "#484848",
  },
  jakartaMedium: {
    fontFamily: "PlusJakartaSans_500Medium",
    fontSize: 16,
    color: "#919191",
    textDecorationLine: "underline",
  },
});

export default SignInPage;
