import { CameraView, useCameraPermissions } from 'expo-camera';
import { useEffect, useState } from 'react';
import { FlatList, Image, Linking, Modal, Text, TouchableOpacity, View } from 'react-native';
import { useApp } from '../context/AppContext';
import styles from '../styles/index';

const SKU_BARCODE_TYPES = [
  'code128',
  'code39',
  'code93',
  'ean13',
  'ean8',
  'upc_a',
  'upc_e',
  'itf14',
  'codabar',
  'qr',
];

export function Scanner() {
  const {
    isScanning,
    setIsScanning,
    cameraFacing,
    setCameraFacing,
    handleBarcodeScanned,
    getOutstandingScanItems,
    masterSettings,
    themeColor,
    selectedOrder,
    localOrderPicks,
  } = useApp();

  const [permission, requestPermission] = useCameraPermissions();
  const [cameraError, setCameraError] = useState('');

  useEffect(() => {
    if (!isScanning || permission !== null) return;
    requestPermission();
  }, [isScanning, permission, requestPermission]);

  if (!isScanning) return null;

  const closeScanner = () => {
    setCameraError('');
    setIsScanning(false);
  };

  const renderPermissionPrompt = (message, actionLabel, onAction) => (
    <Modal visible={true} animationType="slide">
      <View style={styles.scannerWrap}>
        <View style={styles.scannerPermissionPanel}>
          <Text style={styles.scannerPermissionTitle}>Camera access needed</Text>
          <Text style={styles.scannerPermissionText}>{message}</Text>
          <TouchableOpacity
            style={[styles.scannerPermissionBtn, { backgroundColor: themeColor }]}
            onPress={onAction}
          >
            <Text style={styles.scannerActionBtnText}>{actionLabel}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.scannerPermissionBtn, { backgroundColor: '#e74c3c' }]}
            onPress={closeScanner}
          >
            <Text style={styles.scannerActionBtnText}>CLOSE SCANNER</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Modal>
  );

  if (!permission) {
    return renderPermissionPrompt('Checking camera permission...', 'CHECK AGAIN', requestPermission);
  }

  if (!permission.granted) {
    const canAskAgain = permission.canAskAgain !== false;
    return renderPermissionPrompt(
      canAskAgain
        ? 'Allow camera access so the app can scan item barcodes.'
        : 'Camera access is blocked. Open device settings and allow camera access for PickPack Ship.',
      canAskAgain ? 'ALLOW CAMERA' : 'OPEN SETTINGS',
      canAskAgain ? requestPermission : Linking.openSettings
    );
  }

  return (
    <Modal visible={true} animationType="slide">
      <View style={styles.scannerWrap}>
        <View style={styles.scannerTop}>
          <CameraView
            style={styles.scannerCamera}
            facing={cameraFacing}
            active={isScanning}
            barcodeScannerSettings={{ barcodeTypes: SKU_BARCODE_TYPES }}
            onBarcodeScanned={handleBarcodeScanned}
            onMountError={event => setCameraError(event?.message || 'Camera could not start.')}
          />
          {cameraError ? (
            <View style={styles.scannerCameraError}>
              <Text style={styles.scannerCameraErrorText}>{cameraError}</Text>
            </View>
          ) : null}
          <View style={styles.scannerTopOverlay}>
            <TouchableOpacity
              style={[styles.scannerActionBtn, { backgroundColor: '#007ace' }]}
              onPress={() => setCameraFacing(prev => (prev === 'back' ? 'front' : 'back'))}
            >
              <Text style={styles.scannerActionBtnText}>
                {cameraFacing === 'back' ? 'FRONT CAMERA' : 'BACK CAMERA'}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.scannerActionBtn, { backgroundColor: '#e74c3c' }]}
              onPress={closeScanner}
            >
              <Text style={styles.scannerActionBtnText}>CLOSE SCANNER</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.scannerBottom}>
          <Text style={styles.scannerListTitle}>Still to scan</Text>
          <FlatList
            data={getOutstandingScanItems()}
            keyExtractor={(item, index) => `${item.sku}-${index}`}
            ListEmptyComponent={
              <Text style={styles.scannerDoneText}>Everything is scanned for this list.</Text>
            }
            renderItem={({ item }) => {
              const currentQty = selectedOrder ? localOrderPicks[item.sku]?.qty || 0 : item.picked || 0;
              const requiredQty = parseInt(item.qty || 0);
              const remainingQty = Math.max(0, requiredQty - currentQty);

              return (
                <View style={styles.scannerItemRow}>
                  {masterSettings.showProductImages ? (
                    <Image source={{ uri: item.img }} style={styles.scannerThumb} />
                  ) : null}
                  <View style={{ flex: 1 }}>
                    <Text style={styles.scannerItemName}>{item.name}</Text>
                    <Text style={styles.scannerItemSku}>{item.sku}</Text>
                  </View>
                  <View style={styles.scannerRemainingBadge}>
                    <Text style={styles.scannerRemainingText}>{remainingQty} left</Text>
                  </View>
                </View>
              );
            }}
          />
        </View>
      </View>
    </Modal>
  );
}
