import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, FlatList, ActivityIndicator, RefreshControl } from 'react-native';
import { Colors } from '../../constants/theme';
import api from '../../services/api';

export default function BookingsScreen() {
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchBookings = async () => {
    try {
      const response = await api.get('/user/bookinglist');
      setBookings(response.data.data || []);
    } catch (error) {
      console.error('Error fetching bookings:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchBookings();
  }, []);

  const getStatusStyle = (status: number) => {
    switch(status) {
      case 1: return { bg: '#fff3cd', color: '#856404', label: 'Pendente' };
      case 2: return { bg: '#d4edda', color: '#155724', label: 'Aceite' };
      case 3: return { bg: '#f8d7da', color: '#721c24', label: 'Cancelado' };
      case 6: return { bg: '#cce5ff', color: '#004085', label: 'Concluído' };
      default: return { bg: '#eee', color: '#333', label: 'Desconhecido' };
    }
  };

  if (loading && !refreshing) {
    return <View style={styles.loader}><ActivityIndicator size="large" color={Colors.light.primary} /></View>;
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={bookings}
        keyExtractor={(item: any) => item.id.toString()}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); fetchBookings(); }} />}
        renderItem={({ item }: any) => {
          const style = getStatusStyle(item.booking_status);
          return (
            <View style={styles.card}>
              <View style={styles.cardHeader}>
                <Text style={styles.serviceName}>{item.service_name}</Text>
                <View style={[styles.statusBadge, { backgroundColor: style.bg }]}>
                  <Text style={[styles.statusText, { color: style.color }]}>{style.label}</Text>
                </View>
              </View>
              <View style={styles.cardFooter}>
                <Text style={styles.bookingDate}>{item.booking_date} às {item.slot}</Text>
                <Text style={styles.amount}>{item.amount}</Text>
              </View>
            </View>
          );
        }}
        ListEmptyComponent={<Text style={styles.empty}>Nenhum serviço encontrado.</Text>}
        contentContainerStyle={{ padding: 20 }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#f8f9fa' },
  loader: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  card: { backgroundColor: '#fff', borderRadius: 12, padding: 15, marginBottom: 15, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.1, shadowRadius: 2 },
  cardHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 },
  serviceName: { fontSize: 16, fontWeight: 'bold', flex: 1 },
  statusBadge: { paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12 },
  statusText: { fontSize: 11, fontWeight: 'bold' },
  cardFooter: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingTop: 10, borderTopWidth: 1, borderTopColor: '#f0f0f0' },
  bookingDate: { color: '#666', fontSize: 13 },
  amount: { fontSize: 15, fontWeight: 'bold', color: Colors.light.primary },
  empty: { textAlign: 'center', marginTop: 50, color: '#888' }
});
