import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
  Alert,
  ActivityIndicator,
} 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 { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/api';
import * as Haptics from 'expo-haptics';
import { offlineSyncManager } from '../../../lib/offlineSync';
import { useNetworkStore } from '../../../stores/networkStore';

const PRIORITIES = [
  { value: 'critical', label: 'Critical', color: colors.critical },
  { value: 'high', label: 'High', color: colors.high },
  { value: 'normal', label: 'Normal', color: colors.normal },
  { value: 'low', label: 'Low', color: colors.low },
];

const LIFE_AREAS = [
  { value: 'work', label: 'Work', color: colors.work },
  { value: 'health', label: 'Health', color: colors.health },
  { value: 'self', label: 'Self', color: colors.self },
  { value: 'relationships', label: 'Relationships', color: colors.relationships },
  { value: 'learning', label: 'Learning', color: colors.learning },
  { value: 'creation', label: 'Creation', color: colors.creation },
  { value: 'community', label: 'Community', color: colors.community },
  { value: 'recovery', label: 'Recovery', color: colors.recovery },
];

const DURATIONS = [
  { value: 15, label: '15m' },
  { value: 30, label: '30m' },
  { value: 60, label: '1h' },
  { value: 120, label: '2h' },
  { value: 180, label: '3h' },
];

export default function NewTaskScreen() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const { isOnline } = useNetworkStore();

  const [title, setTitle] = useState('');
  const [priority, setPriority] = useState('normal');
  const [lifeArea, setLifeArea] = useState<string | null>(null);
  const [dueDate, setDueDate] = useState('');
  const [dueTime, setDueTime] = useState('');
  const [duration, setDuration] = useState<number | null>(null);
  const [notes, setNotes] = useState('');

  const createMutation = useMutation({
    mutationFn: async (taskData: any) => {
      if (!isOnline) {
        // Queue for later sync
        offlineSyncManager.queueMutation({
          type: 'CREATE',
          endpoint: '/tasks',
          data: taskData,
        });
        return { offline: true, ...taskData };
      }
      const response = await api.post('/tasks', taskData);
      return response.data;
    },
    onSuccess: (data) => {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
      useNetworkStore.getState().updatePendingCount();
      
      if (!isOnline) {
        Alert.alert(
          'Saved Offline',
          'Your task has been saved and will sync when you\'re back online.',
          [{ text: 'OK', onPress: () => router.back() }]
        );
      } else {
        router.back();
      }
    },
    onError: (error: any) => {
      Alert.alert('Error', error.response?.data?.detail || 'Failed to create task');
    },
  });

  const handleCreate = () => {
    if (!title.trim()) {
      Alert.alert('Error', 'Please enter a task title');
      return;
    }

    const taskData = {
      title: title.trim(),
      priority,
      life_area: lifeArea,
      due_date: dueDate || null,
      due_time: dueTime || null,
      duration,
      notes: notes.trim() || null,
      status: 'pending',
    };

    createMutation.mutate(taskData);
  };

  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardView}
      >
        <View style={styles.header}>
          <TouchableOpacity onPress={() => router.back()} style={styles.closeButton}>
            <Ionicons name="close" size={24} color="white" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>New Task</Text>
          <TouchableOpacity
            onPress={handleCreate}
            disabled={createMutation.isPending}
            style={styles.saveButton}
          >
            {createMutation.isPending ? (
              <ActivityIndicator color={colors.primary} />
            ) : (
              <Text style={styles.saveButtonText}>Save</Text>
            )}
          </TouchableOpacity>
        </View>

        <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
          {/* Title */}
          <View style={styles.section}>
            <Text style={styles.label}>Title *</Text>
            <TextInput
              style={styles.input}
              placeholder="What needs to be done?"
              placeholderTextColor={colors.muted}
              value={title}
              onChangeText={setTitle}
              multiline
              autoFocus
            />
          </View>

          {/* Priority */}
          <View style={styles.section}>
            <Text style={styles.label}>Priority</Text>
            <View style={styles.chipContainer}>
              {PRIORITIES.map((p) => (
                <TouchableOpacity
                  key={p.value}
                  style={[
                    styles.chip,
                    priority === p.value && { backgroundColor: p.color + '30', borderColor: p.color },
                  ]}
                  onPress={() => setPriority(p.value)}
                >
                  <Text
                    style={[
                      styles.chipText,
                      priority === p.value && { color: p.color, fontWeight: '600' },
                    ]}
                  >
                    {p.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* Life Area */}
          <View style={styles.section}>
            <Text style={styles.label}>Life Area</Text>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              style={styles.chipScrollContainer}
            >
              <View style={styles.chipContainer}>
                {LIFE_AREAS.map((area) => (
                  <TouchableOpacity
                    key={area.value}
                    style={[
                      styles.chip,
                      lifeArea === area.value && {
                        backgroundColor: area.color + '30',
                        borderColor: area.color,
                      },
                    ]}
                    onPress={() => setLifeArea(lifeArea === area.value ? null : area.value)}
                  >
                    <Text
                      style={[
                        styles.chipText,
                        lifeArea === area.value && { color: area.color, fontWeight: '600' },
                      ]}
                    >
                      {area.label}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            </ScrollView>
          </View>

          {/* Due Date */}
          <View style={styles.section}>
            <Text style={styles.label}>Due Date</Text>
            <TextInput
              style={styles.input}
              placeholder="YYYY-MM-DD"
              placeholderTextColor={colors.muted}
              value={dueDate}
              onChangeText={setDueDate}
            />
          </View>

          {/* Due Time */}
          <View style={styles.section}>
            <Text style={styles.label}>Due Time</Text>
            <TextInput
              style={styles.input}
              placeholder="HH:MM"
              placeholderTextColor={colors.muted}
              value={dueTime}
              onChangeText={setDueTime}
            />
          </View>

          {/* Duration */}
          <View style={styles.section}>
            <Text style={styles.label}>Estimated Duration</Text>
            <View style={styles.chipContainer}>
              {DURATIONS.map((d) => (
                <TouchableOpacity
                  key={d.value}
                  style={[
                    styles.chip,
                    duration === d.value && {
                      backgroundColor: colors.primary + '30',
                      borderColor: colors.primary,
                    },
                  ]}
                  onPress={() => setDuration(duration === d.value ? null : d.value)}
                >
                  <Text
                    style={[
                      styles.chipText,
                      duration === d.value && { color: colors.primary, fontWeight: '600' },
                    ]}
                  >
                    {d.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* Notes */}
          <View style={styles.section}>
            <Text style={styles.label}>Notes</Text>
            <TextInput
              style={[styles.input, styles.textArea]}
              placeholder="Add any additional details..."
              placeholderTextColor={colors.muted}
              value={notes}
              onChangeText={setNotes}
              multiline
              numberOfLines={4}
              textAlignVertical="top"
            />
          </View>

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.bgDark,
  },
  keyboardView: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderDark,
  },
  closeButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: 'white',
  },
  saveButton: {
    padding: 4,
  },
  saveButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.primary,
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
  },
  section: {
    marginTop: 24,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.muted,
    marginBottom: 8,
  },
  input: {
    backgroundColor: colors.cardDark,
    borderRadius: 12,
    padding: 16,
    fontSize: 15,
    color: 'white',
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  textArea: {
    minHeight: 100,
  },
  chipContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  chipScrollContainer: {
    maxHeight: 50,
  },
  chip: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: colors.cardDark,
    borderWidth: 1,
    borderColor: colors.borderDark,
  },
  chipText: {
    fontSize: 14,
    color: colors.muted,
  },
});
