import React, { useState } from "react";
import {
  Alert,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import type { NativeStackScreenProps } from "@react-navigation/native-stack";
import { QRScanner } from "../components/QRScanner";
import { LoadingView } from "../components/LoadingView";
import { useProduct } from "../hooks/useProduct";
import { DEMO_QR_CODE } from "../config/constants";
import type { RootStackParamList } from "../navigation/types";

type Props = NativeStackScreenProps<RootStackParamList, "Scanner">;

export function ScannerScreen({ navigation }: Props) {
  const { loadByQr, loading } = useProduct();
  const [manual, setManual] = useState(DEMO_QR_CODE);

  const handleCode = async (code: string) => {
    const product = await loadByQr(code);
    if (!product) {
      Alert.alert("Producto no encontrado", `QR: ${code}`);
      return;
    }
    navigation.replace("Bottle");
  };

  if (loading) {
    return <LoadingView message="Cargando producto..." />;
  }

  return (
    <View style={styles.container}>
      <View style={styles.scanner}>
        <QRScanner onCode={handleCode} />
      </View>
      <View style={styles.manual}>
        <Text style={styles.label}>O ingresá el código</Text>
        <TextInput
          style={styles.input}
          value={manual}
          onChangeText={setManual}
          autoCapitalize="characters"
          placeholderTextColor="#6E6658"
        />
        <Pressable style={styles.btn} onPress={() => handleCode(manual.trim())}>
          <Text style={styles.btnText}>Continuar</Text>
        </Pressable>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  scanner: { flex: 1 },
  manual: {
    padding: 16,
    gap: 10,
    backgroundColor: "#1C1610",
    borderTopWidth: 1,
    borderTopColor: "#2A2218",
  },
  label: { color: "#B8AFA0", fontSize: 13 },
  input: {
    backgroundColor: "#14100C",
    color: "#FFF8EC",
    borderRadius: 10,
    paddingHorizontal: 14,
    paddingVertical: 12,
    borderWidth: 1,
    borderColor: "#2A2218",
  },
  btn: {
    backgroundColor: "#C4A35A",
    borderRadius: 10,
    paddingVertical: 12,
    alignItems: "center",
  },
  btnText: { color: "#1A140C", fontWeight: "700" },
});
