/* eslint-disable @typescript-eslint/no-unnecessary-condition */
"use client";

import React, { useState, useMemo, useEffect, useCallback } from "react";
import type { Task } from "@mosaic/shared";
import { TaskStatus } from "@mosaic/shared";
import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core";
import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { KanbanColumn } from "./KanbanColumn";
import { TaskCard } from "./TaskCard";
import { apiPatch } from "@/lib/api/client";
import { useToast } from "@mosaic/ui";

interface KanbanBoardProps {
  tasks: Task[];
  onStatusChange?: (taskId: string, newStatus: TaskStatus) => void;
}

/**
 * Map TaskStatus enum to Kanban column configuration
 * Spec requires: todo, in_progress, review, done
 */
const columns = [
  { status: TaskStatus.NOT_STARTED, title: "To Do" },
  { status: TaskStatus.IN_PROGRESS, title: "In Progress" },
  { status: TaskStatus.PAUSED, title: "Review" },
  { status: TaskStatus.COMPLETED, title: "Done" },
] as const;

/**
 * Kanban Board component with drag-and-drop functionality
 *
 * Features:
 * - 4 status columns: To Do, In Progress, Review, Done
 * - Drag-and-drop using @dnd-kit/core
 * - Task cards with title, priority badge, assignee avatar
 * - PATCH /api/tasks/:id on status change
 * - Optimistic updates with rollback on error
 */
export function KanbanBoard({ tasks, onStatusChange }: KanbanBoardProps): React.ReactElement {
  const [activeTaskId, setActiveTaskId] = useState<string | null>(null);
  // Local task state for optimistic updates
  const [localTasks, setLocalTasks] = useState<Task[]>(tasks || []);
  const { showToast } = useToast();

  // Sync local state with props when tasks prop changes
  useEffect(() => {
    setLocalTasks(tasks || []);
  }, [tasks]);

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8, // 8px movement required before drag starts
      },
    })
  );

  // Group tasks by status (using local state for optimistic updates)
  const tasksByStatus = useMemo(() => {
    const grouped: Record<TaskStatus, Task[]> = {
      [TaskStatus.NOT_STARTED]: [],
      [TaskStatus.IN_PROGRESS]: [],
      [TaskStatus.PAUSED]: [],
      [TaskStatus.COMPLETED]: [],
      [TaskStatus.ARCHIVED]: [],
    };

    localTasks.forEach((task) => {
      if (grouped[task.status]) {
        grouped[task.status].push(task);
      }
    });

    // Sort tasks by sortOrder within each column
    Object.keys(grouped).forEach((status) => {
      grouped[status as TaskStatus].sort((a, b) => a.sortOrder - b.sortOrder);
    });

    return grouped;
  }, [localTasks]);

  const activeTask = useMemo(
    () => localTasks.find((task) => task.id === activeTaskId),
    [localTasks, activeTaskId]
  );

  function handleDragStart(event: DragStartEvent): void {
    setActiveTaskId(event.active.id as string);
  }

  // Apply optimistic update to local state
  const applyOptimisticUpdate = useCallback((taskId: string, newStatus: TaskStatus): void => {
    setLocalTasks((prevTasks) =>
      prevTasks.map((task) => (task.id === taskId ? { ...task, status: newStatus } : task))
    );
  }, []);

  // Rollback to previous state
  const rollbackUpdate = useCallback((previousTasks: Task[]): void => {
    setLocalTasks(previousTasks);
  }, []);

  async function handleDragEnd(event: DragEndEvent): Promise<void> {
    const { active, over } = event;

    if (!over) {
      setActiveTaskId(null);
      return;
    }

    const taskId = active.id as string;
    const newStatus = over.id as TaskStatus;

    // Find the task and check if status actually changed
    const task = localTasks.find((t) => t.id === taskId);

    if (task && task.status !== newStatus) {
      // Store previous state for potential rollback
      const previousTasks = [...localTasks];

      // Apply optimistic update immediately
      applyOptimisticUpdate(taskId, newStatus);

      // Call PATCH /api/tasks/:id to update status (using API client for CSRF protection)
      try {
        await apiPatch(`/api/tasks/${taskId}`, { status: newStatus });

        // Optionally call the callback for parent component to refresh
        if (onStatusChange) {
          onStatusChange(taskId, newStatus);
        }
      } catch (error) {
        // Rollback to previous state on error
        rollbackUpdate(previousTasks);

        // Show error notification
        showToast("Unable to update task status. Please try again.", "error");
        console.error("Error updating task status:", error);
      }
    }

    setActiveTaskId(null);
  }

  return (
    <DndContext sensors={sensors} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
      <div
        data-testid="kanban-grid"
        className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"
      >
        {columns.map(({ status, title }) => (
          <KanbanColumn key={status} status={status} title={title} tasks={tasksByStatus[status]} />
        ))}
      </div>

      {/* Drag Overlay - shows a copy of the dragged task */}
      <DragOverlay>
        {activeTask ? (
          <div className="rotate-3 scale-105">
            <TaskCard task={activeTask} />
          </div>
        ) : null}
      </DragOverlay>
    </DndContext>
  );
}
