import type {
  Etape,
  KanbanColumn as KanbanColumnType,
  KanbanTask,
  TaskStatus,
} from "@xtablo/shared-types";
import { useState } from "react";
import { KanbanColumn } from "./KanbanColumn";
import type { TabloMember } from "./types";

interface KanbanBoardProps {
  columns: KanbanColumnType[];
  members: TabloMember[];
  etapes: Etape[];
  etapeTitles: Record<string, string>;
  onTaskClick: (task: KanbanTask) => void;
  onAddTask: (status: TaskStatus) => void;
  onAddTaskInline: (task: {
    title: string;
    description: string;
    assignee_id?: string;
    status: TaskStatus;
    parent_task_id?: string | null;
  }) => void;
  onTaskMove: (taskId: string, newStatus: TaskStatus) => void;
}

export const KanbanBoard = ({
  columns,
  members,
  etapes,
  onTaskClick,
  onAddTask,
  onAddTaskInline,
  onTaskMove,
}: KanbanBoardProps) => {
  const [draggedTask, setDraggedTask] = useState<KanbanTask | null>(null);

  const handleDragStart = (e: React.DragEvent, task: KanbanTask) => {
    setDraggedTask(task);
    e.dataTransfer.effectAllowed = "move";
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
  };

  const handleDrop = (e: React.DragEvent, targetStatus: TaskStatus) => {
    e.preventDefault();
    if (draggedTask && draggedTask.status !== targetStatus) {
      onTaskMove(draggedTask.id, targetStatus);
    }
    setDraggedTask(null);
  };

  return (
    <div className="grid grid-cols-4 gap-4">
      {columns.map((column) => (
        <KanbanColumn
          key={column.id}
          column={column}
          members={members}
          etapes={etapes}
          onTaskClick={onTaskClick}
          onAddTask={onAddTask}
          onAddTaskInline={onAddTaskInline}
          onDragStart={handleDragStart}
          onDragOver={handleDragOver}
          onDrop={handleDrop}
        />
      ))}
    </div>
  );
};
