import React, { useCallback, useState } from 'react';
import { View, Text, StyleSheet, FlatList, ActivityIndicator, RefreshControl, useColorScheme } from 'react-native';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import BookingItem from '@/components/booking/BookingItem';
import Animated, { FadeIn, FadeInDown } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import { useRouter, useNavigation, useFocusEffect } from 'expo-router';

export default function ClientBookingsScreen() {
  const router = useRouter();
  const navigation = useNavigation();
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];

  const [bookings, setBookings] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

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

  useFocusEffect(
    useCallback(() => {
      navigation.getParent()?.setOptions?.({ headerTitle: 'Meus Serviços' });
      fetchBookings();
    }, [navigation])
  );

  const onRefresh = () => { setRefreshing(true); fetchBookings(); };

  if (loading && !refreshing) {
    return (
      <View style={[styles.loaderContainer, { backgroundColor: theme.background }]}>
        <ActivityIndicator size="large" color={theme.primary} />
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <FlatList
        data={bookings}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item, index }) => (
          <Animated.View entering={FadeInDown.duration(400).delay(index * 100)}>
            <BookingItem 
              booking={item} 
              onPress={() => router.push(`/(drawer)/booking/${item.id}` as any)} 
            />
          </Animated.View>
        )}
        contentContainerStyle={styles.listContent}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
        showsVerticalScrollIndicator={false}
        ListEmptyComponent={
          <Animated.View entering={FadeIn.duration(500)} style={styles.emptyContainer}>
            <Ionicons name="calendar-clear-outline" size={64} color={theme.border} style={{ marginBottom: 16 }} />
            <Text style={[styles.emptyText, { color: theme.textMuted }]}>Você ainda não possui serviços agendados.</Text>
          </Animated.View>
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  listContent: { padding: 20, paddingBottom: 100 },
  emptyContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 120 },
  emptyText: { fontSize: 16, textAlign: 'center' },
});
