import { SafeAreaView } from "react-native-safe-area-context";
import {
  Button,
  Colors,
  Dialog,
  LoaderScreen,
  Text,
  View,
} from "react-native-ui-lib";
import React, { useCallback, useEffect, useState } from "react";
import { useRouter } from "expo-router";
import QRIcon from "@/assets/svgs/QRIcon";
import { Camera, CameraView } from "expo-camera";
import { useLoginWithQrCode } from "@/hooks/firebase/useLoginWithQrCode";
import { useAuthContext } from "@/contexts/AuthContext";
import debounce from "debounce";
import * as Device from "expo-device";
import { DeviceType } from "expo-device";
import { Dimensions } from "react-native";

export default function Screen() {
  const router = useRouter();
  const { setRedirectOverride } = useAuthContext();
  const [hasPermission, setHasPermission] = useState<boolean | null>(null);
  const [showCameraDialog, setShowCameraDialog] = useState<boolean>(false);

  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: signInWithQrCode, isLoading } = useLoginWithQrCode();

  const debouncedRouterReplace = useCallback(
    debounce(() => {
      router.push("/(unauth)/cal_sync");
    }, 300),
    []
  );

  const handleQrCodeScanned = async ({ data }: { data: string }) => {
    setShowCameraDialog(false);
    setRedirectOverride(true);
    try {
      await signInWithQrCode({ userId: data });
      debouncedRouterReplace();
    } catch (err) {
      console.log(err);
    }
  };

  const getCameraPermissions = async (callback: () => void) => {
    const { status } = await Camera.requestCameraPermissionsAsync();
    setHasPermission(status === "granted");
    if (status === "granted") {
      callback();
    }
  };

  const handleOpenQrCodeDialog = () => {
    getCameraPermissions(() => setShowCameraDialog(true));
  };

  return (
    <SafeAreaView style={{ flex: 1, alignItems: "center" }}>
      <View
        style={{
          flex: 1,
          padding: 21,
          paddingBottom: 45,
          paddingTop: isLoading ? "20%" : getTopPadding(),
          width: isTablet ? 629 : '100%'
        }}
      >
        <View center>
          <Text style={{ fontSize: 30, fontFamily: "Manrope_600SemiBold" }}>
            Get started with Cally
          </Text>
        </View>

        <View width={"100%"} gap-30>
          <View>
            <Button
              label="Scan QR Code"
              marginT-50
              labelStyle={{
                fontFamily: "PlusJakartaSans_400Regular",
                fontSize: 16,
                marginLeft: 10,
              }}
              iconSource={() => <QRIcon color={"#07B8C7"} />}
              onPress={handleOpenQrCodeDialog}
              style={{ height: 50 }}
              color={Colors.black}
              backgroundColor={Colors.white}
            />
            {/*    GOOGLE LOGIN HERE   */}
          </View>

          <View row center gap-20>
            <View flexG style={{ backgroundColor: "#E2E2E2", height: 2 }} />
            <Text
              style={{
                fontSize: 16,
                fontFamily: "PlusJakartaSans_300Light",
                color: "#7A7A7A",
              }}
            >
              or
            </Text>
            <View flexG style={{ backgroundColor: "#E2E2E2", height: 2 }} />
          </View>

          <View>
            <Button
              label="Continue with Email"
              labelStyle={{
                fontFamily: "PlusJakartaSans_400Regular",
                fontSize: 16,
                marginLeft: 10,
              }}
              onPress={() => router.push("/(unauth)/sign_up")}
              style={{
                height: 50,
                borderStyle: "solid",
                borderColor: "#E2E2E2",
                borderWidth: 2,
              }}
              color={Colors.black}
              backgroundColor={"transparent"}
            />
          </View>
        </View>

        {isTablet ? (
          <View marginT-30 />
        ) : (
          <View flexG />
        )}

        <View row centerH gap-5>
          <Text
            style={{
              fontFamily: "PlusJakartaSans_300Light",
              fontSize: 16,
              color: "#484848",
            }}
            center
          >
            Already have an account?
          </Text>

          <Button
            label="Log in"
            link
            onPress={() => router.push("/(unauth)/sign_in")}
            labelStyle={[
              {
                fontFamily: "PlusJakartaSans_500Medium",
                fontSize: 16,
                color: "#919191",
              },
              { fontSize: 16, textDecorationLine: "none", color: "#fd1775" },
            ]}
          />
        </View>
      </View>

      {/*    Legacy, move into separate component   */}
      {/* Camera Dialog */}
      <Dialog
        visible={showCameraDialog}
        onDismiss={() => setShowCameraDialog(false)}
        bottom
        width="100%"
        height="70%"
        containerStyle={{ padding: 15, backgroundColor: "white" }}
      >
        <Text center style={{ fontSize: 16 }} marginB-15>
          Scan a QR code presented from your family member of provider.
        </Text>
        {hasPermission === null ? (
          <Text>Requesting camera permissions...</Text>
        ) : !hasPermission ? (
          <Text>No access to camera</Text>
        ) : (
          <CameraView
            style={{ flex: 1, borderRadius: 15 }}
            onBarcodeScanned={handleQrCodeScanned}
            barcodeScannerSettings={{
              barcodeTypes: ["qr"],
            }}
          />
        )}
        <Button
          label="Cancel"
          onPress={() => setShowCameraDialog(false)}
          backgroundColor="#fd1775"
          style={{ margin: 10, marginBottom: 30 }}
        />
      </Dialog>

      {isLoading && (
        <LoaderScreen
          overlay
          message={"Signing in..."}
          backgroundColor={Colors.white}
          color={Colors.grey40}
        />
      )}
    </SafeAreaView>
  );
}
