import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import { View, Text, StyleSheet, Animated, RefreshControl, Alert, TouchableOpacity } from 'react-native';
import { useTasks } from '@/hooks/useTasks';
import { useTaskModals } from '@/hooks/useTaskModals';
import { TaskItem } from './TaskItem';
import { SubtaskItem } from './SubtaskItem';
import { TaskData, SubtaskData } from '@/types';
import Task from '@/models/Task';
import { useSettings } from '@/theme';
import {
  toggleTaskComplete,
  deleteTask,
  setTaskCompleted,
  convertTaskToSubtask,
  convertSubtaskToTask,
  moveSubtaskToTask,
  toggleSubtaskComplete,
  fetchSubtaskTree,
} from '@/utils/taskActions';
import Svg, { Path, Rect } from 'react-native-svg';

interface TaskListProps {
  categoryId?: string;
  onSelectionChange?: (active: boolean) => void;
}

const PRIORITY_RANK: Record<string, number> = { none: 0, low: 1, medium: 2, high: 3, critical: 4 };

const SEPARATOR = () => <View style={styles.separator} />;
const MemoSeparator = React.memo(SEPARATOR);

const DropIndicator = ({ theme }: { theme: any }) => (
  <View style={styles.dropIndicatorContainer}>
    <View style={[styles.dropIndicator, { backgroundColor: theme.accent }]} />
    <View style={[styles.dropIndicatorDot, { backgroundColor: theme.accent }]} />
    <View style={[styles.dropIndicatorDot, { backgroundColor: theme.accent }]} />
  </View>
);

export function TaskList({ categoryId = 'all', onSelectionChange }: TaskListProps) {
  const { theme, sortBy } = useSettings();

  const { tasks, loading } = useTasks(categoryId, false);
  const { tasks: completedTasks } = useTasks(categoryId, true);

  const [refreshing, setRefreshing] = useState(false);
  const [selectionMode, setSelectionMode] = useState(false);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [hoverTaskId, setHoverTaskId] = useState<string | null>(null);
  const [expandedTasks, setExpandedTasks] = useState<Set<string>>(new Set());
  const [completedShown, setCompletedShown] = useState(false);
  const [subtasksMap, setSubtasksMap] = useState<Map<string, SubtaskData[]>>(new Map());
  const [dropIndicator, setDropIndicator] = useState<{ targetId: string | null; position: 'above' | 'below' } | null>(null);
  const itemRefs = useRef<Map<string, View>>(new Map());
  const dragStateRef = useRef<{ taskId: string; positions: Record<string, { top: number; bottom: number }> } | null>(null);
  const subtaskDragRef = useRef<{ subtaskId: string; parentTaskId: string; positions: Record<string, { top: number; bottom: number }> } | null>(null);
   const {
      modals,
      openTaskMenu,
      openTaskDelete,
      openSubtaskMenu,
      openSubtaskDelete,
      openSubtaskEdit,
    } = useTaskModals();

  const registerRef = useCallback((taskId: string, ref: View | null) => {
    if (ref) {
      itemRefs.current.set(taskId, ref);
    } else {
      itemRefs.current.delete(taskId);
    }
  }, []);

  const sortedTasks = useMemo(() => {
    const sorted = [...tasks];
    switch (sortBy) {
      case 'date':
        sorted.sort((a, b) => (a.dueDate || Number.MAX_SAFE_INTEGER) - (b.dueDate || Number.MAX_SAFE_INTEGER));
        break;
      case 'priority':
        sorted.sort((a, b) => PRIORITY_RANK[b.priority] - PRIORITY_RANK[a.priority]);
        break;
      case 'alpha':
        sorted.sort((a, b) => a.title.localeCompare(b.title));
        break;
      case 'created':
        sorted.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
        break;
    }
    return sorted;
  }, [tasks, sortBy]);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    setTimeout(() => setRefreshing(false), 600);
  }, []);

  const exitSelection = useCallback(() => {
    setSelectionMode(false);
    setSelectedIds(new Set());
    onSelectionChange?.(false);
  }, [onSelectionChange]);

  const enterSelection = useCallback((taskId: string) => {
    setSelectionMode(true);
    setSelectedIds(new Set([taskId]));
    onSelectionChange?.(true);
  }, [onSelectionChange]);

  const toggleSelect = useCallback((taskId: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(taskId)) {
        next.delete(taskId);
      } else {
        next.add(taskId);
      }
      if (next.size === 0) {
        setSelectionMode(false);
        onSelectionChange?.(false);
      }
      return next;
    });
  }, [onSelectionChange]);

  const fetchSubtasks = useCallback(async (taskId: string) => {
    const withNested = await fetchSubtaskTree(taskId);
    setSubtasksMap((prev) => new Map(prev).set(taskId, withNested));
    return withNested;
  }, []);

  const refreshAll = useCallback(() => {
    for (const taskId of expandedTasks) {
      fetchSubtasks(taskId);
    }
  }, [expandedTasks, fetchSubtasks]);

  const handleToggle = useCallback(async (taskId: string, showCompleted = true) => {
    await toggleTaskComplete(taskId);
    if (showCompleted) setCompletedShown(true);
    refreshAll();
  }, [refreshAll]);

  const toggleExpand = useCallback(async (taskId: string) => {
    setExpandedTasks((prev) => {
      const next = new Set(prev);
      if (next.has(taskId)) {
        next.delete(taskId);
      } else {
        next.add(taskId);
      }
      return next;
    });

    const isCurrentlyExpanded = expandedTasks.has(taskId);
    if (isCurrentlyExpanded) {
      setSubtasksMap((prev) => {
        const next = new Map(prev);
        next.delete(taskId);
        return next;
      });
    } else {
      await fetchSubtasks(taskId);
    }
  }, [expandedTasks, fetchSubtasks]);

  const handleSubtaskToggle = useCallback(async (subtaskId: string, taskId: string) => {
    await toggleSubtaskComplete(subtaskId);
    await fetchSubtasks(taskId);
  }, [fetchSubtasks]);

  const handleBulkDelete = useCallback(() => {
    Alert.alert(`Delete ${selectedIds.size} task${selectedIds.size > 1 ? 's' : ''}?`, 'This cannot be undone.', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          await Promise.all(Array.from(selectedIds).map(taskId => deleteTask(taskId)));
          exitSelection();
          refreshAll();
        },
      },
    ]);
  }, [selectedIds, exitSelection, refreshAll]);

  const handleBulkComplete = useCallback(async () => {
    await Promise.all(Array.from(selectedIds).map(taskId => setTaskCompleted(taskId, true)));
    setCompletedShown(true);
    exitSelection();
    refreshAll();
  }, [selectedIds, exitSelection, refreshAll]);

  const measureItems = useCallback(async () => {
    const positions: Record<string, { top: number; bottom: number }> = {};
    const entries = Array.from(itemRefs.current.entries());
    await Promise.all(entries.map(([id, ref]) => {
      return new Promise<void>((resolve) => {
        ref?.measureInWindow((_x, y, _w, h) => {
          positions[id] = { top: y, bottom: y + h };
          resolve();
        });
      });
    }));
    return positions;
  }, []);

  const findHoverTarget = useCallback((absoluteY: number, draggedId: string, positions: Record<string, { top: number; bottom: number }>) => {
    for (const [id, p] of Object.entries(positions)) {
      if (id === draggedId) continue;
      if (absoluteY >= p.top && absoluteY <= p.bottom) {
        return id;
      }
    }
    return null;
  }, []);

  const calculateDropPosition = useCallback((absoluteY: number, targetId: string, positions: Record<string, { top: number; bottom: number }>) => {
    const target = positions[targetId];
    if (!target) return 'below' as const;
    const middle = (target.top + target.bottom) / 2;
    return absoluteY < middle ? 'above' : 'below';
  }, []);

  const handleDragStart = useCallback(async (taskId: string) => {
    dragStateRef.current = { taskId, positions: await measureItems() };
  }, [measureItems]);

  const handleDragUpdate = useCallback((absoluteY: number) => {
    const state = dragStateRef.current;
    if (!state) return;
    const target = findHoverTarget(absoluteY, state.taskId, state.positions);
    setHoverTaskId((prev) => (prev === target ? prev : target));
    if (target) {
      const position = calculateDropPosition(absoluteY, target, state.positions);
      setDropIndicator({ targetId: target, position });
    } else {
      // Check if below last item
      const positions = state.positions;
      const lastItem = Object.values(positions).reduce((max, p) => p.bottom > max.bottom ? p : max, { bottom: 0 });
      if (absoluteY > lastItem.bottom) {
        setDropIndicator({ targetId: null, position: 'below' });
      } else {
        setDropIndicator(null);
      }
    }
  }, [findHoverTarget, calculateDropPosition]);

  const handleDragEnd = useCallback((absoluteY: number) => {
    const state = dragStateRef.current;
    dragStateRef.current = null;
    setHoverTaskId(null);
    setDropIndicator(null);
    if (!state) return;

    const target = findHoverTarget(absoluteY, state.taskId, state.positions);
    if (target) {
      (async () => {
        await convertTaskToSubtask(state.taskId, target);
        refreshAll();
      })();
    }
  }, [findHoverTarget, refreshAll]);

  const handleSubtaskDragStart = useCallback(async (subtaskId: string, parentTaskId: string) => {
    subtaskDragRef.current = { subtaskId, parentTaskId, positions: await measureItems() };
  }, [measureItems]);

  const handleSubtaskDragUpdate = useCallback((absoluteY: number) => {
    const state = subtaskDragRef.current;
    if (!state) return;
    const target = findHoverTarget(absoluteY, state.subtaskId, state.positions);
    setHoverTaskId((prev) => (prev === target ? prev : target));
  }, [findHoverTarget]);

  const handleSubtaskDragEnd = useCallback(async (absoluteY: number) => {
    const state = subtaskDragRef.current;
    subtaskDragRef.current = null;
    setHoverTaskId(null);
    setDropIndicator(null);
    if (!state) return;

    const target = findHoverTarget(absoluteY, state.subtaskId, state.positions);
    if (target === state.parentTaskId) return;

    if (target) {
      await moveSubtaskToTask(state.subtaskId, target);
      await fetchSubtasks(target);
    } else {
      await convertSubtaskToTask(state.subtaskId);
    }
    await fetchSubtasks(state.parentTaskId);
    refreshAll();
  }, [findHoverTarget, fetchSubtasks, refreshAll]);

  const renderItem = useCallback(
    ({ item, index }: { item: Task; index: number }) => {
      const isExpanded = expandedTasks.has(item.id);
      const itemSubtasks = subtasksMap.get(item.id) ?? [];
      const showDropAbove = dropIndicator?.targetId === item.id && dropIndicator?.position === 'above';
      const showDropBelow = dropIndicator?.targetId === item.id && dropIndicator?.position === 'below';
      return (
        <View>
          {showDropAbove && <DropIndicator theme={theme} />}
          <TaskRow
            task={item}
            expanded={isExpanded}
            subtasks={itemSubtasks}
            selected={selectedIds.has(item.id)}
            selectionMode={selectionMode}
            hovered={hoverTaskId === item.id}
            registerRef={registerRef}
            onToggle={handleToggle}
            onDelete={openTaskDelete}
            onExpand={toggleExpand}
            onSelect={toggleSelect}
            onEnterSelection={enterSelection}
            onMenuOpen={openTaskMenu}
            onSubtaskToggle={handleSubtaskToggle}
            onSubtaskDelete={openSubtaskDelete}
            onSubtaskEdit={openSubtaskEdit}
            onSubtaskMenuOpen={openSubtaskMenu}
            onDragStart={handleDragStart}
            onDragUpdate={handleDragUpdate}
            onDragEnd={handleDragEnd}
            onSubtaskDragStart={handleSubtaskDragStart}
            onSubtaskDragUpdate={handleSubtaskDragUpdate}
            onSubtaskDragEnd={handleSubtaskDragEnd}
            onReorderStart={() => handleDragStart(item.id)}
            onReorderUpdate={handleDragUpdate}
            onReorderEnd={handleDragEnd}
            selectedIds={selectedIds}
          />
          {showDropBelow && <DropIndicator theme={theme} />}
        </View>
      );
    },
    [
      expandedTasks,
      subtasksMap,
      selectedIds,
      selectionMode,
      hoverTaskId,
      dropIndicator,
      theme,
      registerRef,
      handleToggle,
      openTaskDelete,
      toggleExpand,
      toggleSelect,
      enterSelection,
      openTaskMenu,
      handleSubtaskToggle,
      openSubtaskDelete,
      openSubtaskEdit,
      openSubtaskMenu,
      handleDragStart,
      handleDragUpdate,
      handleDragEnd,
      handleSubtaskDragStart,
      handleSubtaskDragUpdate,
      handleSubtaskDragEnd,
    ]
  );

  const listHeader = useMemo(() => {
    if (sortedTasks.length > 0 || completedTasks.length > 0) return null;
    return (
      <View style={styles.emptyState}>
        <Text style={[styles.emptyText, { color: theme.textSecondary }]}>No tasks yet</Text>
        <Text style={[styles.emptySubtext, { color: theme.textMuted }]}>Tap + to add your first task</Text>
      </View>
    );
  }, [sortedTasks.length, completedTasks.length, theme.textSecondary, theme.textMuted]);

  const listFooter = useMemo(() => {
    const footerContent = completedTasks.length === 0 ? null : (
      <CompletedSection
        tasks={completedTasks}
        shown={completedShown}
        onShownChange={setCompletedShown}
        onToggle={(task) => handleToggle(task.id, false)}
        onDelete={openTaskDelete}
        onMenuOpen={openTaskMenu}
        onLongPress={(task) => enterSelection(task.id)}
        selectionMode={selectionMode}
        selectedIds={selectedIds}
        onSelect={toggleSelect}
        onFetchSubtasks={fetchSubtasks}
        subtasksMap={subtasksMap}
        onSubtaskToggle={handleSubtaskToggle}
        onSubtaskDelete={openSubtaskDelete}
        onSubtaskEdit={openSubtaskEdit}
        onSubtaskMenuOpen={openSubtaskMenu}
      />
    );

    const showDropAtEnd = dropIndicator && dropIndicator.targetId === null;

    return (
      <View>
        {footerContent}
        {showDropAtEnd && <DropIndicator theme={theme} />}
      </View>
    );
  }, [
    completedTasks,
    completedShown,
    handleToggle,
    openTaskDelete,
    openTaskMenu,
    enterSelection,
    selectionMode,
    selectedIds,
    toggleSelect,
    fetchSubtasks,
    subtasksMap,
    handleSubtaskToggle,
    openSubtaskDelete,
    openSubtaskEdit,
    openSubtaskMenu,
    dropIndicator,
    theme,
  ]);

  if (loading && !refreshing) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={[styles.loadingText, { color: theme.textFaint }]}>Loading tasks...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Animated.FlatList
        data={sortedTasks}
        keyExtractor={(item) => item.id}
        renderItem={renderItem}
        extraData={{ expandedTasks, subtasksMap, selectedIds, selectionMode, hoverTaskId, dropIndicator }}
        ItemSeparatorComponent={MemoSeparator}
        ListHeaderComponent={listHeader}
        ListFooterComponent={listFooter}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={theme.accent}
            colors={[theme.accent]}
            progressBackgroundColor={theme.card}
          />
        }
        contentContainerStyle={styles.listContent}
      />

      {modals(refreshAll)}

      {selectionMode && (
        <View style={[styles.selectionBar, { backgroundColor: theme.sheetBg, borderTopColor: theme.border }]}>
          <TouchableOpacity onPress={exitSelection} style={styles.selectionCancel} activeOpacity={0.7}>
            <Svg width={20} height={20} viewBox="0 0 24 24">
              <Path d="M18 6L6 18M6 6l12 12" stroke={theme.textFaint} strokeWidth={2} strokeLinecap="round" />
            </Svg>
            <Text style={[styles.selectionCancelText, { color: theme.textFaint }]}>Cancel</Text>
          </TouchableOpacity>
          <Text style={[styles.selectionCount, { color: theme.text }]}>{selectedIds.size} selected</Text>
          <View style={styles.selectionActions}>
            <SelectionButton label="Complete" color="#43A047" onPress={handleBulkComplete} />
            <SelectionButton label="Delete" color="#E53935" onPress={handleBulkDelete} />
          </View>
        </View>
      )}
    </View>
  );
}

const SelectionButton = React.memo(function SelectionButton({ label, color, onPress }: { label: string; color: string; onPress: () => void }) {
  return (
    <TouchableOpacity
      style={[styles.selectionButton, { backgroundColor: color }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <Text style={styles.selectionButtonText}>{label}</Text>
    </TouchableOpacity>
  );
});

interface TaskRowProps {
  task: Task;
  expanded: boolean;
  subtasks: SubtaskData[];
  selected: boolean;
  selectionMode: boolean;
  hovered: boolean;
  registerRef: (taskId: string, ref: View | null) => void;
  onToggle: (taskId: string) => void | Promise<void>;
  onDelete: (task: Task) => void;
  onExpand: (taskId: string) => void | Promise<void>;
  onSelect: (taskId: string) => void;
  onEnterSelection: (taskId: string) => void;
  onMenuOpen: (task: Task) => void;
  onSubtaskToggle: (subtaskId: string, taskId: string) => void;
  onSubtaskDelete: (subtask: SubtaskData) => void;
  onSubtaskEdit: (subtaskId: string) => void;
  onSubtaskMenuOpen: (subtask: SubtaskData) => void;
  onDragStart: (taskId: string) => void;
  onDragUpdate: (absoluteY: number) => void;
  onDragEnd: (absoluteY: number) => void;
  onSubtaskDragStart: (subtaskId: string, parentTaskId: string) => void;
  onSubtaskDragUpdate: (absoluteY: number) => void;
  onSubtaskDragEnd: (absoluteY: number) => void;
  onReorderStart: () => void;
  onReorderUpdate: (absoluteY: number) => void;
  onReorderEnd: (absoluteY: number, translationY: number) => void;
  selectedIds: Set<string>;
}

const TaskRow = React.memo(function TaskRow({
  task,
  expanded,
  subtasks,
  selected,
  selectionMode,
  hovered,
  registerRef,
  onToggle,
  onDelete,
  onExpand,
  onSelect,
  onEnterSelection,
  onMenuOpen,
  onSubtaskToggle,
  onSubtaskDelete,
  onSubtaskEdit,
  onSubtaskMenuOpen,
  onDragStart,
  onDragUpdate,
  onDragEnd,
  onSubtaskDragStart,
  onSubtaskDragUpdate,
  onSubtaskDragEnd,
  onReorderStart,
  onReorderUpdate,
  onReorderEnd,
  selectedIds,
}: TaskRowProps) {
  const sortedSubtasks = useMemo(
    () => subtasks.slice().sort((a, b) => a.order - b.order),
    [subtasks]
  );
  return (
    <View
      ref={(ref) => registerRef(task.id, ref)}
      style={styles.dragContainer}
    >
      <TaskItem
        task={task as unknown as TaskData}
        onToggle={() => onToggle(task.id)}
        onDelete={() => onDelete(task)}
        onPress={() => (selectionMode ? onSelect(task.id) : onExpand(task.id))}
        onLongPress={selectionMode ? undefined : () => onEnterSelection(task.id)}
        onMenuOpen={() => onMenuOpen(task)}
        selected={selected}
        selectionMode={selectionMode}
        expanded={expanded}
        draggable
        hovered={hovered}
        onDragStart={() => onDragStart(task.id)}
        onDragUpdate={onDragUpdate}
        onDragEnd={onDragEnd}
        onReorderStart={onReorderStart}
        onReorderUpdate={onReorderUpdate}
        onReorderEnd={onReorderEnd}
      />
      {expanded && subtasks.length > 0 && (
        <View style={styles.subtaskList}>
          {sortedSubtasks.map((sub) => (
            <SubtaskItem
              key={sub.id}
              subtask={sub}
              onToggle={() => onSubtaskToggle(sub.id, task.id)}
              onDelete={() => onSubtaskDelete(sub)}
              onPress={() => onSubtaskEdit(sub.id)}
              onMenuOpen={() => onSubtaskMenuOpen(sub)}
              selected={selectedIds.has(sub.id)}
              selectionMode={selectionMode}
              draggable
              onDragStart={() => onSubtaskDragStart(sub.id, task.id)}
              onDragUpdate={onSubtaskDragUpdate}
              onDragEnd={onSubtaskDragEnd}
            />
          ))}
        </View>
      )}
     </View>
    );
});

interface CompletedSectionProps {
  tasks: TaskData[];
  shown: boolean;
  onShownChange: (shown: boolean) => void;
  onToggle: (task: TaskData) => void;
  onDelete: (task: TaskData) => void;
  onMenuOpen: (task: TaskData) => void;
  onLongPress: (task: TaskData) => void;
  selectionMode: boolean;
  selectedIds: Set<string>;
  onSelect: (taskId: string) => void;
  onFetchSubtasks: (taskId: string) => Promise<SubtaskData[]>;
  subtasksMap: Map<string, SubtaskData[]>;
  onSubtaskToggle: (subtaskId: string, taskId: string) => void;
  onSubtaskDelete: (subtask: SubtaskData) => void;
  onSubtaskEdit: (subtaskId: string) => void;
  onSubtaskMenuOpen: (subtask: SubtaskData) => void;
}

const CompletedSection = React.memo(function CompletedSection({ tasks, shown, onShownChange, onToggle, onDelete, onMenuOpen, onLongPress, selectionMode, selectedIds, onSelect, onFetchSubtasks, subtasksMap, onSubtaskToggle, onSubtaskDelete, onSubtaskEdit, onSubtaskMenuOpen }: CompletedSectionProps) {
  const { theme } = useSettings();
  const [openTasks, setOpenTasks] = useState<Set<string>>(new Set(tasks.map((t) => t.id)));
  const fetchedRef = useRef<Set<string>>(new Set());

  useEffect(() => {
    setOpenTasks((prev) => {
      const next = new Set(prev);
      let changed = false;
      for (const t of tasks) {
        if (!next.has(t.id)) {
          next.add(t.id);
          changed = true;
        }
      }
      return changed ? next : prev;
    });
    for (const t of tasks) {
      if (!fetchedRef.current.has(t.id)) {
        fetchedRef.current.add(t.id);
        onFetchSubtasks(t.id);
      }
    }
  }, [tasks, onFetchSubtasks]);

  const toggleOpen = useCallback((taskId: string) => {
    setOpenTasks((prev) => {
      const next = new Set(prev);
      if (next.has(taskId)) {
        next.delete(taskId);
      } else {
        next.add(taskId);
      }
      return next;
    });
  }, []);

  return (
    <View style={styles.completedSection}>
      <TouchableOpacity
        style={styles.completedHeader}
        onPress={() => onShownChange(!shown)}
      >
        <Text style={[styles.completedTitle, { color: theme.textFaint }]}>
          Completed ({tasks.length})
        </Text>
        <Text style={[styles.completedToggle, { color: theme.accent }]}>
          {shown ? 'Hide' : 'Show'}
        </Text>
      </TouchableOpacity>
      {shown && (
        <View style={styles.completedList}>
          {tasks.map((task) => {
            const isOpen = openTasks.has(task.id);
            const subtasks = (subtasksMap.get(task.id) ?? [])
              .slice()
              .sort((a, b) => a.order - b.order);
            return (
              <View key={task.id}>
                <TaskItem
                  task={task}
                  onToggle={() => onToggle(task)}
                  onDelete={() => onDelete(task)}
                  onPress={() => (selectionMode ? onSelect(task.id) : toggleOpen(task.id))}
                  onLongPress={() => onLongPress(task)}
                  onMenuOpen={() => onMenuOpen(task)}
                  selected={selectedIds.has(task.id)}
                  selectionMode={selectionMode}
                  completedSection
                  expanded={isOpen}
                />
                {isOpen && subtasks.length > 0 && (
                  <View style={styles.completedSubtasks}>
                    {subtasks.map((sub) => (
                      <SubtaskItem
                        key={sub.id}
                        subtask={sub}
                        onToggle={() => onSubtaskToggle(sub.id, task.id)}
                        onDelete={() => onSubtaskDelete(sub)}
                        onPress={() => onSubtaskEdit(sub.id)}
                        onMenuOpen={() => onSubtaskMenuOpen(sub)}
                      />
                    ))}
                  </View>
                )}
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  listContent: {
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 120,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    fontSize: 16,
  },
  separator: {
    height: 8,
  },
  subtaskList: {
    paddingLeft: 8,
    paddingRight: 4,
    paddingTop: 8,
  },
  completedSubtasks: {
    paddingLeft: 8,
    paddingRight: 4,
    paddingTop: 4,
    marginBottom: 4,
  },
  dragContainer: {
  },
  dropIndicatorContainer: {
    height: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  dropIndicator: {
    width: '80%',
    height: 2,
    borderRadius: 1,
  },
  dropIndicatorDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    position: 'absolute',
  },
  emptyState: {
    alignItems: 'center',
    paddingVertical: 48,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 4,
  },
  emptySubtext: {
    fontSize: 14,
  },
  completedSection: {
    marginTop: 16,
    paddingBottom: 24,
  },
  completedHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 4,
    paddingVertical: 8,
  },
  completedTitle: {
    fontSize: 14,
    fontWeight: '600',
  },
  completedToggle: {
    fontSize: 14,
    fontWeight: '500',
  },
  completedList: {
    paddingTop: 8,
  },
  selectionBar: {
    position: 'absolute',
    left: 16,
    right: 16,
    bottom: 84,
    borderRadius: 20,
    borderWidth: 1,
    paddingHorizontal: 16,
    paddingVertical: 12,
    gap: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 12,
    elevation: 8,
  },
  selectionCancel: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    alignSelf: 'flex-start',
  },
  selectionCancelText: {
    fontSize: 14,
    fontWeight: '500',
  },
  selectionCount: {
    fontSize: 15,
    fontWeight: '700',
    textAlign: 'center',
  },
  selectionActions: {
    flexDirection: 'row',
    gap: 8,
  },
  selectionSecondRow: {
    flexDirection: 'row',
    gap: 8,
  },
  selectionButton: {
    flex: 1,
    paddingVertical: 10,
    borderRadius: 12,
    alignItems: 'center',
  },
  selectionButtonText: {
    color: '#FFFFFF',
    fontSize: 14,
    fontWeight: '600',
  },
});
