import React from "react";
import { Linking, Pressable, StyleSheet, Text, View } from "react-native";
import { useCameraPermissions } from "expo-camera";
import { CameraView } from "./CameraView";
import { useQRCode } from "../hooks/useQRCode";

type Props = {
  onCode: (code: string) => void;
};

export function QRScanner({ onCode }: Props) {
  const [permission, requestPermission] = useCameraPermissions();
  const { scanned, onScan, reset } = useQRCode();

  if (!permission) {
    return (
      <View style={styles.center}>
        <Text style={styles.text}>Preparando cámara...</Text>
      </View>
    );
  }

  if (!permission.granted) {
    return (
      <View style={styles.center}>
        <Text style={styles.title}>Permiso de cámara</Text>
        <Text style={styles.text}>
          Bottle AI necesita la cámara para escanear el QR de la botella.
        </Text>
        {permission.canAskAgain ? (
          <Pressable style={styles.btn} onPress={() => void requestPermission()}>
            <Text style={styles.btnText}>Permitir cámara</Text>
          </Pressable>
        ) : (
          <>
            <Text style={styles.text}>
              El permiso está bloqueado. Activalo en Ajustes de la app.
            </Text>
            <Pressable style={styles.btn} onPress={() => void Linking.openSettings()}>
              <Text style={styles.btnText}>Abrir Ajustes</Text>
            </Pressable>
          </>
        )}
      </View>
    );
  }

  return (
    <CameraView
      onBarcodeScanned={(data) => {
        const code = onScan(data);
        if (code) onCode(code);
      }}
    >
      <View style={styles.overlay} pointerEvents="none">
        <View style={styles.frame} />
        <Text style={styles.hint}>
          {scanned ? "Código detectado" : "Apuntá al QR de la botella"}
        </Text>
      </View>
      {scanned ? (
        <Text style={styles.reset} onPress={reset}>
          Escanear otro
        </Text>
      ) : null}
    </CameraView>
  );
}

const styles = StyleSheet.create({
  center: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#111",
    paddingHorizontal: 28,
    gap: 14,
  },
  title: { color: "#C4A35A", fontSize: 20, fontWeight: "700", textAlign: "center" },
  text: { color: "#fff", textAlign: "center", lineHeight: 22 },
  btn: {
    marginTop: 8,
    backgroundColor: "#C4A35A",
    borderRadius: 12,
    paddingHorizontal: 20,
    paddingVertical: 12,
  },
  btnText: { color: "#1A140C", fontWeight: "700", fontSize: 16 },
  overlay: { flex: 1, alignItems: "center", justifyContent: "center" },
  frame: {
    width: 240,
    height: 240,
    borderWidth: 2,
    borderColor: "#C4A35A",
    borderRadius: 16,
    backgroundColor: "transparent",
  },
  hint: { marginTop: 20, color: "#fff", fontSize: 16 },
  reset: {
    position: "absolute",
    bottom: 40,
    alignSelf: "center",
    color: "#C4A35A",
    fontSize: 16,
  },
});
