import React, { useEffect, useState } from 'react';
import {
  View, Text, ScrollView, StyleSheet,
  ActivityIndicator, Alert, TouchableOpacity,
} from 'react-native';
import { adminFetchStats } from '../../services/api';
import { Stats } from '../../types';

export default function AdminDashboardScreen({ navigation }: any) {
  const [stats, setStats]     = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

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

  const loadStats = async () => {
    setLoading(true);
    try {
      const data = await adminFetchStats();
      setStats(data);
    } catch {
      Alert.alert('Error', 'Could not load stats.');
    } finally {
      setLoading(false);
    }
  };

  const statCards = stats ? [
    { label: 'Total Orders',      value: stats.totalOrders,         emoji: '📦', color: '#3b82f6' },
    { label: 'Total Customers',   value: stats.totalCustomers,      emoji: '👥', color: '#22c55e' },
    { label: 'Total Products',    value: stats.totalProducts,       emoji: '🛒', color: '#8b5cf6' },
    { label: 'Pending Orders',    value: stats.pendingOrders,       emoji: '⏳', color: '#f59e0b' },
    { label: 'Unread Messages',   value: stats.unreadMessages,      emoji: '✉️', color: '#ef4444' },
    {
      label: 'Est. Revenue',
      value: `₦${Number(stats.estimatedRevenue).toLocaleString()}`,
      emoji: '💰',
      color: '#f97316',
    },
  ] : [];

  return (
    <ScrollView style={styles.bg} contentContainerStyle={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>📊 Admin Dashboard</Text>
        <TouchableOpacity onPress={loadStats}>
          <Text style={styles.refresh}>↻ Refresh</Text>
        </TouchableOpacity>
      </View>

      {loading
        ? <ActivityIndicator color="#f97316" size="large" style={{ marginTop: 40 }} />
        : (
          <View style={styles.grid}>
            {statCards.map(card => (
              <View key={card.label} style={[styles.statCard, { borderLeftColor: card.color }]}>
                <Text style={styles.statEmoji}>{card.emoji}</Text>
                <Text style={[styles.statValue, { color: card.color }]}>{card.value}</Text>
                <Text style={styles.statLabel}>{card.label}</Text>
              </View>
            ))}
          </View>
        )
      }

      <Text style={styles.sectionTitle}>Quick Admin Actions</Text>
      <View style={styles.actionGrid}>
        <TouchableOpacity style={styles.actionCard} onPress={() => navigation.navigate('Products')}>
          <Text style={styles.actionEmoji}>📦</Text>
          <Text style={styles.actionText}>Manage Products</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.actionCard} onPress={() => navigation.navigate('Orders')}>
          <Text style={styles.actionEmoji}>🚚</Text>
          <Text style={styles.actionText}>Manage Orders</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.actionCard} onPress={() => navigation.navigate('Users')}>
          <Text style={styles.actionEmoji}>👥</Text>
          <Text style={styles.actionText}>View Customers</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  bg:           { flex: 1, backgroundColor: '#0f172a' },
  container:    { padding: 20 },
  header:       { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 },
  title:        { fontSize: 20, fontWeight: '800', color: '#fff' },
  refresh:      { color: '#f97316', fontWeight: '700' },
  grid:         { flexDirection: 'row', flexWrap: 'wrap', gap: 12, marginBottom: 24 },
  statCard:     {
    width: '47%', backgroundColor: '#1e293b', borderRadius: 12,
    padding: 16, borderLeftWidth: 4,
  },
  statEmoji:    { fontSize: 22, marginBottom: 6 },
  statValue:    { fontSize: 22, fontWeight: '800', marginBottom: 2 },
  statLabel:    { fontSize: 12, color: '#64748b' },
  sectionTitle: { fontSize: 18, fontWeight: '700', color: '#fff', marginBottom: 12 },
  actionGrid:   { flexDirection: 'row', flexWrap: 'wrap', gap: 12 },
  actionCard:   {
    width: '47%', backgroundColor: '#1e293b', borderRadius: 12,
    padding: 18, alignItems: 'center',
  },
  actionEmoji:  { fontSize: 28, marginBottom: 8 },
  actionText:   { color: '#fff', fontWeight: '700', fontSize: 13, textAlign: 'center' },
});
