// components/QRCodeScannerKit.js
import React, { useEffect } from 'react';
import {
  View,
  TouchableOpacity,
  Text,
  StyleSheet,
  BackHandler,
  Modal,
} from 'react-native';
import { Camera } from 'react-native-camera-kit';
import { Ionicons } from './icons'; // tumhara icon wrapper

function QRCodeScannerKit({ visible, onClose, onQRScanned }) {
  // 🔙 Android hardware back button handle
  useEffect(() => {
    if (!visible) return;

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      () => {
        onClose && onClose();
        return true;
      }
    );

    return () => backHandler.remove();
  }, [visible, onClose]);

  if (!visible) return null;

  const handleReadCode = (event) => {
    const value = event?.nativeEvent?.codeStringValue ?? '';
    console.log('QR Value:', value);
    if (!value) return;

    onQRScanned && onQRScanned(value);
  };

  return (
    <Modal
      visible={visible}
      animationType="slide"
      transparent={false}
      onRequestClose={onClose}
    >
      <View style={styles.container}>
        <Camera
          style={styles.camera}
          scanBarcode={true}
          onReadCode={handleReadCode}
          showFrame={true}
          laserColor="red"
          frameColor="white"
        />

        {/* Top overlay bar with close button */}
        <View style={styles.topBar}>
          <TouchableOpacity onPress={onClose} style={styles.closeBtn}>
            <Ionicons name="close" size={26} color="#fff" />
          </TouchableOpacity>
          <Text style={styles.title}>Scan QR Code</Text>
        </View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  camera: {
    flex: 1,
  },
  topBar: {
    position: 'absolute',
    top: 40,
    left: 0,
    right: 0,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
  },
  closeBtn: {
    padding: 8,
    marginRight: 12,
  },
  title: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
});

export default QRCodeScannerKit;
