import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  RefreshControl,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { colors } from '../../../tokens/colors';
import { Ionicons } from '@expo/vector-icons';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/api';
import { Swipeable } from 'react-native-gesture-handler';
import * as Haptics from 'expo-haptics';
import { offlineSyncManager } from '../../../lib/offlineSync';
import { useNetworkStore } from '../../../stores/networkStore';
import { NetworkStatusBar } from '../../../components/ui/NetworkStatus';

type FilterType = 'today' | 'upcoming' | 'all';
type SortType = 'due_date' | 'priority' | 'life_area' | 'created_at';

export default function TasksScreen() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [filter, setFilter] = useState<FilterType>('today');
  const [sortBy, setSortBy] = useState<SortType>('due_date');
  const { isOnline } = useNetworkStore();

  // Fetch tasks
  const { data: tasks, isLoading, refetch } = useQuery({
    queryKey: ['tasks', filter, sortBy],
    queryFn: async () => {
      try {
        const response = await api.get(`/tasks?filter=${filter}&sort_by=${sortBy}`);
        // Save to offline storage
        offlineSyncManager.saveOfflineData(`tasks_${filter}_${sortBy}`, response.data);
        return response.data;
      } catch (error) {
        // If offline, try to get cached data
        if (!isOnline) {
          const cachedData = offlineSyncManager.getOfflineDataByKey(`tasks_${filter}_${sortBy}`);
          if (cachedData) {
            return cachedData;
          }
        }
        throw error;
      }
    },
  });

  // Complete task mutation with offline support
  const completeMutation = useMutation({
    mutationFn: async (taskId: string) => {
      if (!isOnline) {
        // Queue for later
        offlineSyncManager.queueMutation({
          type: 'COMPLETE',
          endpoint: `/tasks/${taskId}/complete`,
        });
        return { offline: true };
      }
      await api.patch(`/tasks/${taskId}/complete`);
    },
    onSuccess: () => {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
      useNetworkStore.getState().updatePendingCount();
    },
  });

  // Delete task mutation with offline support
  const deleteMutation = useMutation({
    mutationFn: async (taskId: string) => {
      if (!isOnline) {
        // Queue for later
        offlineSyncManager.queueMutation({
          type: 'DELETE',
          endpoint: `/tasks/${taskId}`,
        });
        return { offline: true };
      }
      await api.delete(`/tasks/${taskId}`);
    },
    onSuccess: () => {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
      useNetworkStore.getState().updatePendingCount();
    },
  });

  const handleComplete = (taskId: string) => {
    completeMutation.mutate(taskId);
  };

  const handleDelete = (taskId: string, taskTitle: string) => {
    Alert.alert(
      'Delete Task',
      `Are you sure you want to delete "${taskTitle}"?`,
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: () => deleteMutation.mutate(taskId),
        },
      ]
    );
  };

  const renderRightActions = (taskId: string) => {
    return (
      <TouchableOpacity
        style={styles.completeAction}
        onPress={() => handleComplete(taskId)}
      >
        <Ionicons name="checkmark-circle" size={24} color="white" />
        <Text style={styles.actionText}>Complete</Text>
      </TouchableOpacity>
    );
  };

  const renderLeftActions = (taskId: string, taskTitle: string) => {
    return (
      <TouchableOpacity
        style={styles.deleteAction}
        onPress={() => handleDelete(taskId, taskTitle)}
      >
        <Ionicons name="trash" size={24} color="white" />
        <Text style={styles.actionText}>Delete</Text>
      </TouchableOpacity>
    );
  };

  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 getLifeAreaColor = (area: string) => {
    const areaColors: any = {
      work: colors.work,
      health: colors.health,
      self: colors.self,
      relationships: colors.relationships,
      learning: colors.learning,
      creation: colors.creation,
      community: colors.community,
      recovery: colors.recovery,
    };
    return areaColors[area?.toLowerCase()] || colors.muted;
  };

  // Group tasks by status
  const groupedTasks = tasks?.reduce((acc: any, task: any) => {
    if (task.status === 'completed') {
      acc.completed = acc.completed || [];
      acc.completed.push(task);
    } else if (task.due_date && task.due_date < new Date().toISOString().split('T')[0]) {
      acc.overdue = acc.overdue || [];
      acc.overdue.push(task);
    } else if (task.due_date === new Date().toISOString().split('T')[0]) {
      acc.today = acc.today || [];
      acc.today.push(task);
    } else {
      acc.upcoming = acc.upcoming || [];
      acc.upcoming.push(task);
    }
    return acc;
  }, {});

  return (
    <SafeAreaView style={styles.container}>
      <NetworkStatusBar />
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Tasks</Text>
        <TouchableOpacity
          style={styles.addButton}
          onPress={() => router.push('/(app)/(tasks)/new')}
        >
          <Ionicons name="add" size={24} color="white" />
        </TouchableOpacity>
      </View>

      {/* Filter Chips */}
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={styles.filterContainer}
        contentContainerStyle={styles.filterContent}
      >
        <TouchableOpacity
          style={[styles.filterChip, filter === 'today' && styles.filterChipActive]}
          onPress={() => setFilter('today')}
        >
          <Text style={[styles.filterText, filter === 'today' && styles.filterTextActive]}>
            Today
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.filterChip, filter === 'upcoming' && styles.filterChipActive]}
          onPress={() => setFilter('upcoming')}
        >
          <Text style={[styles.filterText, filter === 'upcoming' && styles.filterTextActive]}>
            Upcoming
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.filterChip, filter === 'all' && styles.filterChipActive]}
          onPress={() => setFilter('all')}
        >
          <Text style={[styles.filterText, filter === 'all' && styles.filterTextActive]}>
            All
          </Text>
        </TouchableOpacity>
      </ScrollView>

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl refreshing={false} onRefresh={refetch} tintColor={colors.primary} />
        }
      >
        {isLoading ? (
          <ActivityIndicator color={colors.primary} style={{ marginTop: 40 }} />
        ) : !tasks || tasks.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Ionicons name="checkbox-outline" size={64} color={colors.muted} />
            <Text style={styles.emptyText}>No tasks yet</Text>
            <Text style={styles.emptySubtext}>Tap + to create your first task</Text>
          </View>
        ) : (
          <>
            {/* Overdue Tasks */}
            {groupedTasks?.overdue && groupedTasks.overdue.length > 0 && (
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>OVERDUE ({groupedTasks.overdue.length})</Text>
                {groupedTasks.overdue.map((task: any) => (
                  <Swipeable
                    key={task.id}
                    renderRightActions={() => renderRightActions(task.id)}
                    renderLeftActions={() => renderLeftActions(task.id, task.title)}
                  >
                    <TouchableOpacity
                      style={styles.taskCard}
                      onPress={() => router.push(`/(app)/(tasks)/${task.id}`)}
                    >
                      <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_date} • {task.due_time}
                          </Text>
                        )}
                      </View>
                      {task.life_area && (
                        <View
                          style={[
                            styles.areaTag,
                            { backgroundColor: getLifeAreaColor(task.life_area) + '20' },
                          ]}
                        >
                          <Text
                            style={[
                              styles.areaTagText,
                              { color: getLifeAreaColor(task.life_area) },
                            ]}
                          >
                            {task.life_area}
                          </Text>
                        </View>
                      )}
                    </TouchableOpacity>
                  </Swipeable>
                ))}
              </View>
            )}

            {/* Today Tasks */}
            {groupedTasks?.today && groupedTasks.today.length > 0 && (
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>TODAY ({groupedTasks.today.length})</Text>
                {groupedTasks.today.map((task: any) => (
                  <Swipeable
                    key={task.id}
                    renderRightActions={() => renderRightActions(task.id)}
                    renderLeftActions={() => renderLeftActions(task.id, task.title)}
                  >
                    <TouchableOpacity
                      style={styles.taskCard}
                      onPress={() => router.push(`/(app)/(tasks)/${task.id}`)}
                    >
                      <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>
                      {task.life_area && (
                        <View
                          style={[
                            styles.areaTag,
                            { backgroundColor: getLifeAreaColor(task.life_area) + '20' },
                          ]}
                        >
                          <Text
                            style={[
                              styles.areaTagText,
                              { color: getLifeAreaColor(task.life_area) },
                            ]}
                          >
                            {task.life_area}
                          </Text>
                        </View>
                      )}
                    </TouchableOpacity>
                  </Swipeable>
                ))}
              </View>
            )}

            {/* Upcoming Tasks */}
            {groupedTasks?.upcoming && groupedTasks.upcoming.length > 0 && (
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>UPCOMING ({groupedTasks.upcoming.length})</Text>
                {groupedTasks.upcoming.map((task: any) => (
                  <Swipeable
                    key={task.id}
                    renderRightActions={() => renderRightActions(task.id)}
                    renderLeftActions={() => renderLeftActions(task.id, task.title)}
                  >
                    <TouchableOpacity
                      style={styles.taskCard}
                      onPress={() => router.push(`/(app)/(tasks)/${task.id}`)}
                    >
                      <View
                        style={[
                          styles.priorityDot,
                          { backgroundColor: getPriorityColor(task.priority) },
                        ]}
                      />
                      <View style={styles.taskContent}>
                        <Text style={styles.taskTitle}>{task.title}</Text>
                        {task.due_date && (
                          <Text style={styles.taskTime}>
                            {task.due_date}
                            {task.due_time && ` • ${task.due_time}`}
                          </Text>
                        )}
                      </View>
                      {task.life_area && (
                        <View
                          style={[
                            styles.areaTag,
                            { backgroundColor: getLifeAreaColor(task.life_area) + '20' },
                          ]}
                        >
                          <Text
                            style={[
                              styles.areaTagText,
                              { color: getLifeAreaColor(task.life_area) },
                            ]}
                          >
                            {task.life_area}
                          </Text>
                        </View>
                      )}
                    </TouchableOpacity>
                  </Swipeable>
                ))}
              </View>
            )}

            {/* Completed Tasks */}
            {groupedTasks?.completed && groupedTasks.completed.length > 0 && (
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>COMPLETED ({groupedTasks.completed.length})</Text>
                {groupedTasks.completed.map((task: any) => (
                  <TouchableOpacity
                    key={task.id}
                    style={[styles.taskCard, styles.completedCard]}
                    onPress={() => router.push(`/(app)/(tasks)/${task.id}`)}
                  >
                    <Ionicons name="checkmark-circle" size={20} color={colors.success} />
                    <View style={styles.taskContent}>
                      <Text style={[styles.taskTitle, styles.completedText]}>{task.title}</Text>
                    </View>
                  </TouchableOpacity>
                ))}
              </View>
            )}
          </>
        )}

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.bgDark,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 16,
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: 'bold',
    color: 'white',
  },
  addButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  filterContainer: {
    maxHeight: 50,
  },
  filterContent: {
    paddingHorizontal: 20,
    gap: 8,
    paddingBottom: 12,
  },
  filterChip: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: colors.cardDark,
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  filterChipActive: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  filterText: {
    fontSize: 14,
    color: colors.muted,
    fontWeight: '500',
  },
  filterTextActive: {
    color: 'white',
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 12,
    fontWeight: '700',
    color: colors.muted,
    marginBottom: 8,
    letterSpacing: 0.5,
  },
  taskCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.cardDark,
    padding: 16,
    borderRadius: 12,
    marginBottom: 8,
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  completedCard: {
    opacity: 0.6,
  },
  priorityDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginRight: 12,
  },
  taskContent: {
    flex: 1,
  },
  taskTitle: {
    color: 'white',
    fontSize: 15,
    fontWeight: '500',
  },
  completedText: {
    textDecorationLine: 'line-through',
  },
  taskTime: {
    color: colors.muted,
    fontSize: 13,
    marginTop: 4,
  },
  areaTag: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 12,
  },
  areaTagText: {
    fontSize: 11,
    fontWeight: '600',
    textTransform: 'capitalize',
  },
  completeAction: {
    backgroundColor: colors.success,
    justifyContent: 'center',
    alignItems: 'center',
    width: 100,
    marginBottom: 8,
    borderRadius: 12,
  },
  deleteAction: {
    backgroundColor: colors.danger,
    justifyContent: 'center',
    alignItems: 'center',
    width: 100,
    marginBottom: 8,
    borderRadius: 12,
  },
  actionText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '600',
    marginTop: 4,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    color: 'white',
    marginTop: 16,
  },
  emptySubtext: {
    fontSize: 14,
    color: colors.muted,
    marginTop: 8,
  },
});
