import React, { useCallback, useState } 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 { useRouter, useFocusEffect, useNavigation } from 'expo-router';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import StaffBookingCard from '@/components/staff/StaffBookingCard';

/** Premium Stat widget tile */
function StatWidget({ label, value, icon, colors, delay }: { label: string; value: number | string; icon: any; colors: readonly [string, string]; delay?: number }) {
  return (
    <Animated.View entering={FadeInDown.duration(500).delay(delay || 0)} style={styles.statWidgetContainer}>
      <LinearGradient
        colors={colors}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.statWidget}
      >
        <View style={styles.statContent}>
          {/* Icon left */}
          <View style={styles.statIconContainer}>
            <Ionicons name={icon} size={20} color="#fff" />
          </View>
          
          {/* Text centered in the remaining space */}
          <View style={styles.statTextGroup}>
            <Text style={styles.statValue}>{value}</Text>
            <Text style={styles.statLabel} numberOfLines={2}>{label}</Text>
          </View>
        </View>
        
        {/* Decorative background circle */}
        <View style={styles.decorativeCircle} />
      </LinearGradient>
    </Animated.View>
  );
}

export default function StaffDashboard() {
  const router = useRouter();
  const navigation = useNavigation();
  const { user_id, isAuthenticated } = 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 () => {
    if (!isAuthenticated || !user_id) return;
    try {
      const [statsRes, bookingsRes] = await Promise.all([
        api.post('/staff/get-total-bookingcount', { provider_id: user_id }),
        api.post('/staff/getlatestbookings', { provider_id: user_id })
      ]);
      setStats(statsRes.data?.data?.totalcount ?? null);
      const bookings = bookingsRes.data?.data ?? [];
      const mapped = bookings.map((b: any) => ({
        ...b,
        id: b.booking_id ?? b.id,
        total_amount: b.total_amount || (b.amount ? b.amount.replace(/[^0-9.]/g, '') : null),
      }));
      setRecentBookings(mapped);
    } catch (error) {
      console.error('[StaffDashboard] fetch error:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => { 
    navigation.getParent()?.setOptions?.({ headerTitle: 'E-Concerto' });
    fetchStaffData(); 
  }, []));

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

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

  return (
    <View style={{ flex: 1, backgroundColor: theme.background }}>
      <ScrollView
        contentContainerStyle={{ paddingBottom: 110 }}
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
      >
        {/* ── Header ── */}
        <Animated.View entering={FadeInDown.duration(400)} style={styles.header}>
          <View>
            <Text style={[styles.greeting, { color: theme.text }]}>Painel do Staff</Text>
            <Text style={[styles.subtitle, { color: theme.textMuted }]}>Gerencie suas tarefas e compromissos.</Text>
          </View>
          <View style={[styles.badge, { backgroundColor: theme.primary + '15' }]}>
            <Ionicons name="briefcase" size={24} color={theme.primary} />
          </View>
        </Animated.View>

        {/* ── Stats widgets ── */}
        <View style={styles.statsGrid}>
          <StatWidget 
            label="Em andamento" 
            value={stats?.in_progress_count ?? '0'} 
            icon="sync-outline" 
            colors={['#1F618D', '#2980B9']} 
            delay={100}
          />
          <StatWidget 
            label="Concluídas" 
            value={stats?.completed_count ?? '0'} 
            icon="checkmark-done-circle-outline" 
            colors={['#003171', '#1A5276']} 
            delay={200}
          />
          <StatWidget 
            label="Total Pago" 
            value={stats?.paid_count ?? '0'} 
            icon="cash-outline" 
            colors={['#154360', '#2E86C1']} 
            delay={300}
          />
          <StatWidget 
            label="Cancelados" 
            value={stats?.cancelled_count ?? '0'} 
            icon="close-circle-outline" 
            colors={['#C0392B', '#E74C3C']} 
            delay={400}
          />
        </View>

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

        {/* ── Recent bookings ── */}
        <View style={styles.list}>
          {recentBookings.length > 0 ? (
            recentBookings.map((b: any, i: number) => (
              <Animated.View key={b.booking_id ?? i} entering={FadeInDown.duration(400).delay(300 + i * 80)}>
                <StaffBookingCard
                  booking={b}
                  onPress={() => router.push(`/(drawer)/(tabs)/staff_booking/${b.booking_id}` as any)}
                />
              </Animated.View>
            ))
          ) : (
            <Animated.View entering={FadeIn.duration(500)} style={styles.empty}>
              <Ionicons name="clipboard-outline" size={48} color={theme.border} />
              <Text style={[styles.emptyText, { color: theme.textMuted }]}>Nenhum serviço para o momento.</Text>
            </Animated.View>
          )}
        </View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  loader: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: {
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
    paddingHorizontal: 24, paddingTop: 16, paddingBottom: 20,
  },
  greeting: { fontSize: 26, fontWeight: '800', letterSpacing: -0.5 },
  subtitle: { fontSize: 14, marginTop: 4 },
  badge: { width: 50, height: 50, borderRadius: 25, justifyContent: 'center', alignItems: 'center' },
  statsGrid: {
    flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between',
    paddingHorizontal: 20, gap: 12,
  },
  statWidgetContainer: {
    width: '48%',
    height: 80,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.1)',
    marginBottom: 12,
  },
  statWidget: {
    flex: 1,
    borderRadius: 14,
    paddingHorizontal: 12,
    paddingVertical: 10,
    overflow: 'hidden',
    position: 'relative',
    justifyContent: 'center',
  },
  statContent: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
    zIndex: 2,
  },
  statIconContainer: {
    width: 36,
    height: 36,
    borderRadius: 10,
    backgroundColor: 'rgba(255,255,255,0.25)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  statTextGroup: {
    flex: 1,
    alignItems: 'center', // Center text group
    marginRight: 36, // Offset icon width to keep true center
  },
  statValue: {
    color: '#fff',
    fontSize: 22,
    fontWeight: '900',
    letterSpacing: -0.5,
  },
  statLabel: { fontSize: 11, fontWeight: '600', color: 'rgba(255,255,255,0.9)', textAlign: 'center' },
  decorativeCircle: {
    position: 'absolute',
    top: -15,
    right: -15,
    width: 70,
    height: 70,
    borderRadius: 35,
    backgroundColor: 'rgba(255,255,255,0.1)',
    zIndex: 1,
  },
  sectionHeader: {
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
    paddingHorizontal: 24, marginTop: 24, marginBottom: 14,
  },
  sectionTitle: { fontSize: 20, fontWeight: '700', letterSpacing: -0.5 },
  seeAll: { fontSize: 14, fontWeight: '600' },
  list: { paddingHorizontal: 20 },
  empty: { padding: 40, alignItems: 'center', gap: 12 },
  emptyText: { fontSize: 15, textAlign: 'center' },
});
