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

export default function StaffDashboard() {
  const router = useRouter();
  const { user_id } = useAuthStore();
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];

  const [stats, setStats] = useState<any>(null);
  const [recentBookings, setRecentBookings] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchStaffData = async () => {
    try {
      const [statsRes, bookingsRes] = await Promise.all([
        api.post('/gettotalbookingcountapi', { provider_id: user_id }),
        api.post('/getlatestbookingsapi', { provider_id: user_id })
      ]);

      setStats(statsRes.data.data?.totalcount);
      setRecentBookings(bookingsRes.data.data || []);
    } catch (error) {
      console.error('Error fetching staff dashboard:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(
    useCallback(() => {
      fetchStaffData();
    }, [])
  );

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

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

  return (
    <View style={{ flex: 1, backgroundColor: theme.background }}>
      <ScrollView 
        style={styles.container}
        contentContainerStyle={{ paddingBottom: 100 }}
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
      >
        <Animated.View entering={FadeInDown.duration(400).delay(100)} style={styles.header}>
          <View>
            <Text style={[styles.greeting, { color: theme.text }]}>Olá, Staff!</Text>
            <Text style={[styles.subtitle, { color: theme.textMuted }]}>Suas tarefas e atribuições de hoje.</Text>
          </View>
          <View style={[styles.badge, { backgroundColor: theme.primary + '15' }]}>
             <Ionicons name="briefcase" size={20} color={theme.primary} />
          </View>
        </Animated.View>

        <View style={styles.statsGrid}>
          <StatCard 
            label="Próximas" 
            value={stats?.upcoming_count || 0} 
            icon="time" 
            index={0}
          />
          <StatCard 
            label="Concluídas" 
            value={stats?.completed_count || 0} 
            icon="checkmark-done" 
            index={1}
          />
          <StatCard 
            label="Canceladas" 
            value={stats?.cancelled_count || 0} 
            icon="close-circle" 
            index={2}
          />
          <StatCard 
            label="Ganhos" 
            value={stats?.completed_total_amount || '0'} 
            icon="card" 
            index={3}
          />
        </View>

        <Animated.View entering={FadeIn.duration(400).delay(300)} style={styles.sectionHeader}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>Atribuições Recentes</Text>
          <TouchableOpacity onPress={() => router.push('/(drawer)/(tabs)/bookings' as any)}>
            <Text style={[styles.seeAll, { color: theme.primary }]}>Ver Tudo</Text>
          </TouchableOpacity>
        </Animated.View>

        <View style={styles.bookingsList}>
          {recentBookings.length > 0 ? (
            recentBookings.map((booking: any, index: number) => (
              <Animated.View key={booking.booking_id} entering={FadeInDown.duration(400).delay(400 + (index * 100))}>
                <BookingItem 
                  booking={{
                    ...booking,
                    id: booking.booking_id,
                    source_name: booking.product_name,
                    productimage: booking.productimage
                  }} 
                  onPress={() => {}} 
                  hideBorder={true}
                />
              </Animated.View>
            ))
          ) : (
            <Animated.View entering={FadeIn.duration(500)} style={styles.emptyContainer}>
              <Ionicons name="clipboard-outline" size={48} color={theme.border} style={{ marginBottom: 12 }} />
              <Text style={[styles.emptyText, { color: theme.textMuted }]}>Sem atribuições para o momento.</Text>
            </Animated.View>
          )}
        </View>

      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: { 
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 24, 
    paddingTop: 10,
    paddingBottom: 20
  },
  greeting: { fontSize: 26, fontWeight: '800', letterSpacing: -0.5 },
  subtitle: { fontSize: 15, marginTop: 4, fontWeight: '400' },
  badge: {
    width: 46,
    height: 46,
    borderRadius: 23,
    justifyContent: 'center',
    alignItems: 'center'
  },
  statsGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', paddingHorizontal: 20 },
  sectionHeader: { 
    flexDirection: 'row', 
    justifyContent: 'space-between', 
    alignItems: 'center', 
    paddingHorizontal: 24, 
    marginTop: 15,
    marginBottom: 15 
  },
  sectionTitle: { fontSize: 20, fontWeight: '700', letterSpacing: -0.5 },
  seeAll: { fontSize: 14, fontWeight: '600' },
  bookingsList: { paddingHorizontal: 20 },
  emptyContainer: { padding: 40, alignItems: 'center', justifyContent: 'center' },
  emptyText: { fontSize: 16, textAlign: 'center' },
});
