import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, useColorScheme } from 'react-native';
import { Image } from 'expo-image';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '@/constants/theme';
import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming } from 'react-native-reanimated';

const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);

interface BookingItemProps {
  booking: any;
  onPress?: () => void;
  hideBorder?: boolean;
}

export default function BookingItem({ booking, onPress, hideBorder = false }: BookingItemProps) {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];

  const scale = useSharedValue(1);
  const opacity = useSharedValue(1);

  const getStatusConfig = (status: number) => {
    switch (status) {
      case 5: case 6: return { bg: '#E8F5E9', text: '#2E7D32', icon: 'checkmark-circle' }; // Completed
      case 3: case 8: case 11: return { bg: '#FFEBEE', text: '#C62828', icon: 'close-circle' }; // Cancelled/Rejected
      case 1: case 2: case 12: return { bg: theme.primary + '10', text: theme.primary, icon: 'time' }; // Open/In Progress
      case 9: case 10: case 13: return { bg: '#FFF3E0', text: '#E65100', icon: 'alert-circle' }; // Pending/Budget
      default: return { bg: 'rgba(0,0,0,0.05)', text: '#888', icon: 'help-circle' };
    }
  };

  const getStatusLabel = (status: number, originalLabel: string) => {
    switch (status) {
      case 1: return 'Pendente';
      case 2: return 'Em andamento';
      case 3: return 'Cancelado (Provedor)';
      case 5: case 6: return 'Concluído';
      case 8: return 'Cancelado';
      case 9: return 'Orçamento Pendente';
      case 10: return 'Orçamento Proposto';
      case 11: return 'Orçamento Rejeitado';
      case 12: return 'Pendente de Confirmação';
      case 13: return 'Confirmação de Pagamento';
      default: return originalLabel || 'Pendente';
    }
  };

  const statusConfig = getStatusConfig(Number(booking.booking_status));
  const statusLabel = getStatusLabel(Number(booking.booking_status), booking.booking_status_label);

  const handlePressIn = () => {
    scale.value = withSpring(0.98, { damping: 15, stiffness: 300 });
    opacity.value = withTiming(0.9, { duration: 100 });
  };

  const handlePressOut = () => {
    scale.value = withSpring(1, { damping: 15, stiffness: 300 });
    opacity.value = withTiming(1, { duration: 150 });
  };

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }],
    opacity: opacity.value,
  }));

  const imageUrl = booking.productimage 
    ? (booking.productimage.startsWith('http') 
        ? booking.productimage 
        : `http://172.20.10.7/ecabral/public/storage/${booking.productimage}`) 
    : null;

  return (
    <AnimatedTouchable 
      activeOpacity={1}
      style={[
        styles.container, 
        { 
          backgroundColor: theme.background, 
          borderColor: theme.border,
          borderWidth: 1,
        }, 
        animatedStyle
      ]} 
      onPress={onPress}
      onPressIn={handlePressIn}
      onPressOut={handlePressOut}
    >
      <View style={styles.imageContainer}>
         {imageUrl ? (
           <Image 
             source={{ uri: imageUrl }} 
             style={styles.image} 
             contentFit="cover"
           />
         ) : (
           <View style={[styles.imagePlaceholder, { backgroundColor: theme.primary + '10' }]}>
             <Ionicons name="construct" size={24} color={theme.primary} />
           </View>
         )}
      </View>

      <View style={styles.info}>
        <View style={styles.header}>
          <Text style={[styles.productName, { color: theme.text }]} numberOfLines={1}>
            {booking.source_name || booking.product_name}
          </Text>
          <Text style={[styles.price, { color: theme.text }]}>
            {booking.total_amount} <Text style={styles.currency}>{booking.currency || ''}</Text>
          </Text>
        </View>
        
        <Text style={[styles.category, { color: theme.textMuted }]}>
          #{booking.id} • {booking.category_name}
        </Text>
        
        <View style={styles.footer}>
          <View style={styles.dateRow}>
            <Ionicons name="calendar-outline" size={12} color={theme.textMuted} />
            <Text style={[styles.dateText, { color: theme.textMuted }]}>
              {booking.bookingdate || booking.bookedon || booking.booking_date}
            </Text>
          </View>
          
          <View style={[styles.statusBadge, { backgroundColor: statusConfig.bg }]}>
            <Ionicons name={statusConfig.icon as any} size={10} color={statusConfig.text} style={{ marginRight: 4 }} />
            <Text style={[styles.statusText, { color: statusConfig.text }]}>
              {statusLabel}
            </Text>
          </View>
        </View>
      </View>
    </AnimatedTouchable>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    borderRadius: 20,
    padding: 14,
    marginBottom: 16,
    // Material 3 clean look (no heavy shadows, soft border)
  },
  imageContainer: {
    width: 64,
    height: 64,
    borderRadius: 14,
    overflow: 'hidden',
  },
  image: {
    width: '100%',
    height: '100%',
  },
  imagePlaceholder: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  info: {
    flex: 1,
    marginLeft: 14,
    justifyContent: 'space-between',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  productName: {
    fontSize: 15,
    fontWeight: '800',
    flex: 1,
    letterSpacing: -0.2,
  },
  price: {
    fontSize: 15,
    fontWeight: '900',
    marginLeft: 10,
  },
  currency: {
    fontSize: 11,
    fontWeight: '600',
  },
  category: {
    fontSize: 12,
    fontWeight: '600',
    marginTop: 2,
    opacity: 0.6,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 10,
  },
  dateRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  dateText: {
    fontSize: 11,
    marginLeft: 4,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  statusBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
  },
  statusText: {
    fontSize: 10,
    fontWeight: '800',
    textTransform: 'uppercase',
    letterSpacing: 0.3,
  },
});
