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

interface SubtaskItemProps {
  subtask: SubtaskData;
  onToggle: () => void | Promise<void>;
  onDelete?: () => void;
  onPress?: () => void;
  onLongPress?: () => void;
  onMenuOpen?: () => void;
  selected?: boolean;
  selectionMode?: boolean;
  draggable?: boolean;
  onDragStart?: () => void;
  onDragUpdate?: (absoluteY: number) => void;
  onDragEnd?: (absoluteY: number) => void;
  depth?: number;
}

export const SubtaskItem = React.memo(function SubtaskItem({ 
  subtask, 
  onToggle, 
  onDelete, 
  onPress, 
  onLongPress, 
  onMenuOpen, 
  selected,
  selectionMode,
  draggable, 
  onDragStart, 
  onDragUpdate, 
  onDragEnd, 
  depth = 1 
}: SubtaskItemProps) {
  const { theme } = useSettings();
  const [expanded, setExpanded] = useState(true);
  const hasChildren = subtask.subtasks && subtask.subtasks.length > 0;

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

  return (
    <View>
      <TaskItem
        task={subtask}
        indented
        depth={depth}
        onToggle={onToggle}
        onDelete={onDelete}
        onPress={onPress ?? (() => {})}
        onLongPress={onLongPress}
        onMenuOpen={onMenuOpen}
        selected={selected}
        selectionMode={selectionMode}
        completedSection={subtask.completed}
        draggable={draggable}
        onDragStart={onDragStart}
        onDragUpdate={onDragUpdate}
        onDragEnd={onDragEnd}
      />
      {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={() => {}}
                onDelete={onDelete}
                onPress={onPress}
                onLongPress={onLongPress}
                onMenuOpen={onMenuOpen}
                selected={selected}
                selectionMode={selectionMode}
                draggable={draggable}
                onDragStart={onDragStart}
                onDragUpdate={onDragUpdate}
                onDragEnd={onDragEnd}
                depth={depth + 1}
              />
            ))}
        </View>
      )}
    </View>
  );
});

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