/**
 * BarcodeScanner Component
 *
 * Full-screen camera scanner for barcodes and QR codes
 */

import React, { useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Dimensions,
  ActivityIndicator,
} from 'react-native';
import { CameraView, BarcodeScanningResult } from 'expo-camera';
import { Ionicons } from '@expo/vector-icons';
import { useBarcode, BARCODE_PRESETS } from '@/hooks/useBarcode';
import { ScannedBarcode, ProductBarcode, ParsedQRData, BarcodeType } from '@/services/barcode';

const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');
const SCAN_AREA_SIZE = SCREEN_WIDTH * 0.7;

interface BarcodeScannerProps {
  // Scanner mode
  mode?: 'product' | 'qr' | 'all';
  // Custom barcode types
  barcodeTypes?: BarcodeType[];
  // Show torch toggle
  showTorch?: boolean;
  // Show scan history
  showHistory?: boolean;
  // Callbacks
  onScan?: (barcode: ScannedBarcode) => void;
  onProductScan?: (product: ProductBarcode) => void;
  onQRScan?: (data: ParsedQRData) => void;
  onClose?: () => void;
  // Styling
  overlayColor?: string;
  accentColor?: string;
}

export function BarcodeScanner({
  mode = 'product',
  barcodeTypes,
  showTorch = true,
  showHistory = false,
  onScan,
  onProductScan,
  onQRScan,
  onClose,
  overlayColor = 'rgba(0, 0, 0, 0.6)',
  accentColor = '#1e40af',
}: BarcodeScannerProps) {
  const [torchOn, setTorchOn] = useState(false);

  // Determine barcode types based on mode or custom types
  const types = barcodeTypes || BARCODE_PRESETS[mode] || BARCODE_PRESETS.all;

  const {
    hasPermission,
    canAskPermission,
    lastScan,
    scanHistory,
    requestPermission,
    handleBarcodeScan,
    clearHistory,
    barcodeTypes: scannerTypes,
  } = useBarcode({
    barcodeTypes: types,
    onScan,
    onProductScan,
    onQRScan,
  });

  const onBarcodeScanned = useCallback(
    (result: BarcodeScanningResult) => {
      handleBarcodeScan(result);
    },
    [handleBarcodeScan]
  );

  // Permission not yet determined
  if (hasPermission === null) {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" color={accentColor} />
        <Text style={styles.loadingText}>Verificando permisos...</Text>
      </View>
    );
  }

  // Permission denied
  if (!hasPermission) {
    return (
      <View style={styles.container}>
        <View style={styles.permissionContainer}>
          <Ionicons name="camera-outline" size={64} color="#9ca3af" />
          <Text style={styles.permissionTitle}>Acceso a Cámara Requerido</Text>
          <Text style={styles.permissionText}>
            Necesitamos acceso a tu cámara para escanear códigos de barras.
          </Text>
          {canAskPermission ? (
            <TouchableOpacity
              style={[styles.permissionButton, { backgroundColor: accentColor }]}
              onPress={requestPermission}
            >
              <Text style={styles.permissionButtonText}>Permitir Acceso</Text>
            </TouchableOpacity>
          ) : (
            <Text style={styles.permissionNote}>
              Por favor, habilita el acceso a la cámara en la configuración del dispositivo.
            </Text>
          )}
          {onClose && (
            <TouchableOpacity style={styles.closeButtonAlt} onPress={onClose}>
              <Text style={styles.closeButtonAltText}>Cancelar</Text>
            </TouchableOpacity>
          )}
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <CameraView
        style={StyleSheet.absoluteFill}
        facing="back"
        enableTorch={torchOn}
        barcodeScannerSettings={{
          barcodeTypes: scannerTypes as any[],
        }}
        onBarcodeScanned={onBarcodeScanned}
      />

      {/* Overlay */}
      <View style={styles.overlay}>
        {/* Top overlay */}
        <View style={[styles.overlaySection, { backgroundColor: overlayColor }]}>
          {/* Header */}
          <View style={styles.header}>
            {onClose && (
              <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                <Ionicons name="close" size={28} color="#ffffff" />
              </TouchableOpacity>
            )}
            <Text style={styles.headerTitle}>
              {mode === 'qr' ? 'Escanear QR' : 'Escanear Código'}
            </Text>
            {showTorch && (
              <TouchableOpacity
                style={[styles.torchButton, torchOn && styles.torchButtonActive]}
                onPress={() => setTorchOn(!torchOn)}
              >
                <Ionicons
                  name={torchOn ? 'flash' : 'flash-outline'}
                  size={24}
                  color="#ffffff"
                />
              </TouchableOpacity>
            )}
          </View>
        </View>

        {/* Middle section with scan area */}
        <View style={styles.middleSection}>
          <View style={[styles.sideOverlay, { backgroundColor: overlayColor }]} />
          <View style={styles.scanArea}>
            {/* Corner markers */}
            <View style={[styles.corner, styles.cornerTL, { borderColor: accentColor }]} />
            <View style={[styles.corner, styles.cornerTR, { borderColor: accentColor }]} />
            <View style={[styles.corner, styles.cornerBL, { borderColor: accentColor }]} />
            <View style={[styles.corner, styles.cornerBR, { borderColor: accentColor }]} />

            {/* Scan line animation placeholder */}
            <View style={[styles.scanLine, { backgroundColor: accentColor }]} />
          </View>
          <View style={[styles.sideOverlay, { backgroundColor: overlayColor }]} />
        </View>

        {/* Bottom overlay */}
        <View style={[styles.overlaySection, { backgroundColor: overlayColor }]}>
          <Text style={styles.instructions}>
            {mode === 'qr'
              ? 'Apunta al código QR para escanearlo'
              : 'Apunta al código de barras para escanearlo'}
          </Text>

          {/* Last scan result */}
          {lastScan && (
            <View style={styles.lastScanContainer}>
              <View style={styles.lastScanBadge}>
                <Ionicons name="checkmark-circle" size={20} color="#059669" />
                <Text style={styles.lastScanType}>{lastScan.type.toUpperCase()}</Text>
              </View>
              <Text style={styles.lastScanData} numberOfLines={1}>
                {lastScan.data}
              </Text>
            </View>
          )}

          {/* Scan history */}
          {showHistory && scanHistory.length > 0 && (
            <View style={styles.historyContainer}>
              <View style={styles.historyHeader}>
                <Text style={styles.historyTitle}>
                  Historial ({scanHistory.length})
                </Text>
                <TouchableOpacity onPress={clearHistory}>
                  <Text style={styles.clearButton}>Limpiar</Text>
                </TouchableOpacity>
              </View>
              {scanHistory.slice(0, 3).map((scan, index) => (
                <View key={`${scan.timestamp}-${index}`} style={styles.historyItem}>
                  <Text style={styles.historyItemType}>{scan.type}</Text>
                  <Text style={styles.historyItemData} numberOfLines={1}>
                    {scan.data}
                  </Text>
                </View>
              ))}
            </View>
          )}
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000000',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    color: '#ffffff',
    marginTop: 16,
    fontSize: 16,
  },
  permissionContainer: {
    padding: 32,
    alignItems: 'center',
  },
  permissionTitle: {
    color: '#ffffff',
    fontSize: 20,
    fontWeight: '600',
    marginTop: 16,
    marginBottom: 8,
  },
  permissionText: {
    color: '#9ca3af',
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 24,
  },
  permissionButton: {
    paddingHorizontal: 32,
    paddingVertical: 14,
    borderRadius: 8,
    marginBottom: 16,
  },
  permissionButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
  permissionNote: {
    color: '#9ca3af',
    fontSize: 13,
    textAlign: 'center',
  },
  closeButtonAlt: {
    marginTop: 16,
    padding: 12,
  },
  closeButtonAltText: {
    color: '#9ca3af',
    fontSize: 16,
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
  },
  overlaySection: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 24,
  },
  header: {
    position: 'absolute',
    top: 60,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
  },
  closeButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerTitle: {
    color: '#ffffff',
    fontSize: 18,
    fontWeight: '600',
  },
  torchButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  torchButtonActive: {
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
  },
  middleSection: {
    flexDirection: 'row',
    height: SCAN_AREA_SIZE,
  },
  sideOverlay: {
    flex: 1,
  },
  scanArea: {
    width: SCAN_AREA_SIZE,
    height: SCAN_AREA_SIZE,
    position: 'relative',
  },
  corner: {
    position: 'absolute',
    width: 30,
    height: 30,
    borderWidth: 3,
  },
  cornerTL: {
    top: 0,
    left: 0,
    borderBottomWidth: 0,
    borderRightWidth: 0,
  },
  cornerTR: {
    top: 0,
    right: 0,
    borderBottomWidth: 0,
    borderLeftWidth: 0,
  },
  cornerBL: {
    bottom: 0,
    left: 0,
    borderTopWidth: 0,
    borderRightWidth: 0,
  },
  cornerBR: {
    bottom: 0,
    right: 0,
    borderTopWidth: 0,
    borderLeftWidth: 0,
  },
  scanLine: {
    position: 'absolute',
    left: 20,
    right: 20,
    height: 2,
    top: '50%',
    opacity: 0.8,
  },
  instructions: {
    color: '#ffffff',
    fontSize: 14,
    textAlign: 'center',
    marginTop: 24,
  },
  lastScanContainer: {
    backgroundColor: 'rgba(255, 255, 255, 0.15)',
    borderRadius: 12,
    padding: 16,
    marginTop: 16,
    width: '100%',
    maxWidth: 320,
  },
  lastScanBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  lastScanType: {
    color: '#059669',
    fontSize: 12,
    fontWeight: '600',
    marginLeft: 6,
  },
  lastScanData: {
    color: '#ffffff',
    fontSize: 14,
  },
  historyContainer: {
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 12,
    padding: 12,
    marginTop: 12,
    width: '100%',
    maxWidth: 320,
  },
  historyHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  historyTitle: {
    color: '#9ca3af',
    fontSize: 12,
    fontWeight: '500',
  },
  clearButton: {
    color: '#60a5fa',
    fontSize: 12,
  },
  historyItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
    borderTopWidth: 1,
    borderTopColor: 'rgba(255, 255, 255, 0.1)',
  },
  historyItemType: {
    color: '#9ca3af',
    fontSize: 11,
    width: 60,
  },
  historyItemData: {
    color: '#d1d5db',
    fontSize: 12,
    flex: 1,
  },
});

export default BarcodeScanner;
