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 } from 'react-native-reanimated';

const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);

const BASE_URL = 'http://172.20.10.7/ecabral/public/storage/';

const STATUS_MAP: Record<number, { label: string; color: string; bg: string; icon: string }> = {
  1:  { label: 'Pendente',          color: '#E65100', bg: '#FFF3E0', icon: 'time-outline' },
  2:  { label: 'Aceite',            color: '#1565C0', bg: '#E3F2FD', icon: 'sync-outline' },
  3:  { label: 'Cancelado',         color: '#C62828', bg: '#FFEBEE', icon: 'close-circle-outline' },
  5:  { label: 'Concluído',         color: '#2E7D32', bg: '#E8F5E9', icon: 'checkmark-circle-outline' },
  6:  { label: 'Serviço Concluído', color: '#2E7D32', bg: '#E8F5E9', icon: 'checkmark-done-outline' },
  8:  { label: 'Cancelado',         color: '#C62828', bg: '#FFEBEE', icon: 'close-circle-outline' },
};

interface Props {
  booking: any;
  onPress?: () => void;
}

export default function StaffBookingCard({ booking, onPress }: Props) {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const scale = useSharedValue(1);

  const status = STATUS_MAP[Number(booking.booking_status)] ?? {
    label: booking.booking_status_label ?? 'Pendente',
    color: '#888', bg: 'rgba(0,0,0,0.05)', icon: 'help-circle-outline',
  };

  const imageUrl = booking.productimage
    ? (booking.productimage.startsWith('http')
        ? booking.productimage
        : BASE_URL + booking.productimage)
    : null;

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

  let formattedDate = booking.bookingdate ?? booking.booking_date ?? '—';
  if (formattedDate.includes('T')) formattedDate = formattedDate.split('T')[0];
  else if (formattedDate.includes(' ')) formattedDate = formattedDate.split(' ')[0];

  // The backend might return 'total_amount' or 'amount' (which includes the symbol)
  // The user wants to see the price but NO dollar sign.
  const priceValue = booking.total_amount ?? booking.amount ?? '—';
  const cleanPrice = typeof priceValue === 'string' ? priceValue.replace('$', '') : priceValue;

  return (
    <AnimatedTouchable
      activeOpacity={1}
      style={[
        styles.container, 
        { 
          backgroundColor: theme.background, 
          borderColor: theme.primary + '40', // Thin primary blue border
          borderWidth: 1,
        }, 
        animatedStyle
      ]}
      onPress={onPress}
      onPressIn={() => { scale.value = withSpring(0.98, { damping: 15, stiffness: 300 }); }}
      onPressOut={() => { scale.value = withSpring(1, { damping: 15, stiffness: 300 }); }}
    >
      {/* Image */}
      <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>

      {/* Info */}
      <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 }]}>
            {cleanPrice} <Text style={styles.currency}>{booking.currency && booking.currency !== '$' ? booking.currency : ''}</Text>
          </Text>
        </View>

        <Text style={[styles.category, { color: theme.textMuted }]}>
          #{booking.booking_id ?? booking.id} • {booking.category_name ?? 'Serviço'}
        </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 }]}>
              {formattedDate}
            </Text>
          </View>
          
          <View style={[styles.statusBadge, { backgroundColor: status.bg }]}>
            <Ionicons name={status.icon as any} size={10} color={status.color} style={{ marginRight: 4 }} />
            <Text style={[styles.statusText, { color: status.color }]}>{status.label}</Text>
          </View>
        </View>
      </View>
    </AnimatedTouchable>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    borderRadius: 20,
    padding: 14,
    marginBottom: 16,
  },
  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,
  },
});
