import { Head, router, useForm } from '@inertiajs/react';
import { CheckSquare, Plus, Edit, Trash2, ArrowUpDown } from 'lucide-react';
import { useState, useMemo } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import AppLayout from '@/layouts/app-layout';

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;
    assignee?: User | null;
    parent?: { id: number; key: string; title: string } | null;
}

interface Project {
    id: number;
    name: string;
    key: string;
}

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

export default function ProjectTasksPage({
    projects,
    activeProjectId: initialActiveProjectId,
    tasks,
    users,
}: Props) {
    const [selectedProjectId, setSelectedProjectId] = useState<number | ''>(
        initialActiveProjectId || '',
    );
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [editingTask, setEditingTask] = useState<Task | null>(null);

    // Form states
    const taskForm = useForm({
        project_id: initialActiveProjectId || '',
        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,
    });

    const handleProjectChange = (id: number | '') => {
        setSelectedProjectId(id);
        router.get(
            '/project-tasks',
            { project_id: id },
            { preserveState: false },
        );
    };

    const handleCreateTask = (e: React.FormEvent) => {
        e.preventDefault();
        taskForm.post(route('tasks.store'), {
            onSuccess: () => {
                setIsCreateOpen(false);
                taskForm.reset();
                toast.success('Task created successfully!');
            },
            onError: (errors) => {
                toast.error(errors.title || 'Failed to create task.');
            },
        });
    };

    const handleEditClick = (task: Task) => {
        setEditingTask(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 (!editingTask) return;

        editTaskForm.put(route('tasks.update', editingTask.id), {
            onSuccess: () => {
                setEditingTask(null);
                toast.success('Task updated successfully!');
            },
            onError: (errors) => {
                toast.error(errors.title || 'Failed to update task.');
            },
        });
    };

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

    return (
        <>
            <Head title="Project Tasks Register" />
            <div className="space-y-6 p-6">
                {/* Header */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600 dark:bg-indigo-950/50 dark:text-indigo-400">
                            <CheckSquare className="size-5" />
                        </div>
                        <div>
                            <h1 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-50">
                                Project Tasks Register
                            </h1>
                            <p className="text-xs text-zinc-500 font-medium">
                                View, create, and update tasks dynamically in a tabular matrix sheet.
                            </p>
                        </div>
                    </div>

                    {selectedProjectId && (
                        <Button
                            onClick={() => {
                                taskForm.setData('project_id', selectedProjectId);
                                setIsCreateOpen(true);
                            }}
                            className="flex h-9 items-center gap-1.5 rounded-xl bg-indigo-600 px-4 text-xs font-bold text-white shadow-md hover:bg-indigo-700"
                        >
                            <Plus className="size-4" /> Add Task
                        </Button>
                    )}
                </div>

                {/* Project Selector Card */}
                <Card className="rounded-2xl border-zinc-200/60 p-5 dark:border-zinc-800/60">
                    <div className="max-w-xs space-y-1.5">
                        <Label htmlFor="project-select" className="text-xs font-bold text-zinc-500">
                            Select Active Project
                        </Label>
                        <select
                            id="project-select"
                            className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-sm font-medium focus:outline-none"
                            value={selectedProjectId}
                            onChange={(e) =>
                                handleProjectChange(
                                    e.target.value
                                        ? Number(e.target.value)
                                        : '',
                                )
                            }
                        >
                            <option value="">-- Choose a Project --</option>
                            {projects.map((p) => (
                                <option key={p.id} value={p.id}>
                                    [{p.key}] {p.name}
                                </option>
                            ))}
                        </select>
                    </div>
                </Card>

                {/* Tasks Table */}
                {selectedProjectId ? (
                    <Card className="overflow-hidden rounded-2xl border-zinc-200/60 shadow-sm dark:border-zinc-800/60">
                        <div className="overflow-x-auto">
                            <table className="w-full border-collapse text-left text-xs">
                                <thead>
                                    <tr className="border-b border-zinc-100 bg-zinc-50/50 text-zinc-500 dark:border-zinc-800/50 dark:bg-zinc-900/20">
                                        <th className="p-4 font-bold">Key</th>
                                        <th className="p-4 font-bold">Title</th>
                                        <th className="p-4 font-bold">Type</th>
                                        <th className="p-4 font-bold">Status</th>
                                        <th className="p-4 font-bold">Priority</th>
                                        <th className="p-4 font-bold">Story Points</th>
                                        <th className="p-4 font-bold">Due Date</th>
                                        <th className="p-4 font-bold">Assignee</th>
                                        <th className="p-4 font-bold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/50">
                                    {tasks.map((task) => (
                                        <tr
                                            key={task.id}
                                            className="hover:bg-zinc-50/40 dark:hover:bg-zinc-900/10"
                                        >
                                            <td className="p-4 font-extrabold text-indigo-600 dark:text-indigo-400">
                                                {task.key}
                                            </td>
                                            <td className="p-4">
                                                <div>
                                                    <span className="font-semibold text-zinc-900 dark:text-zinc-100">
                                                        {task.title}
                                                    </span>
                                                    {task.parent && (
                                                        <span className="ml-2 rounded bg-zinc-100 px-1.5 py-0.5 text-[10px] font-bold text-zinc-500 dark:bg-zinc-800">
                                                            Parent: {task.parent.key}
                                                        </span>
                                                    )}
                                                </div>
                                                {task.description && (
                                                    <p className="mt-0.5 truncate text-[10px] text-zinc-400 max-w-xs">
                                                        {task.description}
                                                    </p>
                                                )}
                                            </td>
                                            <td className="p-4 capitalize">
                                                <span className={`inline-block rounded px-1.5 py-0.5 text-[10px] font-bold ${
                                                    task.type === 'bug'
                                                        ? 'bg-red-50 text-red-600 dark:bg-red-950/20 dark:text-red-400'
                                                        : task.type === 'story'
                                                        ? 'bg-green-50 text-green-600 dark:bg-green-950/20 dark:text-green-400'
                                                        : task.type === 'subtask'
                                                        ? 'bg-sky-50 text-sky-600 dark:bg-sky-950/20 dark:text-sky-400'
                                                        : 'bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300'
                                                }`}>
                                                    {task.type}
                                                </span>
                                            </td>
                                            <td className="p-4 capitalize">
                                                <span className={`inline-block rounded-full px-2 py-0.5 text-[10px] font-semibold ${
                                                    task.status === 'done'
                                                        ? 'bg-green-100 text-green-800 dark:bg-green-950/30 dark:text-green-400'
                                                        : task.status === 'in_progress'
                                                        ? 'bg-blue-100 text-blue-800 dark:bg-blue-950/30 dark:text-blue-400'
                                                        : 'bg-zinc-100 text-zinc-800 dark:bg-zinc-800 dark:text-zinc-300'
                                                }`}>
                                                    {task.status.replace('_', ' ')}
                                                </span>
                                            </td>
                                            <td className="p-4 capitalize">
                                                <span className={`inline-block rounded px-1.5 py-0.5 text-[10px] font-bold ${
                                                    task.priority === 'highest' || task.priority === 'high'
                                                        ? 'bg-amber-50 text-amber-600 dark:bg-amber-950/20'
                                                        : 'bg-zinc-50 text-zinc-500 dark:bg-zinc-900'
                                                }`}>
                                                    {task.priority}
                                                </span>
                                            </td>
                                            <td className="p-4 font-medium text-zinc-500">
                                                {task.story_points ?? '-'}
                                            </td>
                                            <td className="p-4 text-zinc-500">
                                                {task.due_date ? new Date(task.due_date).toLocaleDateString() : '-'}
                                            </td>
                                            <td className="p-4 font-semibold text-zinc-900 dark:text-zinc-100">
                                                {task.assignee?.name ?? 'Unassigned'}
                                            </td>
                                            <td className="p-4 text-right">
                                                <div className="flex justify-end gap-1.5">
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 rounded-lg text-zinc-500 hover:bg-zinc-100"
                                                        onClick={() => handleEditClick(task)}
                                                    >
                                                        <Edit className="size-3.5" />
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 rounded-lg text-red-500 hover:bg-red-50"
                                                        onClick={() => handleDeleteTask(task.id)}
                                                    >
                                                        <Trash2 className="size-3.5" />
                                                    </Button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </Card>
                ) : (
                    <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-zinc-200 py-12 text-center dark:border-zinc-800">
                        <CheckSquare className="size-10 text-zinc-300 dark:text-zinc-700" />
                        <h3 className="mt-4 text-sm font-bold text-zinc-900 dark:text-zinc-100">
                            No Project Selected
                        </h3>
                        <p className="mt-1 text-xs text-zinc-500">
                            Please select a project from the dropdown list above to view and update tasks registry.
                        </p>
                    </div>
                )}

                {/* Create Dialog */}
                <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Add Project Task</DialogTitle>
                            <DialogDescription>
                                Add a new development deliverable to the project scope.
                            </DialogDescription>
                        </DialogHeader>
                        <form onSubmit={handleCreateTask} className="space-y-4 pt-2">
                            <div className="space-y-1">
                                <Label htmlFor="create-title">Title</Label>
                                <Input
                                    id="create-title"
                                    value={taskForm.data.title}
                                    onChange={(e) => taskForm.setData('title', e.target.value)}
                                    placeholder="e.g. Implement API route"
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-description">Description</Label>
                                <Input
                                    id="create-description"
                                    value={taskForm.data.description}
                                    onChange={(e) => taskForm.setData('description', e.target.value)}
                                    placeholder="Deliverable description details..."
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-2">
                                <div className="space-y-1">
                                    <Label htmlFor="create-type">Type</Label>
                                    <select
                                        id="create-type"
                                        className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-xs focus:outline-none"
                                        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>
                                <div className="space-y-1">
                                    <Label htmlFor="create-status">Status</Label>
                                    <select
                                        id="create-status"
                                        className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-xs focus:outline-none"
                                        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>

                            {(taskForm.data.type === 'task' || taskForm.data.type === 'subtask') && (
                                <div className="space-y-1">
                                    <Label htmlFor="create-parent">Parent Task</Label>
                                    <select
                                        id="create-parent"
                                        className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-xs focus:outline-none"
                                        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="grid grid-cols-2 gap-2">
                                <div className="space-y-1">
                                    <Label htmlFor="create-priority">Priority</Label>
                                    <select
                                        id="create-priority"
                                        className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-xs focus:outline-none"
                                        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="create-sp">Story Points</Label>
                                    <Input
                                        id="create-sp"
                                        type="number"
                                        value={taskForm.data.story_points}
                                        onChange={(e) => taskForm.setData('story_points', e.target.value)}
                                    />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-2">
                                <div className="space-y-1">
                                    <Label htmlFor="create-due">Due Date</Label>
                                    <Input
                                        id="create-due"
                                        type="date"
                                        value={taskForm.data.due_date}
                                        onChange={(e) => taskForm.setData('due_date', e.target.value)}
                                    />
                                </div>
                                <div className="space-y-1">
                                    <Label htmlFor="create-assignee">Assignee</Label>
                                    <select
                                        id="create-assignee"
                                        className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-xs focus:outline-none"
                                        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>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsCreateOpen(false)}
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    className="bg-indigo-600 text-white hover:bg-indigo-700 font-bold"
                                >
                                    Save Task
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Dialog */}
                <Dialog open={editingTask !== null} onOpenChange={(open) => !open && setEditingTask(null)}>
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Edit Project Task</DialogTitle>
                            <DialogDescription>
                                Update the development deliverable parameters.
                            </DialogDescription>
                        </DialogHeader>
                        <form onSubmit={handleUpdateTask} className="space-y-4 pt-2">
                            <div className="space-y-1">
                                <Label htmlFor="edit-title">Title</Label>
                                <Input
                                    id="edit-title"
                                    value={editTaskForm.data.title}
                                    onChange={(e) => editTaskForm.setData('title', e.target.value)}
                                    placeholder="e.g. Implement API route"
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="edit-description">Description</Label>
                                <Input
                                    id="edit-description"
                                    value={editTaskForm.data.description}
                                    onChange={(e) => editTaskForm.setData('description', e.target.value)}
                                    placeholder="Deliverable description details..."
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-2">
                                <div className="space-y-1">
                                    <Label htmlFor="edit-type">Type</Label>
                                    <select
                                        id="edit-type"
                                        className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-xs focus:outline-none"
                                        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>
                                <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.5 py-1 text-xs focus:outline-none"
                                        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>

                            {(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.5 py-1 text-xs focus:outline-none"
                                        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 !== editingTask?.id)
                                            .map((t) => (
                                                <option key={t.id} value={t.id}>
                                                    [{t.key}] {t.title}
                                                </option>
                                            ))}
                                    </select>
                                </div>
                            )}

                            <div className="grid grid-cols-2 gap-2">
                                <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.5 py-1 text-xs focus:outline-none"
                                        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-sp">Story Points</Label>
                                    <Input
                                        id="edit-sp"
                                        type="number"
                                        value={editTaskForm.data.story_points}
                                        onChange={(e) => editTaskForm.setData('story_points', e.target.value)}
                                    />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-2">
                                <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 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.5 py-1 text-xs focus:outline-none"
                                        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>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setEditingTask(null)}
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    className="bg-indigo-600 text-white hover:bg-indigo-700 font-bold"
                                >
                                    Save Changes
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>
            </div>
        </>
    );
}
