import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  TouchableOpacity,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../../src/constants/colors';
import { api } from '../../src/services/api';
import { useAuth } from '../../src/context/AuthContext';

export default function AdminDashboard() {
  const { user } = useAuth();
  const [insights, setInsights] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

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

  const loadInsights = async () => {
    try {
      const data = await api.getAdminInsights();
      setInsights(data);
    } catch (error) {
      console.error('Error loading insights:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await loadInsights();
    setRefreshing(false);
  };

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>Welcome back,</Text>
            <Text style={styles.name}>{user?.name || 'Admin'}</Text>
          </View>
          <View style={styles.logoContainer}>
            <Text style={styles.logoText}>ABBAS</Text>
            <Text style={styles.logoSubtext}>FIT</Text>
          </View>
        </View>

        {/* Stats Grid */}
        <View style={styles.statsGrid}>
          <View style={[styles.statCard, { backgroundColor: 'rgba(255, 107, 53, 0.1)' }]}>
            <Ionicons name="people" size={28} color={colors.primary} />
            <Text style={styles.statNumber}>{insights?.total_users || 0}</Text>
            <Text style={styles.statLabel}>Total Clients</Text>
          </View>
          <View style={[styles.statCard, { backgroundColor: 'rgba(29, 185, 84, 0.1)' }]}>
            <Ionicons name="checkmark-circle" size={28} color={colors.secondary} />
            <Text style={styles.statNumber}>{insights?.adherence_rate || 0}%</Text>
            <Text style={styles.statLabel}>Adherence Rate</Text>
          </View>
          <View style={[styles.statCard, { backgroundColor: 'rgba(59, 130, 246, 0.1)' }]}>
            <Ionicons name="restaurant" size={28} color={colors.info} />
            <Text style={styles.statNumber}>{insights?.total_meals_logged || 0}</Text>
            <Text style={styles.statLabel}>Meals Logged</Text>
          </View>
          <View style={[styles.statCard, { backgroundColor: 'rgba(245, 158, 11, 0.1)' }]}>
            <Ionicons name="fitness" size={28} color={colors.warning} />
            <Text style={styles.statNumber}>{insights?.total_activities_logged || 0}</Text>
            <Text style={styles.statLabel}>Activities</Text>
          </View>
        </View>

        {/* Quick Actions */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Quick Actions</Text>
          <View style={styles.actionsRow}>
            <TouchableOpacity style={styles.actionButton}>
              <Ionicons name="person-add" size={24} color={colors.text} />
              <Text style={styles.actionText}>Add Client</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionButton}>
              <Ionicons name="clipboard" size={24} color={colors.text} />
              <Text style={styles.actionText}>New Plan</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionButton}>
              <Ionicons name="calendar" size={24} color={colors.text} />
              <Text style={styles.actionText}>Sessions</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Alerts */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Alerts</Text>
          {insights?.unread_contacts > 0 && (
            <View style={styles.alertCard}>
              <Ionicons name="mail-unread" size={20} color={colors.warning} />
              <Text style={styles.alertText}>
                {insights.unread_contacts} unread contact{insights.unread_contacts > 1 ? 's' : ''}
              </Text>
            </View>
          )}
          {insights?.pending_sessions > 0 && (
            <View style={styles.alertCard}>
              <Ionicons name="time" size={20} color={colors.info} />
              <Text style={styles.alertText}>
                {insights.pending_sessions} pending session{insights.pending_sessions > 1 ? 's' : ''}
              </Text>
            </View>
          )}
          {!insights?.unread_contacts && !insights?.pending_sessions && (
            <View style={styles.alertCard}>
              <Ionicons name="checkmark-circle" size={20} color={colors.success} />
              <Text style={styles.alertText}>All caught up!</Text>
            </View>
          )}
        </View>

        {/* Active This Week */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Weekly Overview</Text>
          <View style={styles.weeklyCard}>
            <View style={styles.weeklyRow}>
              <Text style={styles.weeklyLabel}>Active Clients</Text>
              <Text style={styles.weeklyValue}>{insights?.active_users_this_week || 0}</Text>
            </View>
            <View style={styles.weeklyDivider} />
            <View style={styles.weeklyRow}>
              <Text style={styles.weeklyLabel}>Total Sessions</Text>
              <Text style={styles.weeklyValue}>{insights?.total_sessions || 0}</Text>
            </View>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 24,
  },
  greeting: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  name: {
    fontSize: 24,
    fontWeight: '700',
    color: colors.text,
  },
  logoContainer: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  logoText: {
    fontSize: 18,
    fontWeight: '900',
    color: colors.text,
    letterSpacing: 2,
  },
  logoSubtext: {
    fontSize: 18,
    fontWeight: '900',
    color: colors.primary,
    letterSpacing: 2,
  },
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
    marginBottom: 24,
  },
  statCard: {
    width: '48%',
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 16,
    alignItems: 'center',
  },
  statNumber: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.text,
    marginTop: 8,
  },
  statLabel: {
    fontSize: 12,
    color: colors.textSecondary,
    marginTop: 4,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
    marginBottom: 12,
  },
  actionsRow: {
    flexDirection: 'row',
    gap: 12,
  },
  actionButton: {
    flex: 1,
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    alignItems: 'center',
    gap: 8,
  },
  actionText: {
    fontSize: 12,
    color: colors.text,
    fontWeight: '500',
  },
  alertCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    gap: 12,
    marginBottom: 8,
  },
  alertText: {
    fontSize: 14,
    color: colors.text,
  },
  weeklyCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 20,
  },
  weeklyRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  weeklyLabel: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  weeklyValue: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.primary,
  },
  weeklyDivider: {
    height: 1,
    backgroundColor: colors.border,
    marginVertical: 16,
  },
});
