import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, RefreshControl } from 'react-native';
import { Colors } from '../../../constants/theme';
import api from '../../../services/api';
import { Ionicons } from '@expo/vector-icons';

export default function DashboardScreen() {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchData = async () => {
    try {
      const response = await api.get('/userdashboarddata');
      setData(response.data);
    } catch (error) {
      console.error('Error fetching dashboard data:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

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

  return (
    <ScrollView 
      style={styles.container}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); fetchData(); }} />}
    >
      <View style={styles.header}>
        <Text style={styles.welcome}>Olá, {data?.userdata?.name || 'Cliente'}!</Text>
        <Text style={styles.subtitle}>Aqui está o resumo da sua atividade.</Text>
      </View>

      <View style={styles.statsRow}>
        <View style={styles.statBox}>
          <Ionicons name="calendar" size={24} color={Colors.light.primary} />
          <Text style={styles.statVal}>{data?.upcomingBooking?.length || 0}</Text>
          <Text style={styles.statLabel}>Próximas</Text>
        </View>
        <View style={styles.statBox}>
          <Ionicons name="wallet" size={24} color="#28a745" />
          <Text style={styles.statVal}>{data?.wallet_balance || '0.00'}</Text>
          <Text style={styles.statLabel}>Carteira</Text>
        </View>
        <View style={styles.statBox}>
          <Ionicons name="ticket" size={24} color="#ffc107" />
          <Text style={styles.statVal}>{data?.total_tickets || 0}</Text>
          <Text style={styles.statLabel}>Tickets</Text>
        </View>
      </View>

      <Text style={styles.sectionTitle}>Próximos Serviços</Text>
      {data?.upcomingBooking?.length > 0 ? data.upcomingBooking.map((b: any) => (
        <View key={b.id} style={styles.bookingCard}>
          <Text style={styles.bookingTitle}>{b.service_name}</Text>
          <Text style={styles.bookingDate}>{b.booking_date} às {b.slot}</Text>
        </View>
      )) : <Text style={styles.empty}>Sem serviços futuros.</Text>}

    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#f8f9fa' },
  loader: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: { padding: 20, backgroundColor: Colors.light.primary, borderBottomLeftRadius: 30, borderBottomRightRadius: 30, paddingBottom: 40 },
  welcome: { fontSize: 24, fontWeight: 'bold', color: '#fff' },
  subtitle: { fontSize: 14, color: '#e0e0e0', marginTop: 5 },
  statsRow: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 20, marginTop: -30 },
  statBox: { flex: 1, backgroundColor: '#fff', padding: 15, borderRadius: 12, alignItems: 'center', marginHorizontal: 5, elevation: 3 },
  statVal: { fontSize: 18, fontWeight: 'bold', marginTop: 10 },
  statLabel: { fontSize: 12, color: '#666' },
  sectionTitle: { fontSize: 18, fontWeight: 'bold', margin: 20 },
  bookingCard: { backgroundColor: '#fff', marginHorizontal: 20, padding: 15, borderRadius: 8, marginBottom: 10, borderLeftWidth: 4, borderLeftColor: Colors.light.primary },
  bookingTitle: { fontWeight: 'bold', fontSize: 16 },
  bookingDate: { color: '#666', marginTop: 5 },
  empty: { textAlign: 'center', color: '#888', fontStyle: 'italic' }
});
