import { useStartTestMutation } from "@/api/userTests";
import { Button, ButtonText } from "@/components/ui/button";
import { ThemedText } from "@/components/ui/themed-text";
import getErrorAxiosMessage from "@/utils/get-error-axios-message";
import { router, Stack, useFocusEffect } from "expo-router";
import { useCallback, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { useToast } from "react-native-toast-notifications";
import {
  Camera,
  useCameraDevice,
  useCameraPermission,
  useCodeScanner,
} from "react-native-vision-camera";

const QrScreen = () => {
  const device = useCameraDevice("back");
  const { hasPermission, requestPermission } = useCameraPermission();
  const toast = useToast();
  const [scanned, setScanned] = useState(false);

  const { mutate, isPending } = useStartTestMutation();

  useFocusEffect(
    useCallback(() => {
      setScanned(false);
    }, [])
  );

  const handleStartTest = (id: number) => {
    mutate(
      {
        test_id: id,
      },
      {
        onSuccess: (data) => {
          router.push(`/user-tests/doing/${data.id}`);
        },
        onError: (error) => {
          toast.show(getErrorAxiosMessage(error), { type: "danger" });
        },
      }
    );
  };

  const codeScanner = useCodeScanner({
    codeTypes: ["qr", "ean-13"],
    onCodeScanned: (codes) => {
      if (scanned) return;
      if (!codes || codes.length === 0) return;

      const scannedValue = codes[0].value;
      if (scannedValue) {
        const id = parseInt(scannedValue, 10);
        setScanned(true);
        toast.show("Going to test", { type: "normal" });
        router.push(`/tests/${id}`);
        // handleStartTest(id);
      } else {
        toast.show("Invalid QR code", { type: "warning" });
      }
    },
  });

  if (!hasPermission) {
    return (
      <View style={styles.center}>
        <Stack.Screen options={{ title: "Scan QR Code" }} />
        <ThemedText>No camera permission</ThemedText>
        <Button onPress={requestPermission} className="mt-2">
          <ButtonText>Grant Permission</ButtonText>
        </Button>
      </View>
    );
  }
  if (!device) {
    return (
      <View style={styles.center}>
        <ThemedText>No camera device found</ThemedText>
      </View>
    );
  }
  return (
    <>
      <Stack.Screen options={{ title: "Scan QR Code" }} />
      <Camera
        codeScanner={codeScanner}
        style={StyleSheet.absoluteFill}
        device={device}
        isActive={true}
      />
    </>
  );
};

const styles = StyleSheet.create({
  center: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});

export default QrScreen;
