import React, { useCallback, useRef, useState } from "react";
import {
  ActivityIndicator,
  Linking,
  Pressable,
  StyleSheet,
  Text,
  View,
} from "react-native";
import { CameraView as ExpoCameraView, useCameraPermissions } from "expo-camera";
import { CameraView } from "./CameraView";

type Props = {
  onCapture: (uri: string) => void;
  busy?: boolean;
};

export function LabelCamera({ onCapture, busy = false }: Props) {
  const cameraRef = useRef<ExpoCameraView>(null);
  const [permission, requestPermission] = useCameraPermissions();
  const [capturing, setCapturing] = useState(false);

  const takePhoto = useCallback(async () => {
    if (busy || capturing || !cameraRef.current) return;
    setCapturing(true);
    try {
      const photo = await cameraRef.current.takePictureAsync({
        quality: 0.7,
        skipProcessing: true,
      });
      if (photo?.uri) onCapture(photo.uri);
    } finally {
      setCapturing(false);
    }
  }, [busy, capturing, onCapture]);

  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 fotografiar la etiqueta.
        </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>
    );
  }

  const disabled = busy || capturing;

  return (
    <CameraView ref={cameraRef} enableBarcode={false}>
      <View style={styles.overlay} pointerEvents="box-none">
        <View style={styles.frame} />
        <Text style={styles.hint}>Apuntá a la etiqueta de la botella</Text>
        <Pressable
          style={[styles.shutter, disabled && styles.shutterDisabled]}
          onPress={() => void takePhoto()}
          disabled={disabled}
        >
          {disabled ? (
            <ActivityIndicator color="#1A140C" />
          ) : (
            <Text style={styles.shutterText}>Capturar</Text>
          )}
        </Pressable>
      </View>
    </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",
    paddingBottom: 48,
  },
  frame: {
    width: 260,
    height: 340,
    borderWidth: 2,
    borderColor: "#C4A35A",
    borderRadius: 16,
    backgroundColor: "transparent",
  },
  hint: { marginTop: 20, color: "#fff", fontSize: 16 },
  shutter: {
    position: "absolute",
    bottom: 36,
    alignSelf: "center",
    backgroundColor: "#C4A35A",
    borderRadius: 28,
    minWidth: 140,
    paddingHorizontal: 28,
    paddingVertical: 16,
    alignItems: "center",
  },
  shutterDisabled: { opacity: 0.7 },
  shutterText: { color: "#1A140C", fontWeight: "800", fontSize: 16 },
});
