import { View, Text, Button, StyleSheet, Animated } from "react-native";
import { useQRScanner } from "../src/hooks/useQRScanner";
import { CameraView } from "expo-camera/next";
import { BarCodeScanningResult } from "expo-camera";
import { useEffect, useRef } from "react";

export default function ScanScreen() {
  const { hasPermission, getPermission, scanning, onQRScanned, qrData } =
    useQRScanner();

  const qrAnimation = useRef(new Animated.Value(0)).current;

  const startAnimation = () => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(qrAnimation, {
          toValue: 1,
          duration: 1000,
          useNativeDriver: true,
        }),
        Animated.timing(qrAnimation, {
          toValue: 0,
          duration: 1000,
          useNativeDriver: true,
        }),
      ])
    ).start();
  };

  useEffect(() => {
    return () => {
      qrAnimation.stopAnimation();
    };
  }, []);

  if (!hasPermission) {
    return (
      <View>
        <Text>No permission</Text>
        <Button title="Request permission" onPress={getPermission} />
      </View>
    );
  }

  if (!scanning) {
    return (
      <View>
        <Text>{qrData}</Text>
      </View>
    );
  }

  startAnimation();

  return (
    <View style={styles.container}>
      <View style={{borderRadius: 10, overflow: 'hidden'}}>
        <CameraView
          style={styles.camera}
          barcodeScannerSettings={{
            barcodeTypes: ["qr"],
          }}
          onBarcodeScanned={onQRScanned}
          zoom={0.5}
        >
          <View style={styles.square}>
            <Animated.View
              style={{
                width: "100%",
                height: 2,
                borderColor: "white",
                borderWidth: 1,
                borderRadius: 10,
                transform: [
                  {
                    translateY: qrAnimation.interpolate({
                      inputRange: [0, 1],
                      outputRange: [-10, 200],
                    }),
                  },
                ],
              }}
            />
          </View>
        </CameraView>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  camera: {
    width: 250,
    aspectRatio: 1,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
  },
  square: {
    width: 200,
    aspectRatio: 1,
    borderWidth: 2,
    borderColor: "white",
    borderRadius: 10,
    overflow: "hidden",
    backgroundColor: "rgba(0,0,0,0.2)",
  },
});
