import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } 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 * as Haptics from 'expo-haptics';

export default function TaskDetailScreen() {
  const router = useRouter();
  const { id } = useLocalSearchParams();
  const queryClient = useQueryClient();

  // Fetch task details
  const { data: task, isLoading } = useQuery({
    queryKey: ['task', id],
    queryFn: async () => {
      const response = await api.get(`/tasks/${id}`);
      return response.data;
    },
    enabled: !!id,
  });

  // Complete task mutation
  const completeMutation = useMutation({
    mutationFn: async () => {
      if (task.status === 'completed') {
        await api.patch(`/tasks/${id}/uncomplete`);
      } else {
        await api.patch(`/tasks/${id}/complete`);
      }
    },
    onSuccess: () => {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      queryClient.invalidateQueries({ queryKey: ['task', id] });
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
    },
  });

  // Delete task mutation
  const deleteMutation = useMutation({
    mutationFn: async () => {
      await api.delete(`/tasks/${id}`);
    },
    onSuccess: () => {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
      router.back();
    },
  });

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

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

  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;
  };

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <ActivityIndicator color={colors.primary} style={{ marginTop: 40 }} />
      </SafeAreaView>
    );
  }

  if (!task) {
    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.errorText}>Task not found</Text>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <Ionicons name="arrow-back" size={24} color="white" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Task Details</Text>
        <View style={{ width: 24 }} />
      </View>

      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {/* Badges */}
        <View style={styles.badgeRow}>
          <View
            style={[
              styles.badge,
              { backgroundColor: getPriorityColor(task.priority) + '30', borderColor: getPriorityColor(task.priority) },
            ]}
          >
            <Text style={[styles.badgeText, { color: getPriorityColor(task.priority) }]}>
              {task.priority}
            </Text>
          </View>
          {task.life_area && (
            <View
              style={[
                styles.badge,
                { backgroundColor: getLifeAreaColor(task.life_area) + '30', borderColor: getLifeAreaColor(task.life_area) },
              ]}
            >
              <Text style={[styles.badgeText, { color: getLifeAreaColor(task.life_area) }]}>
                {task.life_area}
              </Text>
            </View>
          )}
          {task.status === 'completed' && (
            <View style={[styles.badge, { backgroundColor: colors.success + '30', borderColor: colors.success }]}>
              <Ionicons name="checkmark-circle" size={14} color={colors.success} />
              <Text style={[styles.badgeText, { color: colors.success, marginLeft: 4 }]}>Completed</Text>
            </View>
          )}
        </View>

        {/* Title */}
        <Text style={styles.title}>{task.title}</Text>

        {/* Details */}
        <View style={styles.detailsSection}>
          {task.due_date && (
            <View style={styles.detailRow}>
              <Ionicons name="calendar" size={20} color={colors.muted} />
              <Text style={styles.detailText}>
                {task.due_date}
                {task.due_time && ` • ${task.due_time}`}
              </Text>
            </View>
          )}

          {task.duration && (
            <View style={styles.detailRow}>
              <Ionicons name="time" size={20} color={colors.muted} />
              <Text style={styles.detailText}>Estimated: {task.duration} min</Text>
            </View>
          )}

          {task.goal_id && (
            <View style={styles.detailRow}>
              <Ionicons name="flag" size={20} color={colors.muted} />
              <Text style={styles.detailText}>Linked to goal</Text>
            </View>
          )}

          {task.recurrence && (
            <View style={styles.detailRow}>
              <Ionicons name="repeat" size={20} color={colors.muted} />
              <Text style={styles.detailText}>Recurrence: {task.recurrence}</Text>
            </View>
          )}
        </View>

        {/* Notes */}
        {task.notes && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Notes</Text>
            <Text style={styles.notesText}>{task.notes}</Text>
          </View>
        )}

        {/* Actions */}
        <View style={styles.actionsSection}>
          <TouchableOpacity
            style={[
              styles.actionButton,
              task.status === 'completed' ? styles.uncompleteButton : styles.completeButton,
            ]}
            onPress={handleComplete}
            disabled={completeMutation.isPending}
          >
            {completeMutation.isPending ? (
              <ActivityIndicator color="white" />
            ) : (
              <>
                <Ionicons
                  name={task.status === 'completed' ? 'refresh' : 'checkmark-circle'}
                  size={20}
                  color="white"
                />
                <Text style={styles.actionButtonText}>
                  {task.status === 'completed' ? 'Mark Pending' : 'Complete'}
                </Text>
              </>
            )}
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.actionButton, styles.deleteButton]}
            onPress={handleDelete}
            disabled={deleteMutation.isPending}
          >
            {deleteMutation.isPending ? (
              <ActivityIndicator color="white" />
            ) : (
              <>
                <Ionicons name="trash" size={20} color="white" />
                <Text style={styles.actionButtonText}>Delete</Text>
              </>
            )}
          </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,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderDark,
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: 'white',
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
  },
  badgeRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
    marginTop: 20,
  },
  badge: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
    borderWidth: 1,
  },
  badgeText: {
    fontSize: 12,
    fontWeight: '600',
    textTransform: 'capitalize',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: 'white',
    marginTop: 16,
    lineHeight: 32,
  },
  detailsSection: {
    marginTop: 24,
    gap: 12,
  },
  detailRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
  },
  detailText: {
    fontSize: 15,
    color: 'white',
  },
  section: {
    marginTop: 24,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: 'white',
    marginBottom: 8,
  },
  notesText: {
    fontSize: 15,
    color: colors.muted,
    lineHeight: 22,
  },
  actionsSection: {
    marginTop: 32,
    gap: 12,
  },
  actionButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 16,
    borderRadius: 12,
    gap: 8,
  },
  completeButton: {
    backgroundColor: colors.success,
  },
  uncompleteButton: {
    backgroundColor: colors.warning,
  },
  deleteButton: {
    backgroundColor: colors.danger,
  },
  actionButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '600',
  },
  errorText: {
    color: colors.muted,
    fontSize: 16,
    textAlign: 'center',
    marginTop: 40,
  },
});
