import { Head, router, useForm } from '@inertiajs/react';
import {
    Plus,
    Search,
    Trash2,
    ChevronUp,
    ChevronDown,
    ChevronsUp,
    ChevronsDown,
    BookOpen,
    CheckSquare,
    Bug,
    Activity,
    Calendar,
    User as UserIcon,
    Layers,
    Settings,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

import ProjectController from '@/actions/App/Http/Controllers/ProjectController';
import TaskController from '@/actions/App/Http/Controllers/TaskController';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogFooter,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Sheet,
    SheetContent,
    SheetHeader,
    SheetTitle,
    SheetDescription,
} from '@/components/ui/sheet';
import { usePermissions } from '@/hooks/use-permissions';
import { kanban } from '@/routes';
import { update as updateProject } from '@/routes/projects';

interface Project {
    id: number;
    name: string;
    key: string;
    description: string | null;
    status: 'planning' | 'active' | 'on_hold' | 'completed';
}

interface User {
    id: number;
    name: string;
    email: string;
}

interface Task {
    id: number;
    key: string;
    project_id: number;
    parent_id?: number | null;
    title: string;
    description: string | null;
    status: 'todo' | 'in_progress' | 'in_review' | 'done';
    priority: 'lowest' | 'low' | 'medium' | 'high' | 'highest';
    type: 'story' | 'task' | 'bug' | 'epic' | 'subtask';
    story_points: number | null;
    due_date: string | null;
    assignee_id: number | null;
    reporter_id: number | null;
    assignee?: User | null;
    reporter?: User | null;
    created_at: string;
}

interface KanbanProps {
    projects: Project[];
    activeProjectId: number | null;
    tasks: Task[];
    users: User[];
}

const COLUMNS = [
    { id: 'todo', title: 'To Do', color: 'border-t-slate-400 bg-slate-500/5' },
    {
        id: 'in_progress',
        title: 'In Progress',
        color: 'border-t-blue-500 bg-blue-500/5',
    },
    {
        id: 'in_review',
        title: 'In Review',
        color: 'border-t-amber-500 bg-amber-500/5',
    },
    { id: 'done', title: 'Done', color: 'border-t-green-500 bg-green-500/5' },
] as const;

export default function Kanban({
    projects,
    activeProjectId,
    tasks,
    users,
}: KanbanProps) {
    const { hasPermission } = usePermissions();

    const activeProject =
        projects.find((p) => p.id === activeProjectId) || null;

    // Filter states
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedAssignee, setSelectedAssignee] = useState<string>('all');
    const [selectedPriority, setSelectedPriority] = useState<string>('all');
    const [selectedType, setSelectedType] = useState<string>('all');
    const [dragOverColumn, setDragOverColumn] = useState<string | null>(null);

    // Dialog & Sheet states
    const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false);
    const [isTaskDialogOpen, setIsTaskDialogOpen] = useState(false);
    const [selectedTask, setSelectedTask] = useState<Task | null>(null);

    // Form Hooks
    const projectForm = useForm({
        name: '',
        key: '',
        description: '',
    });

    const [isEditProjectOpen, setIsEditProjectOpen] = useState(false);
    const editProjectForm = useForm({
        name: '',
        description: '',
        status: 'active' as Project['status'],
    });

    const taskForm = useForm({
        project_id: activeProjectId || '',
        parent_id: '' as number | string,
        title: '',
        description: '',
        status: 'todo' as Task['status'],
        priority: 'medium' as Task['priority'],
        type: 'task' as Task['type'],
        story_points: '' as number | string,
        due_date: '',
        assignee_id: '' as number | string,
    });

    const editTaskForm = useForm({
        parent_id: '' as number | string,
        title: '',
        description: '',
        status: 'todo' as Task['status'],
        priority: 'medium' as Task['priority'],
        type: 'task' as Task['type'],
        story_points: '' as number | string,
        due_date: '',
        assignee_id: '' as number | string,
    });

    // Helper: get Initials
    const getInitials = (name: string) => {
        return name
            .split(' ')
            .map((n) => n[0])
            .join('')
            .toUpperCase()
            .substring(0, 2);
    };

    // Filter Tasks
    const filteredTasks = tasks.filter((task) => {
        const matchesSearch =
            task.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
            task.key.toLowerCase().includes(searchQuery.toLowerCase());
        const matchesAssignee =
            selectedAssignee === 'all' ||
            (selectedAssignee === 'unassigned' && !task.assignee_id) ||
            task.assignee_id?.toString() === selectedAssignee;
        const matchesPriority =
            selectedPriority === 'all' || task.priority === selectedPriority;
        const matchesType =
            selectedType === 'all' || task.type === selectedType;

        return (
            matchesSearch && matchesAssignee && matchesPriority && matchesType
        );
    });

    // Handlers
    const handleProjectChange = (projectId: string) => {
        router.get(
            kanban.url(),
            { project_id: projectId },
            { preserveState: true },
        );
    };

    const handleCreateProject = (e: React.FormEvent) => {
        e.preventDefault();
        projectForm.post(ProjectController.store.url(), {
            onSuccess: () => {
                setIsProjectDialogOpen(false);
                projectForm.reset();
                toast.success('Project created successfully!');
            },
            onError: (errors) => {
                toast.error(
                    errors.key || errors.name || 'Failed to create project.',
                );
            },
        });
    };

    const handleDeleteProject = (projectId: number) => {
        if (
            confirm(
                'Are you sure you want to delete this project and all its tasks?',
            )
        ) {
            router.delete(ProjectController.destroy.url(projectId), {
                onSuccess: () => {
                    toast.success('Project deleted successfully.');
                },
            });
        }
    };

    const handleEditProjectClick = () => {
        if (!activeProject) {
            return;
        }

        editProjectForm.setData({
            name: activeProject.name,
            description: activeProject.description || '',
            status: activeProject.status || 'active',
        });
        setIsEditProjectOpen(true);
    };

    const handleUpdateProject = (e: React.FormEvent) => {
        e.preventDefault();

        if (!activeProject) {
            return;
        }

        editProjectForm.put(updateProject.url(activeProject.id), {
            onSuccess: () => {
                setIsEditProjectOpen(false);
                toast.success('Project updated successfully.');
            },
            onError: (errors) => {
                toast.error(errors.name || 'Failed to update project.');
            },
        });
    };

    const handleCreateTask = (e: React.FormEvent) => {
        e.preventDefault();

        if (!activeProjectId) {
            return;
        }

        taskForm.post(TaskController.store.url(), {
            onSuccess: () => {
                setIsTaskDialogOpen(false);
                taskForm.reset();
                toast.success('Task created successfully!');
            },
            onError: (errors) => {
                toast.error(errors.title || 'Failed to create task.');
            },
        });
    };

    const handleEditTaskClick = (task: Task) => {
        setSelectedTask(task);
        editTaskForm.setData({
            parent_id: task.parent_id || '',
            title: task.title,
            description: task.description || '',
            status: task.status,
            priority: task.priority,
            type: task.type,
            story_points: task.story_points || '',
            due_date: task.due_date || '',
            assignee_id: task.assignee_id || '',
        });
    };

    const handleUpdateTask = (e: React.FormEvent) => {
        e.preventDefault();

        if (!selectedTask) {
            return;
        }

        editTaskForm.put(TaskController.update.url(selectedTask.id), {
            onSuccess: () => {
                setSelectedTask(null);
                toast.success('Task updated successfully.');
            },
            onError: (errors) => {
                toast.error(errors.title || 'Failed to update task.');
            },
        });
    };

    const handleDeleteTask = (taskId: number) => {
        if (confirm('Are you sure you want to delete this task?')) {
            router.delete(TaskController.destroy.url(taskId), {
                onSuccess: () => {
                    setSelectedTask(null);
                    toast.success('Task deleted successfully.');
                },
            });
        }
    };

    // HTML5 Drag and Drop handlers
    const handleDragStart = (e: React.DragEvent, task: Task) => {
        if (!hasPermission('projects.edit')) {
            e.preventDefault();

            return;
        }

        e.dataTransfer.setData('text/plain', task.id.toString());
    };

    const handleDragOver = (e: React.DragEvent, columnId: string) => {
        e.preventDefault();
        setDragOverColumn(columnId);
    };

    const handleDrop = (e: React.DragEvent, targetColumn: Task['status']) => {
        e.preventDefault();
        setDragOverColumn(null);
        const taskIdStr = e.dataTransfer.getData('text/plain');

        if (!taskIdStr) {
            return;
        }

        const taskId = parseInt(taskIdStr);
        const task = tasks.find((t) => t.id === taskId);

        if (!task || task.status === targetColumn) {
            return;
        }

        // Perform status update
        router.patch(
            TaskController.updateStatus.url(task.id),
            { status: targetColumn },
            {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success(
                        `Task transitioned to ${targetColumn.replace('_', ' ')}`,
                    );
                },
                onError: () => {
                    toast.error('Failed to update task status.');
                },
            },
        );
    };

    // Priority Icon helper
    const getPriorityIcon = (priority: Task['priority']) => {
        switch (priority) {
            case 'highest':
                return <ChevronsUp className="h-4 w-4 text-red-600" />;
            case 'high':
                return <ChevronUp className="h-4 w-4 text-orange-500" />;
            case 'medium':
                return <Activity className="h-4 w-4 text-amber-500" />;
            case 'low':
                return <ChevronDown className="h-4 w-4 text-blue-500" />;
            case 'lowest':
                return <ChevronsDown className="h-4 w-4 text-slate-400" />;
        }
    };

    // Type Icon helper
    const getTypeIcon = (type: Task['type']) => {
        switch (type) {
            case 'story':
                return <BookOpen className="h-4 w-4 text-green-500" />;
            case 'subtask':
                return <CheckSquare className="h-4 w-4 text-sky-400 stroke-[3px]" />;
            case 'task':
                return <CheckSquare className="h-4 w-4 text-blue-500" />;
            case 'bug':
                return <Bug className="h-4 w-4 text-red-500" />;
            case 'epic':
                return <Layers className="h-4 w-4 text-purple-500" />;
        }
    };

    return (
        <>
            <Head title="Kanban Board" />
            <div className="space-y-6 p-6">
                {/* Board Actions & Filters Toolbar */}
                <div className="flex flex-col gap-4 border-b pb-6 md:flex-row md:items-center md:justify-between">
                    <div className="flex items-center space-x-3">
                        <div>
                            <Label className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground">
                                Active Project
                                {activeProject && (
                                    <span
                                        className={`rounded-full border px-2 py-0.5 text-[9px] leading-none font-extrabold tracking-wider uppercase ${
                                            activeProject.status === 'completed'
                                                ? 'border-emerald-200 bg-emerald-50 text-emerald-600 dark:bg-emerald-950/50 dark:text-emerald-400'
                                                : activeProject.status ===
                                                    'on_hold'
                                                  ? 'border-red-200 bg-red-50 text-red-600 dark:bg-red-950/50 dark:text-red-400'
                                                  : activeProject.status ===
                                                      'planning'
                                                    ? 'border-blue-200 bg-blue-50 text-blue-600 dark:bg-blue-950/50 dark:text-blue-400'
                                                    : 'border-indigo-200 bg-indigo-50 text-indigo-600 dark:bg-indigo-950/50 dark:text-indigo-400'
                                        }`}
                                    >
                                        {activeProject.status || 'active'}
                                    </span>
                                )}
                            </Label>
                            {projects.length > 0 ? (
                                <div className="mt-1 flex items-center space-x-2">
                                    <select
                                        className="h-10 rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus:ring-1 focus:ring-ring focus:outline-none"
                                        value={activeProjectId || ''}
                                        onChange={(e) =>
                                            handleProjectChange(e.target.value)
                                        }
                                    >
                                        {projects.map((proj) => (
                                            <option
                                                key={proj.id}
                                                value={proj.id}
                                            >
                                                {proj.name} ({proj.key})
                                            </option>
                                        ))}
                                    </select>
                                    {hasPermission('projects.edit') &&
                                        activeProject && (
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                className="text-zinc-500 hover:bg-zinc-100 hover:text-zinc-950"
                                                onClick={handleEditProjectClick}
                                                title="Project Settings"
                                            >
                                                <Settings className="h-4 w-4" />
                                            </Button>
                                        )}
                                    {hasPermission('projects.delete') &&
                                        activeProject && (
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                className="text-red-500 hover:bg-red-50"
                                                onClick={() =>
                                                    handleDeleteProject(
                                                        activeProject.id,
                                                    )
                                                }
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        )}
                                </div>
                            ) : (
                                <p className="text-sm font-semibold text-muted-foreground">
                                    No projects created yet.
                                </p>
                            )}
                        </div>
                    </div>

                    <div className="flex flex-wrap items-center gap-3">
                        {hasPermission('projects.create') && (
                            <Button
                                variant="outline"
                                className="flex items-center gap-1.5"
                                onClick={() => setIsProjectDialogOpen(true)}
                            >
                                <Plus className="h-4 w-4" /> New Project
                            </Button>
                        )}
                        {hasPermission('projects.edit') && activeProjectId && (
                            <Button
                                className="flex items-center gap-1.5"
                                onClick={() => {
                                    taskForm.setData(
                                        'project_id',
                                        activeProjectId,
                                    );
                                    setIsTaskDialogOpen(true);
                                }}
                            >
                                <Plus className="h-4 w-4" /> Create Issue
                            </Button>
                        )}
                    </div>
                </div>

                {/* Filters Row */}
                {activeProjectId && (
                    <div className="flex flex-wrap items-center gap-3 rounded-lg border bg-muted/20 p-3">
                        <div className="relative min-w-[200px] flex-1">
                            <Search className="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
                            <Input
                                type="text"
                                placeholder="Search tasks..."
                                className="pl-9"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                            />
                        </div>

                        <div>
                            <select
                                className="h-9 rounded-md border bg-card px-2 py-1 text-xs"
                                value={selectedAssignee}
                                onChange={(e) =>
                                    setSelectedAssignee(e.target.value)
                                }
                            >
                                <option value="all">Assignee: All</option>
                                <option value="unassigned">Unassigned</option>
                                {users.map((u) => (
                                    <option key={u.id} value={u.id}>
                                        {u.name}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div>
                            <select
                                className="h-9 rounded-md border bg-card px-2 py-1 text-xs"
                                value={selectedPriority}
                                onChange={(e) =>
                                    setSelectedPriority(e.target.value)
                                }
                            >
                                <option value="all">Priority: All</option>
                                <option value="lowest">Lowest</option>
                                <option value="low">Low</option>
                                <option value="medium">Medium</option>
                                <option value="high">High</option>
                                <option value="highest">Highest</option>
                            </select>
                        </div>

                        <div>
                            <select
                                className="h-9 rounded-md border bg-card px-2 py-1 text-xs"
                                value={selectedType}
                                onChange={(e) =>
                                    setSelectedType(e.target.value)
                                }
                            >
                                <option value="all">Type: All</option>
                                <option value="story">Story</option>
                                <option value="task">Task</option>
                                <option value="bug">Bug</option>
                                <option value="epic">Epic</option>
                            </select>
                        </div>

                        {(searchQuery ||
                            selectedAssignee !== 'all' ||
                            selectedPriority !== 'all' ||
                            selectedType !== 'all') && (
                            <Button
                                variant="ghost"
                                size="sm"
                                className="h-8 text-xs text-muted-foreground"
                                onClick={() => {
                                    setSearchQuery('');
                                    setSelectedAssignee('all');
                                    setSelectedPriority('all');
                                    setSelectedType('all');
                                }}
                            >
                                Clear Filters
                            </Button>
                        )}
                    </div>
                )}

                {/* Kanban Columns Grid */}
                {activeProjectId ? (
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                        {COLUMNS.map((column) => {
                            const columnTasks = filteredTasks.filter(
                                (t) => t.status === column.id,
                            );
                            const totalPoints = columnTasks.reduce(
                                (acc, t) => acc + (t.story_points || 0),
                                0,
                            );
                            const isOver = dragOverColumn === column.id;

                            return (
                                <div
                                    key={column.id}
                                    className={`flex min-h-[600px] flex-col rounded-xl border p-3 transition-all duration-200 ${column.color} ${
                                        isOver
                                            ? 'ring-2 ring-primary ring-offset-2'
                                            : ''
                                    }`}
                                    onDragOver={(e) =>
                                        handleDragOver(e, column.id)
                                    }
                                    onDragLeave={() => setDragOverColumn(null)}
                                    onDrop={(e) => handleDrop(e, column.id)}
                                >
                                    <div className="mb-3 flex items-center justify-between border-b pb-2">
                                        <div className="flex items-center space-x-2">
                                            <span className="text-sm font-semibold">
                                                {column.title}
                                            </span>
                                            <Badge
                                                variant="secondary"
                                                className="text-xs"
                                            >
                                                {columnTasks.length}
                                            </Badge>
                                        </div>
                                        {totalPoints > 0 && (
                                            <Badge
                                                variant="outline"
                                                className="text-[10px] text-muted-foreground"
                                            >
                                                {totalPoints} SP
                                            </Badge>
                                        )}
                                    </div>

                                    <div className="max-h-[700px] flex-1 space-y-3 overflow-y-auto pr-1">
                                        {columnTasks.map((task) => (
                                            <div
                                                key={task.id}
                                                draggable={hasPermission(
                                                    'projects.edit',
                                                )}
                                                onDragStart={(e) =>
                                                    handleDragStart(e, task)
                                                }
                                                onClick={() =>
                                                    handleEditTaskClick(task)
                                                }
                                                className={`group relative flex cursor-pointer flex-col justify-between rounded-xl border bg-card p-4 shadow-sm transition-all hover:shadow-md ${
                                                    hasPermission(
                                                        'projects.edit',
                                                    )
                                                        ? 'hover:border-primary/50'
                                                        : ''
                                                }`}
                                            >
                                                <div className="space-y-1.5">
                                                    <div className="flex items-center justify-between">
                                                        <span className="text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                                            {task.key}
                                                        </span>
                                                        <div className="flex items-center space-x-1">
                                                            {getTypeIcon(
                                                                task.type,
                                                            )}
                                                            {getPriorityIcon(
                                                                task.priority,
                                                            )}
                                                        </div>
                                                    </div>
                                                    <p className="text-sm leading-tight font-semibold text-card-foreground transition-colors group-hover:text-primary">
                                                        {task.title}
                                                    </p>
                                                </div>

                                                <div className="mt-4 flex items-center justify-between">
                                                    <div className="flex items-center space-x-1.5">
                                                        {task.story_points !==
                                                            null && (
                                                            <Badge
                                                                variant="secondary"
                                                                className="h-5 px-1.5 text-[10px]"
                                                            >
                                                                {
                                                                    task.story_points
                                                                }
                                                            </Badge>
                                                        )}
                                                        {task.due_date && (
                                                            <span className="flex items-center gap-1 text-[10px] text-muted-foreground">
                                                                <Calendar className="h-3 w-3" />
                                                                {new Date(
                                                                    task.due_date,
                                                                ).toLocaleDateString(
                                                                    undefined,
                                                                    {
                                                                        month: 'short',
                                                                        day: 'numeric',
                                                                    },
                                                                )}
                                                            </span>
                                                        )}
                                                    </div>
                                                    {task.assignee ? (
                                                        <Avatar className="h-6 w-6">
                                                            <AvatarFallback className="bg-primary/10 text-[10px] font-bold text-primary">
                                                                {getInitials(
                                                                    task
                                                                        .assignee
                                                                        .name,
                                                                )}
                                                            </AvatarFallback>
                                                        </Avatar>
                                                    ) : (
                                                        <div className="rounded-full border border-dashed p-0.5 text-muted-foreground hover:bg-muted">
                                                            <UserIcon className="h-4 w-4" />
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        ))}

                                        {columnTasks.length === 0 && (
                                            <div className="flex h-32 items-center justify-center rounded-xl border border-dashed text-xs text-muted-foreground">
                                                No tasks here
                                            </div>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    <div className="flex flex-col items-center justify-center rounded-xl border border-dashed p-12 text-center">
                        <Layers className="mb-4 h-12 w-12 text-muted-foreground" />
                        <h3 className="text-lg font-bold">No active project</h3>
                        <p className="mb-4 max-w-sm text-sm text-muted-foreground">
                            You need a project to start organizing tasks. Create
                            a new project to get started.
                        </p>
                        {hasPermission('projects.create') && (
                            <Button
                                onClick={() => setIsProjectDialogOpen(true)}
                            >
                                Create Project
                            </Button>
                        )}
                    </div>
                )}

                {/* Create Project Dialog */}
                <Dialog
                    open={isProjectDialogOpen}
                    onOpenChange={setIsProjectDialogOpen}
                >
                    <DialogContent className="max-w-md">
                        <form
                            onSubmit={handleCreateProject}
                            className="space-y-4"
                        >
                            <DialogHeader>
                                <DialogTitle>Create Project</DialogTitle>
                                <DialogDescription>
                                    Create a new project workspace. Use a clean,
                                    capital letters project key prefix (e.g.
                                    ACME, MOB).
                                </DialogDescription>
                            </DialogHeader>

                            <div className="space-y-3">
                                <div className="space-y-1">
                                    <Label htmlFor="project-name">
                                        Project Name
                                    </Label>
                                    <Input
                                        id="project-name"
                                        placeholder="e.g. Acme Web Application"
                                        value={projectForm.data.name}
                                        onChange={(e) =>
                                            projectForm.setData(
                                                'name',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="project-key">
                                        Project Key Prefix
                                    </Label>
                                    <Input
                                        id="project-key"
                                        placeholder="e.g. ACME (Alphabetic only)"
                                        maxLength={10}
                                        value={projectForm.data.key}
                                        onChange={(e) =>
                                            projectForm.setData(
                                                'key',
                                                e.target.value
                                                    .replace(/[^a-zA-Z]/g, '')
                                                    .toUpperCase(),
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="project-description">
                                        Description
                                    </Label>
                                    <Input
                                        id="project-description"
                                        placeholder="Summary description of the project..."
                                        value={projectForm.data.description}
                                        onChange={(e) =>
                                            projectForm.setData(
                                                'description',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>
                            </div>

                            <DialogFooter>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() =>
                                        setIsProjectDialogOpen(false)
                                    }
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={projectForm.processing}
                                >
                                    Create Project
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Project Dialog */}
                <Dialog
                    open={isEditProjectOpen}
                    onOpenChange={setIsEditProjectOpen}
                >
                    <DialogContent className="max-w-md">
                        <form
                            onSubmit={handleUpdateProject}
                            className="space-y-4"
                        >
                            <DialogHeader>
                                <DialogTitle>Project Settings</DialogTitle>
                                <DialogDescription>
                                    Update name, description, and status for the
                                    active project.
                                </DialogDescription>
                            </DialogHeader>

                            <div className="space-y-3">
                                <div className="space-y-1">
                                    <Label htmlFor="edit-project-name">
                                        Project Name
                                    </Label>
                                    <Input
                                        id="edit-project-name"
                                        value={editProjectForm.data.name}
                                        onChange={(e) =>
                                            editProjectForm.setData(
                                                'name',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="edit-project-description">
                                        Description
                                    </Label>
                                    <Input
                                        id="edit-project-description"
                                        value={editProjectForm.data.description}
                                        onChange={(e) =>
                                            editProjectForm.setData(
                                                'description',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="edit-project-status">
                                        Project Status
                                    </Label>
                                    <select
                                        id="edit-project-status"
                                        className="h-10 w-full rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus:ring-1 focus:ring-ring focus:outline-none"
                                        value={editProjectForm.data.status}
                                        onChange={(e) =>
                                            editProjectForm.setData(
                                                'status',
                                                e.target
                                                    .value as Project['status'],
                                            )
                                        }
                                    >
                                        <option value="planning">
                                            Planning
                                        </option>
                                        <option value="active">Active</option>
                                        <option value="on_hold">On Hold</option>
                                        <option value="completed">
                                            Completed
                                        </option>
                                    </select>
                                </div>
                            </div>

                            <DialogFooter>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsEditProjectOpen(false)}
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={editProjectForm.processing}
                                >
                                    Save Changes
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Create Task/Issue Dialog */}
                <Dialog
                    open={isTaskDialogOpen}
                    onOpenChange={setIsTaskDialogOpen}
                >
                    <DialogContent className="max-w-lg">
                        <form onSubmit={handleCreateTask} className="space-y-4">
                            <DialogHeader>
                                <DialogTitle>Create Issue</DialogTitle>
                                <DialogDescription>
                                    Add a new issue to the active project
                                    workspace.
                                </DialogDescription>
                            </DialogHeader>

                            <div className="grid grid-cols-1 gap-3 space-y-3 md:grid-cols-2">
                                <div className="col-span-2 space-y-1">
                                    <Label htmlFor="task-title">
                                        Title / Summary
                                    </Label>
                                    <Input
                                        id="task-title"
                                        placeholder="What needs to be done?"
                                        value={taskForm.data.title}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'title',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="col-span-2 space-y-1">
                                    <Label htmlFor="task-description">
                                        Description
                                    </Label>
                                    <textarea
                                        id="task-description"
                                        rows={4}
                                        className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
                                        placeholder="Describe the issue in detail..."
                                        value={taskForm.data.description}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'description',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="task-type">
                                        Issue Type
                                    </Label>
                                    <select
                                        id="task-type"
                                        className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                        value={taskForm.data.type}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'type',
                                                e.target.value as Task['type'],
                                            )
                                        }
                                    >
                                        <option value="task">Task</option>
                                        <option value="subtask">Subtask</option>
                                        <option value="story">Story</option>
                                        <option value="bug">Bug</option>
                                        <option value="epic">Epic</option>
                                    </select>
                                </div>

                                {(taskForm.data.type === 'task' || taskForm.data.type === 'subtask') && (
                                    <div className="space-y-1">
                                        <Label htmlFor="task-parent">
                                            Parent Task
                                        </Label>
                                        <select
                                            id="task-parent"
                                            className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                            value={taskForm.data.parent_id}
                                            onChange={(e) =>
                                                taskForm.setData(
                                                    'parent_id',
                                                    e.target.value,
                                                )
                                            }
                                        >
                                            <option value="">None (Independent)</option>
                                            {tasks
                                                .filter((t) => t.type !== 'subtask')
                                                .map((t) => (
                                                    <option key={t.id} value={t.id}>
                                                        [{t.key}] {t.title}
                                                    </option>
                                                ))}
                                        </select>
                                    </div>
                                )}

                                <div className="space-y-1">
                                    <Label htmlFor="task-priority">
                                        Priority
                                    </Label>
                                    <select
                                        id="task-priority"
                                        className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                        value={taskForm.data.priority}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'priority',
                                                e.target
                                                    .value as Task['priority'],
                                            )
                                        }
                                    >
                                        <option value="lowest">Lowest</option>
                                        <option value="low">Low</option>
                                        <option value="medium">Medium</option>
                                        <option value="high">High</option>
                                        <option value="highest">Highest</option>
                                    </select>
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="task-status">
                                        Status Column
                                    </Label>
                                    <select
                                        id="task-status"
                                        className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                        value={taskForm.data.status}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'status',
                                                e.target
                                                    .value as Task['status'],
                                            )
                                        }
                                    >
                                        <option value="todo">To Do</option>
                                        <option value="in_progress">
                                            In Progress
                                        </option>
                                        <option value="in_review">
                                            In Review
                                        </option>
                                        <option value="done">Done</option>
                                    </select>
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="task-assignee">
                                        Assignee
                                    </Label>
                                    <select
                                        id="task-assignee"
                                        className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                        value={taskForm.data.assignee_id}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'assignee_id',
                                                e.target.value,
                                            )
                                        }
                                    >
                                        <option value="">Unassigned</option>
                                        {users.map((u) => (
                                            <option key={u.id} value={u.id}>
                                                {u.name}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="task-points">
                                        Story Points
                                    </Label>
                                    <Input
                                        id="task-points"
                                        type="number"
                                        placeholder="e.g. 5"
                                        min={0}
                                        value={taskForm.data.story_points}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'story_points',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="task-due">Due Date</Label>
                                    <Input
                                        id="task-due"
                                        type="date"
                                        value={taskForm.data.due_date}
                                        onChange={(e) =>
                                            taskForm.setData(
                                                'due_date',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>
                            </div>

                            <DialogFooter className="pt-4">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsTaskDialogOpen(false)}
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={taskForm.processing}
                                >
                                    Create Issue
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Task Details Drawer Sheet */}
                <Sheet
                    open={!!selectedTask}
                    onOpenChange={(open) => !open && setSelectedTask(null)}
                >
                    <SheetContent className="w-full overflow-y-auto sm:max-w-xl">
                        <SheetHeader className="mb-4 border-b pb-4">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center space-x-2">
                                    {selectedTask &&
                                        getTypeIcon(editTaskForm.data.type)}
                                    <span className="text-xs font-bold text-muted-foreground uppercase">
                                        {selectedTask?.key}
                                    </span>
                                </div>
                                {hasPermission('projects.delete') &&
                                    selectedTask && (
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="h-8 w-8 text-red-500 hover:bg-red-50"
                                            onClick={() =>
                                                handleDeleteTask(
                                                    selectedTask.id,
                                                )
                                            }
                                        >
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    )}
                            </div>
                            <SheetTitle>Edit Issue Details</SheetTitle>
                            <SheetDescription>
                                Modify specifications, assignee, progress
                                status, and priority details.
                            </SheetDescription>
                        </SheetHeader>

                        {selectedTask && (
                            <form
                                onSubmit={handleUpdateTask}
                                className="space-y-4"
                            >
                                <div className="space-y-1">
                                    <Label htmlFor="edit-title">
                                        Title / Summary
                                    </Label>
                                    <Input
                                        id="edit-title"
                                        value={editTaskForm.data.title}
                                        onChange={(e) =>
                                            editTaskForm.setData(
                                                'title',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="edit-description">
                                        Description
                                    </Label>
                                    <textarea
                                        id="edit-description"
                                        rows={6}
                                        className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
                                        placeholder="Add rich descriptions..."
                                        value={editTaskForm.data.description}
                                        onChange={(e) =>
                                            editTaskForm.setData(
                                                'description',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>

                                <div className="grid grid-cols-2 gap-3 border-t pt-4">
                                    <div className="space-y-1">
                                        <Label htmlFor="edit-status">
                                            Status
                                        </Label>
                                        <select
                                            id="edit-status"
                                            className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                            value={editTaskForm.data.status}
                                            onChange={(e) =>
                                                editTaskForm.setData(
                                                    'status',
                                                    e.target
                                                        .value as Task['status'],
                                                )
                                            }
                                        >
                                            <option value="todo">To Do</option>
                                            <option value="in_progress">
                                                In Progress
                                            </option>
                                            <option value="in_review">
                                                In Review
                                            </option>
                                            <option value="done">Done</option>
                                        </select>
                                    </div>

                                    <div className="space-y-1">
                                        <Label htmlFor="edit-priority">
                                            Priority
                                        </Label>
                                        <select
                                            id="edit-priority"
                                            className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                            value={editTaskForm.data.priority}
                                            onChange={(e) =>
                                                editTaskForm.setData(
                                                    'priority',
                                                    e.target
                                                        .value as Task['priority'],
                                                )
                                            }
                                        >
                                            <option value="lowest">
                                                Lowest
                                            </option>
                                            <option value="low">Low</option>
                                            <option value="medium">
                                                Medium
                                            </option>
                                            <option value="high">High</option>
                                            <option value="highest">
                                                Highest
                                            </option>
                                        </select>
                                    </div>

                                    <div className="space-y-1">
                                        <Label htmlFor="edit-type">
                                            Issue Type
                                        </Label>
                                        <select
                                            id="edit-type"
                                            className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                            value={editTaskForm.data.type}
                                            onChange={(e) =>
                                                editTaskForm.setData(
                                                    'type',
                                                    e.target
                                                        .value as Task['type'],
                                                )
                                            }
                                        >
                                            <option value="task">Task</option>
                                            <option value="subtask">Subtask</option>
                                            <option value="story">Story</option>
                                            <option value="bug">Bug</option>
                                            <option value="epic">Epic</option>
                                        </select>
                                    </div>

                                    {(editTaskForm.data.type === 'task' || editTaskForm.data.type === 'subtask') && (
                                        <div className="space-y-1">
                                            <Label htmlFor="edit-parent">
                                                Parent Task
                                            </Label>
                                            <select
                                                id="edit-parent"
                                                className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                                value={editTaskForm.data.parent_id}
                                                onChange={(e) =>
                                                    editTaskForm.setData(
                                                        'parent_id',
                                                        e.target.value,
                                                    )
                                                }
                                            >
                                                <option value="">None (Independent)</option>
                                                {tasks
                                                    .filter((t) => t.type !== 'subtask' && t.id !== selectedTask?.id)
                                                    .map((t) => (
                                                        <option key={t.id} value={t.id}>
                                                            [{t.key}] {t.title}
                                                        </option>
                                                    ))}
                                            </select>
                                        </div>
                                    )}

                                    <div className="space-y-1">
                                        <Label htmlFor="edit-assignee">
                                            Assignee
                                        </Label>
                                        <select
                                            id="edit-assignee"
                                            className="h-9 w-full rounded-md border bg-card px-2 py-1 text-sm"
                                            value={
                                                editTaskForm.data.assignee_id
                                            }
                                            onChange={(e) =>
                                                editTaskForm.setData(
                                                    'assignee_id',
                                                    e.target.value,
                                                )
                                            }
                                        >
                                            <option value="">Unassigned</option>
                                            {users.map((u) => (
                                                <option key={u.id} value={u.id}>
                                                    {u.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>

                                    <div className="space-y-1">
                                        <Label htmlFor="edit-points">
                                            Story Points
                                        </Label>
                                        <Input
                                            id="edit-points"
                                            type="number"
                                            min={0}
                                            value={
                                                editTaskForm.data.story_points
                                            }
                                            onChange={(e) =>
                                                editTaskForm.setData(
                                                    'story_points',
                                                    e.target.value,
                                                )
                                            }
                                        />
                                    </div>

                                    <div className="space-y-1">
                                        <Label htmlFor="edit-due">
                                            Due Date
                                        </Label>
                                        <Input
                                            id="edit-due"
                                            type="date"
                                            value={editTaskForm.data.due_date}
                                            onChange={(e) =>
                                                editTaskForm.setData(
                                                    'due_date',
                                                    e.target.value,
                                                )
                                            }
                                        />
                                    </div>
                                </div>

                                <div className="flex justify-end space-x-2 border-t pt-6">
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => setSelectedTask(null)}
                                    >
                                        Cancel
                                    </Button>
                                    <Button
                                        type="submit"
                                        disabled={editTaskForm.processing}
                                    >
                                        Save Changes
                                    </Button>
                                </div>
                            </form>
                        )}
                    </SheetContent>
                </Sheet>
            </div>
        </>
    );
}

Kanban.layout = {
    breadcrumbs: [
        {
            title: 'Kanban Board',
            href: '/kanban',
        },
    ],
};
