import React, { useState, useEffect } from 'react';
import { View, StyleSheet } from 'react-native';
import { SubtaskData } from '@/types';
import { TaskItem } from './TaskItem';

interface SubtaskItemProps {
  subtask: SubtaskData;
  onToggle?: (subtask: SubtaskData) => void | Promise<void>;
  onDelete?: (subtask: SubtaskData) => void;
  onPress?: (subtask: SubtaskData) => void;
  onLongPress?: (subtask: SubtaskData) => void;
  onMenuOpen?: (subtask: SubtaskData) => void;
  selected?: boolean;
  selectionMode?: boolean;
  draggable?: boolean;
  onDragStart?: (subtask: SubtaskData) => void;
  onDragUpdate?: (absoluteY: number) => void;
  onDragEnd?: (absoluteY: number) => void;
  depth?: number;
  categoryColor?: string;
  categoryColorResolver?: (categoryId: string | undefined) => string | undefined;
  registerRef?: (subtaskId: string, parentTaskId: string, ref: View | null) => void;
  hoveredId?: string | null;
}

export const SubtaskItem = React.memo(function SubtaskItem({
  subtask,
  onToggle,
  onDelete,
  onPress,
  onLongPress,
  onMenuOpen,
  selected,
  selectionMode,
  draggable,
  onDragStart,
  onDragUpdate,
  onDragEnd,
  depth = 1,
  categoryColor,
  categoryColorResolver,
  registerRef,
  hoveredId,
}: SubtaskItemProps) {
  const [expanded, setExpanded] = useState(false);
  const hasChildren = subtask.subtasks && subtask.subtasks.length > 0;
  const hovered = hoveredId === subtask.id;
  const effectiveColor = subtask.categoryId
    ? categoryColorResolver?.(subtask.categoryId) ?? categoryColor
    : categoryColor;

  const handleExpand = () => setExpanded(!expanded);

  useEffect(() => {
    if (hovered && hasChildren && !expanded) {
      setExpanded(true);
    }
  }, [hovered, hasChildren, expanded]);

  return (
    <View>
      <View ref={(ref) => registerRef?.(subtask.id, subtask.taskId, ref)}>
        <TaskItem
          task={subtask}
          indented
          depth={depth}
          expanded={hasChildren && expanded}
          onToggle={() => onToggle?.(subtask)}
          onDelete={() => onDelete?.(subtask)}
          onPress={onPress ? () => onPress(subtask) : handleExpand}
          onLongPress={() => onLongPress?.(subtask)}
          onMenuOpen={() => onMenuOpen?.(subtask)}
          selected={selected}
          selectionMode={selectionMode}
          completedSection={subtask.completed}
          draggable={draggable}
          hovered={hovered}
          onDragStart={() => onDragStart?.(subtask)}
          onDragUpdate={onDragUpdate}
          onDragEnd={onDragEnd}
          categoryColor={effectiveColor}
        />
      </View>
      {hasChildren && expanded && (
        <View style={[styles.nestedSubtasks, { marginLeft: depth * 12 }]}>
          {subtask.subtasks
            .slice()
            .sort((a, b) => a.order - b.order)
            .map((child) => (
              <SubtaskItem
                key={child.id}
                subtask={child}
                onToggle={onToggle}
                onDelete={onDelete}
                onPress={onPress}
                onLongPress={onLongPress}
                onMenuOpen={onMenuOpen}
                selected={selected}
                selectionMode={selectionMode}
                draggable={draggable}
                onDragStart={onDragStart}
                onDragUpdate={onDragUpdate}
                onDragEnd={onDragEnd}
                depth={depth + 1}
                categoryColor={effectiveColor}
                categoryColorResolver={categoryColorResolver}
                registerRef={registerRef}
                hoveredId={hoveredId}
              />
            ))}
        </View>
      )}
    </View>
  );
});

const styles = StyleSheet.create({
  nestedSubtasks: {
    marginTop: 4,
  },
});