import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Alert, useWindowDimensions, ScrollView } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import * as ImagePicker from 'expo-image-picker';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius, shadows } from '../../constants/theme';

const TABLET_MIN_WIDTH = 768;

export default function ScanTabScreen() {
  const router = useRouter();
  const { width } = useWindowDimensions();
  const isTablet = width >= TABLET_MIN_WIDTH;
  const { colors } = useThemeContext();
  const [manualNumber, setManualNumber] = useState('');
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  const handleTakePhoto = async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert(
        'Permiso requerido',
        'Necesitamos acceso a la cámara para tomar fotos del dispositivo.'
      );
      return;
    }

    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      quality: 0.8,
    });

    if (!result.canceled && result.assets[0]) {
      setSelectedImage(result.assets[0].uri);
    }
  };

  const handleSelectFromGallery = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert(
        'Permiso requerido',
        'Necesitamos acceso a la galería para seleccionar fotos.'
      );
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      quality: 0.8,
    });

    if (!result.canceled && result.assets[0]) {
      setSelectedImage(result.assets[0].uri);
    }
  };

  const handleManualSubmit = () => {
    const trimmed = manualNumber.trim();
    if (trimmed.length === 0) {
      Alert.alert('Campo requerido', 'Por favor, introduce el número de la tarjeta.');
      return;
    }
    router.push(`/medicine/${trimmed}`);
  };

  return (
    <ScrollView
      style={[styles.scrollContainer, { backgroundColor: colors.background }]}
      contentContainerStyle={styles.scrollContent}
    >
      <View style={[styles.content, isTablet && styles.contentTablet]}>
        <View style={[styles.iconContainer, isTablet && styles.iconContainerTablet, { backgroundColor: colors.primaryContainer }]}>
          <Ionicons name="scan" size={isTablet ? 80 : 64} color={colors.scanButton} />
        </View>
        <Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Escanear TSI</Text>
        <Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
          Escanea el código de barras de tu tarjeta sanitaria para encontrar tus medicamentos
        </Text>
        <TouchableOpacity
          style={[styles.primaryButton, shadows.scanButton, isTablet && styles.primaryButtonTablet]}
          activeOpacity={0.85}
          onPress={() => router.push('/scanner')}
        >
          <Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
          <Text style={[styles.primaryButtonText, isTablet && styles.primaryButtonTextTablet]}>
            Iniciar escaneo
          </Text>
        </TouchableOpacity>

        {/* Separator */}
        <View style={styles.separator}>
          <View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
          <Text style={[styles.separatorText, { color: colors.textSecondary }]}>o</Text>
          <View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
        </View>

        {/* Option 2: Upload device photo */}
        <View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
          <Ionicons name="camera" size={24} color={colors.primary} />
          <View style={styles.optionTextContainer}>
            <Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
              Subir foto del dispositivo
            </Text>
            <Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
              Toma o selecciona una foto del dispositivo sanitario
            </Text>
          </View>
        </View>
        <View style={styles.photoButtonsRow}>
          <TouchableOpacity
            style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
            activeOpacity={0.7}
            onPress={handleTakePhoto}
          >
            <Ionicons name="camera-outline" size={20} color={colors.primary} />
            <Text style={[styles.photoButtonText, { color: colors.primary }]}>Tomar foto</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
            activeOpacity={0.7}
            onPress={handleSelectFromGallery}
          >
            <Ionicons name="images-outline" size={20} color={colors.primary} />
            <Text style={[styles.photoButtonText, { color: colors.primary }]}>Galería</Text>
          </TouchableOpacity>
        </View>
        {selectedImage && (
          <View style={styles.imagePreviewContainer}>
            <Ionicons name="checkmark-circle" size={20} color={colors.success} />
            <Text style={[styles.imagePreviewText, { color: colors.success }]}>Foto seleccionada correctamente</Text>
          </View>
        )}

        {/* Option 3: Enter card number manually */}
        <View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
          <Ionicons name="keypad" size={24} color={colors.primary} />
          <View style={styles.optionTextContainer}>
            <Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
              Introducir número manualmente
            </Text>
            <Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
              Escribe el número de tu tarjeta sanitaria
            </Text>
          </View>
        </View>
        <View style={styles.manualInputRow}>
          <TextInput
            style={[styles.manualInput, isTablet && styles.manualInputTablet, { backgroundColor: colors.card, borderColor: colors.border, color: colors.text }]}
            placeholder="Introduce el número de tarjeta"
            placeholderTextColor={colors.textSecondary}
            value={manualNumber}
            onChangeText={setManualNumber}
            keyboardType="default"
            autoCapitalize="none"
            autoCorrect={false}
            returnKeyType="search"
            onSubmitEditing={handleManualSubmit}
          />
          <TouchableOpacity
            style={[styles.manualSubmitButton, isTablet && styles.manualSubmitButtonTablet]}
            activeOpacity={0.7}
            onPress={handleManualSubmit}
          >
            <Ionicons name="arrow-forward" size={20} color="#ffffff" />
          </TouchableOpacity>
        </View>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  scrollContainer: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    paddingVertical: spacing.xl,
  },
  content: {
    alignItems: 'center',
    paddingHorizontal: spacing.xl,
    gap: spacing.md,
  },
  contentTablet: {
    gap: spacing.lg,
  },
  iconContainer: {
    width: 100,
    height: 100,
    borderRadius: 50,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: spacing.sm,
  },
  iconContainerTablet: {
    width: 140,
    height: 140,
    borderRadius: 70,
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  titleTablet: {
    fontSize: 28,
  },
  description: {
    fontSize: 15,
    textAlign: 'center',
    lineHeight: 22,
    maxWidth: 280,
  },
  descriptionTablet: {
    fontSize: 17,
    maxWidth: 420,
    lineHeight: 26,
  },
  primaryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    backgroundColor: '#2b5bb5',
    borderRadius: borderRadius.lg,
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.xl,
    marginTop: spacing.sm,
  },
  primaryButtonTablet: {
    paddingVertical: spacing.lg,
    paddingHorizontal: spacing.xl * 1.5,
  },
  primaryButtonText: {
    fontSize: 17,
    fontWeight: '600',
    color: '#ffffff',
  },
  primaryButtonTextTablet: {
    fontSize: 20,
  },
  separator: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
    marginVertical: spacing.sm,
  },
  separatorLine: {
    flex: 1,
    height: 1,
  },
  separatorText: {
    marginHorizontal: spacing.md,
    fontSize: 14,
  },
  optionCard: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
    borderRadius: borderRadius.lg,
    padding: spacing.md,
    gap: spacing.md,
    borderWidth: 1,
  },
  optionCardTablet: {
    padding: spacing.lg,
  },
  optionTextContainer: {
    flex: 1,
  },
  optionTitle: {
    fontSize: 16,
    fontWeight: '600',
  },
  optionTitleTablet: {
    fontSize: 18,
  },
  optionDescription: {
    fontSize: 13,
    marginTop: 2,
  },
  optionDescriptionTablet: {
    fontSize: 15,
  },
  photoButtonsRow: {
    flexDirection: 'row',
    width: '100%',
    gap: spacing.sm,
  },
  photoButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.xs,
    borderRadius: borderRadius.md,
    paddingVertical: spacing.sm + 4,
    borderWidth: 1,
  },
  photoButtonTablet: {
    paddingVertical: spacing.md,
  },
  photoButtonText: {
    fontSize: 14,
    fontWeight: '500',
  },
  imagePreviewContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
    paddingVertical: spacing.xs,
  },
  imagePreviewText: {
    fontSize: 13,
    fontWeight: '500',
  },
  manualInputRow: {
    flexDirection: 'row',
    width: '100%',
    gap: spacing.sm,
  },
  manualInput: {
    flex: 1,
    borderRadius: borderRadius.md,
    borderWidth: 1,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm + 4,
    fontSize: 15,
  },
  manualInputTablet: {
    fontSize: 18,
    paddingVertical: spacing.md,
  },
  manualSubmitButton: {
    backgroundColor: '#7fbf8f',
    borderRadius: borderRadius.md,
    width: 48,
    alignItems: 'center',
    justifyContent: 'center',
  },
  manualSubmitButtonTablet: {
    width: 56,
  },
});
