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 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 () => {
    await signIn({ email, password });
    if (!isError) {
      Toast.show({
        type: "success",
        text1: "Login successful!",
      });
    } else {
      Toast.show({
        type: "error",
        text1: "Error logging in",
        text2: `${error}`,
      });
    }
  };

  return (
    <SafeAreaView style={{ flex: 1, alignItems: isTablet ? "center" : undefined}}>
      <KeyboardAwareScrollView
        contentContainerStyle={{ flexGrow: 1 }}
        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%" }}
            contentContainerStyle={{ justifyContent: "center" }}
            keyboardVerticalOffset={50}
            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 }}>{`${
              error?.toString()?.split("]")?.[1]
            }`}</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..."}
              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;
