import React, { useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  TextInput,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  Alert,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Plus, Pencil, Trash2, Check, X } from 'lucide-react-native';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFonts, Inter_400Regular, Inter_600SemiBold } from '@expo-google-fonts/inter';

const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;
const ALL_TYPES = ['Kurk', 'Berk', '3D'] as const;
type InsoleType = (typeof ALL_TYPES)[number];

const TYPE_COLORS: Record<InsoleType, { bg: string; border: string; text: string }> = {
  Kurk: { bg: '#FEF9C3', border: '#FDE047', text: '#854D0E' },
  Berk: { bg: '#DCFCE7', border: '#86EFAC', text: '#166534' },
  '3D': { bg: '#EDE9FE', border: '#C4B5FD', text: '#5B21B6' },
};

function TypeToggle({
  type,
  selected,
  onPress,
}: {
  type: InsoleType;
  selected: boolean;
  onPress: () => void;
}) {
  const c = TYPE_COLORS[type];
  return (
    <TouchableOpacity
      onPress={onPress}
      style={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 6,
        paddingHorizontal: 12,
        paddingVertical: 7,
        borderRadius: 999,
        borderWidth: 2,
        borderColor: selected ? c.border : '#E5E7EB',
        backgroundColor: selected ? c.bg : '#F9FAFB',
      }}
    >
      {selected && <Check size={13} color={c.text} />}
      <Text
        style={{
          fontSize: 13,
          fontWeight: '600',
          color: selected ? c.text : '#9CA3AF',
          fontFamily: 'Inter_600SemiBold',
        }}
      >
        {type}
      </Text>
    </TouchableOpacity>
  );
}

function TypeBadge({ type }: { type: InsoleType }) {
  const c = TYPE_COLORS[type];
  return (
    <View
      style={{
        paddingHorizontal: 8,
        paddingVertical: 3,
        borderRadius: 999,
        backgroundColor: c.bg,
        borderWidth: 1,
        borderColor: c.border,
      }}
    >
      <Text
        style={{ fontSize: 11, fontWeight: '600', color: c.text, fontFamily: 'Inter_600SemiBold' }}
      >
        {type}
      </Text>
    </View>
  );
}

export default function TasksScreen() {
  const insets = useSafeAreaInsets();
  const queryClient = useQueryClient();
  const [fontsLoaded, fontError] = useFonts({ Inter_400Regular, Inter_600SemiBold });

  const [newTaskName, setNewTaskName] = useState('');
  const [newTaskTypes, setNewTaskTypes] = useState<InsoleType[]>(['Kurk', 'Berk', '3D']);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editingName, setEditingName] = useState('');
  const [editingTypes, setEditingTypes] = useState<InsoleType[]>([]);

  const { data: tasks = [], isLoading } = useQuery({
    queryKey: ['tasks'],
    queryFn: async () => {
      const res = await fetch(`${BASE_URL}/api/tasks`);
      if (!res.ok) throw new Error('Failed to fetch tasks');
      return res.json();
    },
  });

  const addTaskMutation = useMutation({
    mutationFn: async ({ name, insole_types }: { name: string; insole_types: string[] }) => {
      const res = await fetch(`${BASE_URL}/api/tasks`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, insole_types }),
      });
      if (!res.ok) throw new Error('Failed to add task');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      setNewTaskName('');
      setNewTaskTypes(['Kurk', 'Berk', '3D']);
    },
  });

  const updateTaskMutation = useMutation({
    mutationFn: async ({
      id,
      name,
      insole_types,
    }: {
      id: number;
      name: string;
      insole_types: string[];
    }) => {
      const res = await fetch(`${BASE_URL}/api/tasks/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, insole_types }),
      });
      if (!res.ok) throw new Error('Failed to update task');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      setEditingId(null);
    },
  });

  const deleteTaskMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await fetch(`${BASE_URL}/api/tasks/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to delete task');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      queryClient.invalidateQueries({ queryKey: ['logs'] });
    },
  });

  const toggleNewType = (type: InsoleType) => {
    setNewTaskTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
    );
  };

  const toggleEditType = (type: InsoleType) => {
    setEditingTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
    );
  };

  const handleAddTask = () => {
    if (!newTaskName.trim() || newTaskTypes.length === 0) return;
    addTaskMutation.mutate({ name: newTaskName.trim(), insole_types: newTaskTypes });
  };

  const handleStartEdit = (task: any) => {
    setEditingId(task.id);
    setEditingName(task.name);
    setEditingTypes(Array.isArray(task.insole_types) ? task.insole_types : ['Kurk', 'Berk', '3D']);
  };

  const handleConfirmEdit = () => {
    if (!editingName.trim() || editingId === null || editingTypes.length === 0) return;
    updateTaskMutation.mutate({
      id: editingId,
      name: editingName.trim(),
      insole_types: editingTypes,
    });
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setEditingName('');
    setEditingTypes([]);
  };

  const handleDelete = (task: any) => {
    Alert.alert(
      'Taak verwijderen',
      `"${task.name}" verwijderen? Alle tijdsregistraties voor deze taak worden ook verwijderd.`,
      [
        { text: 'Annuleren', style: 'cancel' },
        {
          text: 'Verwijderen',
          style: 'destructive',
          onPress: () => deleteTaskMutation.mutate(task.id),
        },
      ]
    );
  };

  if (!fontsLoaded && !fontError) return null;

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, backgroundColor: '#ffffff' }}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <View style={{ paddingTop: insets.top, flex: 1 }}>
        {/* Header */}
        <View
          style={{
            paddingHorizontal: 24,
            paddingVertical: 16,
            borderBottomWidth: 1,
            borderBottomColor: '#E5E7EB',
          }}
        >
          <Text
            style={{
              fontSize: 24,
              fontWeight: '600',
              color: '#111827',
              fontFamily: 'Inter_600SemiBold',
            }}
          >
            Instellingen
          </Text>
          <Text
            style={{ fontSize: 14, color: '#6B7280', marginTop: 4, fontFamily: 'Inter_400Regular' }}
          >
            Beheer handelingen per zooltype
          </Text>
        </View>

        <ScrollView
          contentContainerStyle={{ padding: 20, paddingBottom: 60 }}
          keyboardShouldPersistTaps="handled"
        >
          {/* Add New Task */}
          <View
            style={{
              backgroundColor: '#F9FAFB',
              borderRadius: 16,
              padding: 16,
              borderWidth: 1,
              borderColor: '#E5E7EB',
              marginBottom: 28,
            }}
          >
            <Text
              style={{
                fontSize: 12,
                fontWeight: '600',
                color: '#6B7280',
                marginBottom: 12,
                textTransform: 'uppercase',
                letterSpacing: 0.5,
                fontFamily: 'Inter_600SemiBold',
              }}
            >
              Nieuwe handeling toevoegen
            </Text>

            {/* Name input */}
            <TextInput
              value={newTaskName}
              onChangeText={setNewTaskName}
              placeholder="Naam van de stap, bijv. Leerrand"
              placeholderTextColor="#9CA3AF"
              returnKeyType="done"
              onSubmitEditing={handleAddTask}
              style={{
                backgroundColor: '#ffffff',
                borderWidth: 1,
                borderColor: '#E5E7EB',
                borderRadius: 10,
                paddingHorizontal: 14,
                paddingVertical: 11,
                fontSize: 15,
                color: '#111827',
                fontFamily: 'Inter_400Regular',
                marginBottom: 12,
              }}
            />

            {/* Insole type toggles */}
            <Text
              style={{
                fontSize: 11,
                fontWeight: '600',
                color: '#9CA3AF',
                marginBottom: 8,
                textTransform: 'uppercase',
                letterSpacing: 0.4,
                fontFamily: 'Inter_600SemiBold',
              }}
            >
              Van toepassing op
            </Text>
            <View style={{ flexDirection: 'row', gap: 8, marginBottom: 14 }}>
              {ALL_TYPES.map((type) => (
                <TypeToggle
                  key={type}
                  type={type}
                  selected={newTaskTypes.includes(type)}
                  onPress={() => toggleNewType(type)}
                />
              ))}
            </View>

            <TouchableOpacity
              onPress={handleAddTask}
              disabled={
                addTaskMutation.isPending || !newTaskName.trim() || newTaskTypes.length === 0
              }
              style={{
                backgroundColor:
                  newTaskName.trim() && newTaskTypes.length > 0 ? '#2563EB' : '#E5E7EB',
                borderRadius: 10,
                paddingVertical: 12,
                alignItems: 'center',
                justifyContent: 'center',
                flexDirection: 'row',
                gap: 8,
              }}
            >
              {addTaskMutation.isPending ? (
                <ActivityIndicator color="white" size="small" />
              ) : (
                <>
                  <Plus
                    color={newTaskName.trim() && newTaskTypes.length > 0 ? 'white' : '#9CA3AF'}
                    size={18}
                  />
                  <Text
                    style={{
                      color: newTaskName.trim() && newTaskTypes.length > 0 ? 'white' : '#9CA3AF',
                      fontSize: 15,
                      fontWeight: '600',
                      fontFamily: 'Inter_600SemiBold',
                    }}
                  >
                    Stap toevoegen
                  </Text>
                </>
              )}
            </TouchableOpacity>
          </View>

          {/* Task List */}
          <Text
            style={{
              fontSize: 12,
              fontWeight: '600',
              color: '#6B7280',
              marginBottom: 12,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
              fontFamily: 'Inter_600SemiBold',
            }}
          >
            Huidige stappen ({tasks.length})
          </Text>

          {isLoading ? (
            <ActivityIndicator color="#2563EB" style={{ marginTop: 40 }} />
          ) : tasks.length === 0 ? (
            <View style={{ alignItems: 'center', marginTop: 40 }}>
              <Text style={{ color: '#9CA3AF', fontSize: 15, fontFamily: 'Inter_400Regular' }}>
                Nog geen stappen. Voeg er een toe hierboven.
              </Text>
            </View>
          ) : (
            tasks.map((task: any) => {
              const types: InsoleType[] = Array.isArray(task.insole_types) ? task.insole_types : [];
              const isEditing = editingId === task.id;

              return (
                <View
                  key={task.id}
                  style={{
                    backgroundColor: '#ffffff',
                    borderRadius: 12,
                    borderWidth: 1,
                    borderColor: isEditing ? '#2563EB' : '#E5E7EB',
                    padding: 14,
                    marginBottom: 10,
                  }}
                >
                  {isEditing ? (
                    <>
                      {/* Edit name */}
                      <TextInput
                        value={editingName}
                        onChangeText={setEditingName}
                        autoFocus
                        returnKeyType="done"
                        onSubmitEditing={handleConfirmEdit}
                        style={{
                          fontSize: 15,
                          color: '#111827',
                          fontFamily: 'Inter_400Regular',
                          borderBottomWidth: 1,
                          borderBottomColor: '#E5E7EB',
                          paddingBottom: 8,
                          marginBottom: 12,
                        }}
                      />

                      {/* Edit insole types */}
                      <Text
                        style={{
                          fontSize: 11,
                          fontWeight: '600',
                          color: '#9CA3AF',
                          marginBottom: 8,
                          textTransform: 'uppercase',
                          letterSpacing: 0.4,
                          fontFamily: 'Inter_600SemiBold',
                        }}
                      >
                        Van toepassing op
                      </Text>
                      <View style={{ flexDirection: 'row', gap: 8, marginBottom: 14 }}>
                        {ALL_TYPES.map((type) => (
                          <TypeToggle
                            key={type}
                            type={type}
                            selected={editingTypes.includes(type)}
                            onPress={() => toggleEditType(type)}
                          />
                        ))}
                      </View>

                      {/* Confirm / Cancel */}
                      <View style={{ flexDirection: 'row', gap: 8 }}>
                        <TouchableOpacity
                          onPress={handleConfirmEdit}
                          disabled={updateTaskMutation.isPending || editingTypes.length === 0}
                          style={{
                            flex: 1,
                            backgroundColor: '#DCFCE7',
                            borderRadius: 8,
                            paddingVertical: 10,
                            alignItems: 'center',
                            justifyContent: 'center',
                            flexDirection: 'row',
                            gap: 6,
                          }}
                        >
                          {updateTaskMutation.isPending ? (
                            <ActivityIndicator color="#16A34A" size="small" />
                          ) : (
                            <>
                              <Check size={16} color="#16A34A" />
                              <Text
                                style={{
                                  color: '#16A34A',
                                  fontWeight: '600',
                                  fontFamily: 'Inter_600SemiBold',
                                  fontSize: 14,
                                }}
                              >
                                Opslaan
                              </Text>
                            </>
                          )}
                        </TouchableOpacity>
                        <TouchableOpacity
                          onPress={handleCancelEdit}
                          style={{
                            flex: 1,
                            backgroundColor: '#F3F4F6',
                            borderRadius: 8,
                            paddingVertical: 10,
                            alignItems: 'center',
                            justifyContent: 'center',
                            flexDirection: 'row',
                            gap: 6,
                          }}
                        >
                          <X size={16} color="#6B7280" />
                          <Text
                            style={{
                              color: '#6B7280',
                              fontWeight: '600',
                              fontFamily: 'Inter_600SemiBold',
                              fontSize: 14,
                            }}
                          >
                            Annuleren
                          </Text>
                        </TouchableOpacity>
                      </View>
                    </>
                  ) : (
                    <>
                      {/* Task name + actions */}
                      <View
                        style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 }}
                      >
                        <Text
                          style={{
                            flex: 1,
                            fontSize: 15,
                            color: '#374151',
                            fontFamily: 'Inter_400Regular',
                          }}
                        >
                          {task.name}
                        </Text>
                        <View style={{ flexDirection: 'row', gap: 8 }}>
                          <TouchableOpacity
                            onPress={() => handleStartEdit(task)}
                            style={{
                              backgroundColor: '#EFF6FF',
                              borderRadius: 8,
                              width: 36,
                              height: 36,
                              alignItems: 'center',
                              justifyContent: 'center',
                            }}
                          >
                            <Pencil color="#2563EB" size={16} />
                          </TouchableOpacity>
                          <TouchableOpacity
                            onPress={() => handleDelete(task)}
                            disabled={deleteTaskMutation.isPending}
                            style={{
                              backgroundColor: '#FEF2F2',
                              borderRadius: 8,
                              width: 36,
                              height: 36,
                              alignItems: 'center',
                              justifyContent: 'center',
                            }}
                          >
                            <Trash2 color="#DC2626" size={16} />
                          </TouchableOpacity>
                        </View>
                      </View>

                      {/* Insole type badges */}
                      <View style={{ flexDirection: 'row', gap: 6 }}>
                        {types.map((type) => (
                          <TypeBadge key={type} type={type} />
                        ))}
                      </View>
                    </>
                  )}
                </View>
              );
            })
          )}
        </ScrollView>
      </View>
    </KeyboardAvoidingView>
  );
}
