'use client';

import { useParams } from 'next/navigation';
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  DragStartEvent,
  closestCorners,
} from '@dnd-kit/core';
import { useState } from 'react';
import { useIssues, useChangeIssueStatus } from '@/lib/hooks/use-issues';
import { Button } from '@/components/ui/button';
import { Plus, Loader2 } from 'lucide-react';
import { Issue } from '@/lib/api/issues';
import { KanbanColumn } from '@/components/features/kanban/KanbanColumn';
import { IssueCard } from '@/components/features/kanban/IssueCard';
import { CreateIssueDialog } from '@/components/features/issues/CreateIssueDialog';

const COLUMNS = [
  { id: 'Backlog', title: 'Backlog', color: 'bg-gray-100' },
  { id: 'Todo', title: 'To Do', color: 'bg-blue-100' },
  { id: 'InProgress', title: 'In Progress', color: 'bg-yellow-100' },
  { id: 'Done', title: 'Done', color: 'bg-green-100' },
];

export default function KanbanPage() {
  const params = useParams();
  const projectId = params.id as string;
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [activeIssue, setActiveIssue] = useState<Issue | null>(null);

  const { data: issues, isLoading } = useIssues(projectId);
  const changeStatusMutation = useChangeIssueStatus(projectId);

  // Group issues by status
  const issuesByStatus = {
    Backlog: issues?.filter((i) => i.status === 'Backlog') || [],
    Todo: issues?.filter((i) => i.status === 'Todo') || [],
    InProgress: issues?.filter((i) => i.status === 'InProgress') || [],
    Done: issues?.filter((i) => i.status === 'Done') || [],
  };

  const handleDragStart = (event: DragStartEvent) => {
    const issue = issues?.find((i) => i.id === event.active.id);
    setActiveIssue(issue || null);
  };

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    setActiveIssue(null);

    if (!over || active.id === over.id) return;

    const newStatus = over.id as string;
    const issue = issues?.find((i) => i.id === active.id);

    if (issue && issue.status !== newStatus) {
      changeStatusMutation.mutate({ issueId: issue.id, status: newStatus });
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Kanban Board</h1>
          <p className="text-muted-foreground">
            Drag and drop to update issue status
          </p>
        </div>
        <Button onClick={() => setIsCreateDialogOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          New Issue
        </Button>
      </div>

      <DndContext
        collisionDetection={closestCorners}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
      >
        <div className="grid grid-cols-4 gap-4">
          {COLUMNS.map((column) => (
            <KanbanColumn
              key={column.id}
              id={column.id}
              title={column.title}
              issues={issuesByStatus[column.id as keyof typeof issuesByStatus]}
            />
          ))}
        </div>

        <DragOverlay>
          {activeIssue && <IssueCard issue={activeIssue} />}
        </DragOverlay>
      </DndContext>

      <CreateIssueDialog
        projectId={projectId}
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
      />
    </div>
  );
}
