import React, { useCallback, useState, useMemo } from 'react';
import {
  View, Text, StyleSheet, FlatList, ActivityIndicator,
  RefreshControl, TouchableOpacity, useColorScheme, ScrollView, Alert
} from 'react-native';
import { Colors } from '@/constants/theme';
import { useAuthStore } from '@/store/authStore';
import api from '@/services/api';
import { useRouter, useFocusEffect, useNavigation } from 'expo-router';
import Animated, { FadeIn, FadeInDown } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import StaffBookingCard from '@/components/staff/StaffBookingCard';

const FILTERS = [
  { label: 'Todas',          statuses: [] },
  { label: 'Pendente',       statuses: [1] },
  { label: 'Em Andamento',   statuses: [2] },
  { label: 'Concluídas',     statuses: [5, 6] },
  { label: 'Canceladas',     statuses: [3, 8] },
];

export default function StaffBookingsScreen() {
  const router = useRouter();
  const navigation = useNavigation();
  const { user_id } = useAuthStore();
  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 [activeFilter, setActiveFilter] = useState(0);
  const [actionLoading, setActionLoading] = useState<number | null>(null);

  const fetchBookings = async () => {
    try {
      const res = await api.get(`/getstaffBookings?staffid=${user_id}`);
      const data = Array.isArray(res.data) ? res.data : (res.data?.data ?? []);
      
      const mapped = data.map((b: any) => ({
        ...b,
        booking_id: b.id,
        product_name: b.source_name,
        booking_date: b.booking_date || b.start,
        total_amount: b.total_amount || (b.amount ? b.amount.replace(/[^0-9.]/g, '') : null),
        booking_status: b.booking_status || b.status_no,
      }));
      
      setBookings(mapped);
    } catch (error) {
      console.error('[StaffBookings] fetch error:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

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

  /** Change booking status: 2=accept, 3=cancel, 5=complete */
  const changeStatus = async (bookingId: number, type: number, label: string) => {
    let message = `Deseja ${label.toLowerCase()} deste serviço?`;
    if (type === 5) message = 'Confirma a conclusão do trabalho?';
    if (type === 2) message = 'Deseja aceitar este serviço?';
    if (type === 3) message = 'Deseja cancelar este serviço?';

    Alert.alert(label, message, [
      { text: 'Não', style: 'cancel' },
      {
        text: 'Sim, Confirmar', style: 'default',
        onPress: async () => {
          try {
            setActionLoading(bookingId);
            await api.post('/updatebookingstatus', { id: bookingId, status: type });
            // Update locally
            setBookings(prev => prev.map(b =>
              (b.booking_id === bookingId || b.id === bookingId)
                ? { ...b, booking_status: type }
                : b
            ));
          } catch (err: any) {
            console.error('[StaffBookings] Error updating status:', err.response?.data || err.message);
            Alert.alert('Erro', 'Não foi possível actualizar o estado do serviço.');
          } finally {
            setActionLoading(null);
          }
        }
      }
    ]);
  };

  // Apply filter locally
  const filtered = activeFilter === 0
    ? bookings
    : bookings.filter(b => FILTERS[activeFilter].statuses.includes(Number(b.booking_status)));

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

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      {/* Filter chips */}
      <ScrollView 
        horizontal 
        showsHorizontalScrollIndicator={false}
        style={styles.filtersWrapper}
        contentContainerStyle={styles.filtersContainer}
      >
        {FILTERS.map((f, index) => {
          const isActive = activeFilter === index;
          return (
            <TouchableOpacity
              key={index}
              activeOpacity={0.7}
              style={[
                styles.filterChip, 
                { backgroundColor: isActive ? theme.primary : theme.surface },
                isActive && styles.activeFilterChip
              ]}
              onPress={() => setActiveFilter(index)}
            >
              {isActive && <Ionicons name="checkmark" size={12} color="#fff" style={{ marginRight: 4 }} />}
              <Text style={[
                styles.filterText, 
                { color: isActive ? '#fff' : theme.textMuted }
              ]}>
                {f.label}
              </Text>
            </TouchableOpacity>
          );
        })}
      </ScrollView>

      <FlatList
        data={filtered}
        style={{ flex: 1 }} // Force FlatList to fill space
        keyExtractor={(item, i) => String(item.booking_id ?? item.id ?? i)}
        renderItem={({ item, index }) => (
          <Animated.View entering={FadeInDown.duration(400).delay(index * 60)}>
            <StaffBookingCard
              booking={item}
              onPress={() => router.push(`/(drawer)/(tabs)/staff_booking/${item.booking_id ?? item.id}` as any)}
            />
            {/* Quick action buttons */}
            <View style={styles.actions}>
              {Number(item.booking_status) === 1 && (
                <>
                  <ActionBtn
                    label="Aceitar Serviço"   color="#48c774" icon="checkmark-outline"
                    loading={actionLoading === (item.booking_id ?? item.id)}
                    onPress={() => changeStatus(item.booking_id ?? item.id, 2, 'Aceitar Serviço')}
                  />
                  <ActionBtn
                    label="Cancelar Serviço"  color="#ff6b6b" icon="close-outline"
                    loading={actionLoading === (item.booking_id ?? item.id)}
                    onPress={() => changeStatus(item.booking_id ?? item.id, 3, 'Cancelar Serviço')}
                  />
                </>
              )}
              {Number(item.booking_status) === 2 && (
                <ActionBtn
                  label="Concluir Serviço"  color="#3273dc" icon="checkmark-done-outline"
                  loading={actionLoading === (item.booking_id ?? item.id)}
                  onPress={() => changeStatus(item.booking_id ?? item.id, 5, 'Concluir Serviço')}
                />
              )}
            </View>
          </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.empty}>
            <Ionicons name="calendar-clear-outline" size={56} color={theme.border} />
            <Text style={[styles.emptyText, { color: theme.textMuted }]}>Nenhum serviço encontrado.</Text>
          </Animated.View>
        }
      />
    </View>
  );
}

function ActionBtn({ label, color, icon, loading, onPress }: any) {
  return (
    <TouchableOpacity
      style={[styles.actionBtn, { borderColor: color, backgroundColor: color + '12' }]}
      onPress={onPress}
      disabled={loading}
    >
      {loading ? (
        <ActivityIndicator size={12} color={color} />
      ) : (
        <Ionicons name={icon} size={14} color={color} />
      )}
      <Text style={[styles.actionLabel, { color }]}>{label}</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loader: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: { padding: 24, paddingBottom: 10 },
  title: { fontSize: 26, fontWeight: '800', letterSpacing: -0.5 },
  filtersWrapper: { maxHeight: 60, marginTop: 15, marginBottom: 15 },
  filtersContainer: { paddingHorizontal: 20, alignItems: 'center', gap: 10 },
  filterChip: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 100,
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: 'transparent',
  },
  activeFilterChip: {
    shadowColor: Colors.light.primary,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 8,
    elevation: 3,
  },
  filterText: { fontSize: 13, fontWeight: '700' },
  listContent: { padding: 16, paddingBottom: 110, flexGrow: 1 },
  actions: { flexDirection: 'row', gap: 8, marginTop: -6, marginBottom: 14, paddingHorizontal: 4 },
  actionBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 5,
    paddingHorizontal: 12, paddingVertical: 7, borderRadius: 10, borderWidth: 1,
  },
  actionLabel: { fontSize: 12, fontWeight: '700' },
  empty: { paddingTop: 80, alignItems: 'center', gap: 12 },
  emptyText: { fontSize: 15, textAlign: 'center' },
});
