import React, { useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { colors } from '../../../tokens/colors';
import { useAuthStore } from '../../../stores/authStore';
import { Ionicons } from '@expo/vector-icons';
import { useQuery } from '@tanstack/react-query';
import { api } from '../../../lib/api';
import { format } from 'date-fns';
import { NetworkStatusBar } from '../../../components/ui/NetworkStatus';
import { offlineSyncManager } from '../../../lib/offlineSync';
import { useNetworkStore } from '../../../stores/networkStore';

export default function HomeScreen() {
  const router = useRouter();
  const user = useAuthStore((state) => state.user);
  const logout = useAuthStore((state) => state.logout);
  const { isOnline } = useNetworkStore();

  // Fetch dashboard data
  const { data: dashboardData, isLoading, refetch } = useQuery({
    queryKey: ['dashboard'],
    queryFn: async () => {
      try {
        const response = await api.get('/dashboard');
        // Save to offline storage
        offlineSyncManager.saveOfflineData('dashboard', response.data);
        return response.data;
      } catch (error) {
        // If offline, try to get cached data
        if (!isOnline) {
          const cachedData = offlineSyncManager.getOfflineDataByKey('dashboard');
          if (cachedData) {
            return cachedData;
          }
        }
        throw error;
      }
    },
  });

  // Fetch user profile if not loaded
  useEffect(() => {
    const fetchUser = async () => {
      if (!user) {
        try {
          const response = await api.get('/auth/me');
          useAuthStore.getState().setAuth(response.data, useAuthStore.getState().token || '');
        } catch (error) {
          console.error('Failed to fetch user:', error);
        }
      }
    };
    fetchUser();
  }, [user]);

  const handleLogout = async () => {
    await logout();
    router.replace('/(auth)/login');
  };

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return 'Good morning';
    if (hour < 18) return 'Good afternoon';
    return 'Good evening';
  };

  return (
    <SafeAreaView style={styles.container}>
      <NetworkStatusBar />
      <View style={styles.header}>
        <View>
          <Text style={styles.greeting}>{getGreeting()}, {user?.username || 'User'}</Text>
          <Text style={styles.date}>{format(new Date(), 'EEEE, MMMM d')}</Text>
        </View>
        <View style={styles.headerRight}>
          <TouchableOpacity style={styles.iconButton}>
            <Ionicons name="notifications-outline" size={24} color={colors.muted} />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.avatar}
            onPress={() => router.push('/(app)/(more)/settings')}
          >
            <Text style={styles.avatarText}>
              {user?.username?.[0]?.toUpperCase() || 'U'}
            </Text>
          </TouchableOpacity>
        </View>
      </View>

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl refreshing={false} onRefresh={refetch} tintColor={colors.primary} />
        }
      >
        {/* Stats Row */}
        <View style={styles.statsRow}>
          <TouchableOpacity style={styles.statCard} onPress={() => router.push('/(app)/(tasks)')}>
            <Text style={styles.statValue}>{dashboardData?.tasks_today || 0}</Text>
            <Text style={styles.statLabel}>Tasks</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.statCard} onPress={() => router.push('/(app)/(life)/habits')}>
            <Text style={styles.statValue}>{dashboardData?.habits_done || 0}/{dashboardData?.habits_total || 0}</Text>
            <Text style={styles.statLabel}>Habits</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.statCard} onPress={() => router.push('/(app)/(life)/goals')}>
            <Text style={styles.statValue}>{dashboardData?.goals_active || 0}</Text>
            <Text style={styles.statLabel}>Goals</Text>
          </TouchableOpacity>
        </View>

        {/* Alerts Banner */}
        {dashboardData?.critical_alerts > 0 && (
          <TouchableOpacity style={styles.alertBanner}>
            <Ionicons name="warning" size={20} color={colors.critical} />
            <Text style={styles.alertText}>
              {dashboardData.critical_alerts} Critical Alert{dashboardData.critical_alerts > 1 ? 's' : ''}
            </Text>
            <Ionicons name="chevron-forward" size={20} color={colors.muted} />
          </TouchableOpacity>
        )}

        {/* Today's Tasks */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>Today's Tasks</Text>
            <TouchableOpacity onPress={() => router.push('/(app)/(tasks)')}>
              <Text style={styles.seeAllText}>See all</Text>
            </TouchableOpacity>
          </View>
          {isLoading ? (
            <ActivityIndicator color={colors.primary} style={{ marginTop: 20 }} />
          ) : (
            <View style={styles.taskList}>
              {dashboardData?.tasks?.slice(0, 3).map((task: any) => (
                <TouchableOpacity key={task.id} style={styles.taskCard}>
                  <View style={[styles.priorityDot, { backgroundColor: getPriorityColor(task.priority) }]} />
                  <View style={styles.taskContent}>
                    <Text style={styles.taskTitle}>{task.title}</Text>
                    {task.due_time && <Text style={styles.taskTime}>{task.due_time}</Text>}
                  </View>
                </TouchableOpacity>
              )) || (
                <Text style={styles.emptyText}>No tasks for today</Text>
              )}
            </View>
          )}
        </View>

        {/* Habits Today */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>Habits Today</Text>
            <TouchableOpacity onPress={() => router.push('/(app)/(life)/habits')}>
              <Text style={styles.seeAllText}>See all</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.habitList}>
            {dashboardData?.habits?.slice(0, 3).map((habit: any) => (
              <View key={habit.id} style={styles.habitCard}>
                <View style={[styles.habitDot, { backgroundColor: habit.color || colors.primary }]} />
                <Text style={styles.habitTitle}>{habit.title}</Text>
                <View style={styles.habitStatus}>
                  {habit.completed_today ? (
                    <Text style={styles.habitDone}>Done</Text>
                  ) : (
                    <Text style={styles.habitPending}>Pending</Text>
                  )}
                </View>
              </View>
            )) || (
              <Text style={styles.emptyText}>No habits tracked</Text>
            )}
          </View>
        </View>

        {/* Quick Actions */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Quick Actions</Text>
          <View style={styles.actionGrid}>
            <TouchableOpacity style={styles.actionCard} onPress={() => router.push('/(app)/(tasks)')}
            >
              <Ionicons name="add-circle" size={32} color={colors.primary} />
              <Text style={styles.actionText}>Add Task</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionCard}>
              <Ionicons name="checkmark-circle" size={32} color={colors.success} />
              <Text style={styles.actionText}>Check Habit</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionCard}>
              <Ionicons name="time" size={32} color={colors.warning} />
              <Text style={styles.actionText}>Focus Session</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionCard}>
              <Ionicons name="create" size={32} color={colors.creation} />
              <Text style={styles.actionText}>Journal</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={{ height: 40 }} />
      </ScrollView>
    </SafeAreaView>
  );
}

const getPriorityColor = (priority: string) => {
  switch (priority?.toLowerCase()) {
    case 'critical':
      return colors.critical;
    case 'high':
      return colors.high;
    case 'normal':
      return colors.normal;
    case 'low':
      return colors.low;
    default:
      return colors.muted;
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.bgDark,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 16,
  },
  greeting: {
    fontSize: 24,
    fontWeight: 'bold',
    color: 'white',
  },
  date: {
    fontSize: 14,
    color: colors.muted,
    marginTop: 4,
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
  },
  iconButton: {
    padding: 8,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  avatarText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  content: {
    flex: 1,
  },
  statsRow: {
    flexDirection: 'row',
    paddingHorizontal: 20,
    gap: 12,
    marginBottom: 20,
  },
  statCard: {
    flex: 1,
    backgroundColor: colors.cardDark,
    borderRadius: 12,
    padding: 16,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  statValue: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colors.primary,
    marginBottom: 4,
  },
  statLabel: {
    fontSize: 12,
    color: colors.muted,
  },
  alertBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.critical + '20',
    marginHorizontal: 20,
    padding: 12,
    borderRadius: 10,
    marginBottom: 20,
    gap: 8,
  },
  alertText: {
    flex: 1,
    color: colors.critical,
    fontSize: 14,
    fontWeight: '600',
  },
  section: {
    marginBottom: 24,
    paddingHorizontal: 20,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: 'white',
  },
  seeAllText: {
    fontSize: 14,
    color: colors.primary,
    fontWeight: '600',
  },
  taskList: {
    gap: 8,
  },
  taskCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.cardDark,
    padding: 16,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  priorityDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginRight: 12,
  },
  taskContent: {
    flex: 1,
  },
  taskTitle: {
    color: 'white',
    fontSize: 15,
    fontWeight: '500',
  },
  taskTime: {
    color: colors.muted,
    fontSize: 13,
    marginTop: 4,
  },
  habitList: {
    gap: 8,
  },
  habitCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.cardDark,
    padding: 16,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  habitDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginRight: 12,
  },
  habitTitle: {
    flex: 1,
    color: 'white',
    fontSize: 15,
    fontWeight: '500',
  },
  habitStatus: {
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 12,
  },
  habitDone: {
    color: colors.success,
    fontSize: 12,
    fontWeight: '600',
  },
  habitPending: {
    color: colors.muted,
    fontSize: 12,
  },
  actionGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
    marginTop: 8,
  },
  actionCard: {
    width: '48%',
    backgroundColor: colors.cardDark,
    padding: 16,
    borderRadius: 12,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  actionText: {
    color: 'white',
    fontSize: 13,
    marginTop: 8,
    fontWeight: '500',
  },
  emptyText: {
    color: colors.muted,
    fontSize: 14,
    textAlign: 'center',
    padding: 20,
  },
});
