import {Button, ButtonSize, Dialog, Text, TextField, View} from "react-native-ui-lib";
import React, {useEffect, useState} from "react";
import {useSignIn} from "@/hooks/firebase/useSignIn";
import {StyleSheet} from "react-native";
import Toast from 'react-native-toast-message';
import {useLoginWithQrCode} from "@/hooks/firebase/useLoginWithQrCode";
import {Camera, CameraView} from 'expo-camera';
import {BarCodeScanner} from "expo-barcode-scanner";

const SignInPage = ({setTab}: { setTab:  React.Dispatch<React.SetStateAction<"register" | "login" | "reset-password">> }) => {
    const [email, setEmail] = useState<string>("");
    const [password, setPassword] = useState<string>("");
    const [hasPermission, setHasPermission] = useState<boolean | null>(null);
    const [scanned, setScanned] = useState<boolean>(false);
    const [showCameraDialog, setShowCameraDialog] = useState<boolean>(false);

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

    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}`
            });
        }
    };

    const handleQrCodeScanned = async ({ data }: { data: string }) => {
        setShowCameraDialog(false);
        try {
            await signInWithQrCode({ userId: data });
            Toast.show({
                type: "success",
                text1: "Login successful with QR code!"
            });
        } catch (err) {
            Toast.show({
                type: "error",
                text1: "Error logging in with QR code",
                text2: `${err}`
            });
        }
    };

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

    return (
        <View padding-10 centerV height={"100%"}>
            <TextField
                placeholder="Email"
                value={email}
                onChangeText={setEmail}
                style={styles.textfield}
            />
            <TextField
                placeholder="Password"
                value={password}
                onChangeText={setPassword}
                secureTextEntry
                style={styles.textfield}
            />
            <Button
                label="Login"
                onPress={handleSignIn}
                style={{marginBottom: 20}}
                backgroundColor="#fd1775"
            />
            <Button
                label="Login with a QR Code"
                onPress={() => {
                    getCameraPermissions(() => setShowCameraDialog(true));
                    }
            }
                style={{marginBottom: 20}}
                backgroundColor="#fd1775"
            />
            {isError && <Text center style={{marginBottom: 20}}>{`${error}`}</Text>}

            <View row centerH marginB-5 gap-5>
                <Text text70>
                    Don't have an account?
                </Text>
                <Button
                    onPress={() => setTab("register")}
                    label="Sign Up"
                    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={() => setTab("reset-password")}
                    label="Reset password"
                    link
                    size={ButtonSize.xSmall}
                    padding-0
                    margin-0
                    text70
                    left
                    color="#fd1775"
                />
            </View>

            {/* Camera Dialog */}
            <Dialog
                visible={showCameraDialog}
                onDismiss={() => setShowCameraDialog(false)}
                bottom
                width="100%"
                height="70%"
                containerStyle={{ padding: 0 }}
            >
                {hasPermission === null ? (
                    <Text>Requesting camera permissions...</Text>
                ) : !hasPermission ? (
                    <Text>No access to camera</Text>
                ) : (
                    <CameraView
                        style={{ flex: 1 }}
                        onBarcodeScanned={handleQrCodeScanned}
                        barcodeScannerSettings={{
                            barcodeTypes: ["qr"],
                        }}
                    />
                )}
                <Button
                    label="Cancel"
                    onPress={() => setShowCameraDialog(false)}
                    backgroundColor="#fd1775"
                    style={{ margin: 10 }}
                />
            </Dialog>
        </View>
    );
};

const styles = StyleSheet.create({
    textfield: {
        backgroundColor: "white",
        marginVertical: 10,
        padding: 30,
        height: 45,
        borderRadius: 50,
    },
});

export default SignInPage;
