import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'sonner';
import { ArrowLeft, LayoutGrid, Loader2, MoreHorizontal, Pencil, Plus, Trash2 } from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { boardDelete, boardGet, boardUpdate, columnCreate } from '@/client';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import { KanbanBoard } from '@/components/project/KanbanBoard';

export function ProjectBoardDetail() {
    const { project_name, boardId } = useParams<{ project_name: string; boardId: string }>();
    const navigate = useNavigate();
    const queryClient = useQueryClient();
    const [addingColumn, setAddingColumn] = useState(false);
    const [newColumnName, setNewColumnName] = useState('');
    const [editOpen, setEditOpen] = useState(false);
    const [editLoading, setEditLoading] = useState(false);
    const [editName, setEditName] = useState('');
    const [editDesc, setEditDesc] = useState('');

    const { data: board, isLoading } = useQuery({
        queryKey: ['projectBoard', project_name, boardId],
        queryFn: async () => {
            const resp = await boardGet({
                path: { project_name: project_name!, board_id: boardId! },
            });
            return resp.data?.data ?? null;
        },
        enabled: !!project_name && !!boardId,
    });

    const addColMutation = useMutation({
        mutationFn: async (name: string) => {
            await columnCreate({
                path: { project_name: project_name!, board_id: boardId! },
                body: { name, position: board?.columns.length ?? 0 },
            });
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['projectBoard', project_name, boardId] });
            setAddingColumn(false);
            setNewColumnName('');
            toast.success('Column added');
        },
        onError: () => toast.error('Failed to add column'),
    });

    const openEditDialog = () => {
        if (!board) return;
        setEditName(board.board.name);
        setEditDesc(board.board.description ?? '');
        setEditOpen(true);
    };

    const handleEditBoard = async () => {
        if (!project_name || !boardId || !editName.trim()) return;
        setEditLoading(true);
        try {
            await boardUpdate({
                path: { project_name, board_id: boardId },
                body: {
                    name: editName.trim(),
                    description: editDesc.trim() || undefined,
                },
            });
            setEditOpen(false);
            queryClient.invalidateQueries({ queryKey: ['projectBoard', project_name, boardId] });
            toast.success('Board updated');
        } catch {
            toast.error('Failed to update board');
        } finally {
            setEditLoading(false);
        }
    };

    const handleDelete = async () => {
        if (!project_name || !boardId) return;
        if (!confirm('Delete this board? This cannot be undone.')) return;
        try {
            await boardDelete({ path: { project_name, board_id: boardId } });
            navigate(`/project/${project_name}/boards`);
        } catch {
            toast.error('Failed to delete board');
        }
    };

    if (!project_name) return null;

    if (isLoading) {
        return (
            <div className="flex h-full items-center justify-center">
                <Spinner />
            </div>
        );
    }

    if (!board) {
        return (
            <div className="flex h-full flex-col items-center justify-center gap-4">
                <p className="text-[#71717A]">Board not found.</p>
                <button
                    type="button"
                    onClick={() => navigate(`/project/${project_name}/boards`)}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg border border-[#E4E4E7] bg-white text-[13px] font-medium text-[#27272A] hover:bg-[#F4F4F5] transition-colors cursor-pointer"
                >
                    <ArrowLeft className="h-4 w-4" />
                    Back to Boards
                </button>
            </div>
        );
    }

    return (
        <div className="flex h-full flex-col">
            {/* Header */}
            <div className="flex items-center gap-3 border-b border-[#E4E4E7] px-4 py-3">
                <button
                    type="button"
                    onClick={() => navigate(`/project/${project_name}/boards`)}
                    className="flex h-8 w-8 items-center justify-center rounded-md hover:bg-[#F4F4F5] cursor-pointer bg-transparent border-0 transition-colors"
                >
                    <ArrowLeft className="h-4 w-4" />
                </button>
                <LayoutGrid className="h-5 w-5 text-[#18181B]" />
                <h1 className="text-[15px] font-semibold text-[#18181B]">{board.board.name}</h1>
                {board.board.description && (
                    <p className="text-[13px] text-[#71717A]">— {board.board.description}</p>
                )}
                <div className="ml-auto flex items-center gap-2">
                    {/* Add Column */}
                    <button
                        onClick={() => setAddingColumn(true)}
                        className="inline-flex items-center gap-1.5 rounded-lg border border-[#D4D4D8] bg-white px-3 py-1.5 text-[13px] font-medium text-[#27272A] hover:bg-[#F4F4F5] transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                    >
                        {addColMutation.isPending ? (
                            <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        ) : (
                            <Plus className="h-3.5 w-3.5" />
                        )}
                        Add Column
                    </button>

                    {/* Board menu */}
                    <div className="relative">
                        <button
                            type="button"
                            onClick={(e) => {
                                const btn = e.currentTarget;
                                const menu = btn.nextElementSibling as HTMLElement | null;
                                if (menu) menu.classList.toggle('hidden');
                            }}
                            className="flex h-8 w-8 items-center justify-center rounded-md hover:bg-[#F4F4F5] cursor-pointer bg-transparent border-0 transition-colors"
                        >
                            <MoreHorizontal className="h-4 w-4" />
                        </button>
                        <div className="hidden absolute right-0 top-full mt-1 z-20 w-44 rounded-lg border border-[#E4E4E7] bg-white p-1 shadow-lg">
                            <button
                                type="button"
                                onClick={openEditDialog}
                                className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-[13px] text-[#27272A] hover:bg-[#F4F4F5] cursor-pointer bg-transparent border-0 text-left transition-colors"
                            >
                                <Pencil className="h-4 w-4" />
                                Edit board
                            </button>
                            <button
                                type="button"
                                onClick={handleDelete}
                                className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-[13px] text-[#DC2626] hover:bg-[rgba(220,38,38,0.08)] cursor-pointer bg-transparent border-0 text-left transition-colors"
                            >
                                <Trash2 className="h-4 w-4" />
                                Delete board
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            {/* Board */}
            <div className="flex-1 overflow-hidden">
                <KanbanBoard board={board} onCardMoved={() => queryClient.invalidateQueries({ queryKey: ['projectBoard', project_name, boardId] })} />
            </div>

            {/* Add Column Dialog */}
            <Dialog open={addingColumn} onOpenChange={setAddingColumn}>
                <DialogContent className="max-w-xs">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-[15px] font-semibold">
                            <Plus className="h-4 w-4 text-[#18181B]" />
                            Add Column
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <div className="space-y-1.5">
                            <Label htmlFor="col-name" className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]">
                                Column Name
                            </Label>
                            <Input
                                id="col-name"
                                value={newColumnName}
                                onChange={(e) => setNewColumnName(e.target.value)}
                                placeholder="e.g. To Do"
                                className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                                autoFocus
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') addColMutation.mutate(newColumnName.trim());
                                }}
                            />
                        </div>
                        <div className="flex justify-end gap-2">
                            <button
                                onClick={() => setAddingColumn(false)}
                                className="px-4 py-2.5 rounded-lg border border-[#E4E4E7] bg-white text-[13px] font-medium text-[#27272A] hover:bg-[#F4F4F5] transition-colors cursor-pointer"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={() => addColMutation.mutate(newColumnName.trim())}
                                disabled={!newColumnName.trim() || addColMutation.isPending}
                                className="px-4 py-2.5 rounded-lg border border-[#D4D4D8] bg-[#18181B] text-[13px] font-medium text-white hover:bg-[#27272A] transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                            >
                                Add Column
                            </button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            {/* Edit Board Dialog */}
            <Dialog open={editOpen} onOpenChange={setEditOpen}>
                <DialogContent className="max-w-sm">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-[15px] font-semibold">
                            <Pencil className="h-4 w-4 text-[#18181B]" />
                            Edit Board
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <div className="space-y-1.5">
                            <Label htmlFor="edit-name" className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]">
                                Name
                            </Label>
                            <Input
                                id="edit-name"
                                value={editName}
                                onChange={(e) => setEditName(e.target.value)}
                                placeholder="Board name"
                                className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                                autoFocus
                            />
                        </div>
                        <div className="space-y-1.5">
                            <Label htmlFor="edit-desc" className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]">
                                Description
                            </Label>
                            <Input
                                id="edit-desc"
                                value={editDesc}
                                onChange={(e) => setEditDesc(e.target.value)}
                                placeholder="Optional"
                                className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                            />
                        </div>
                        <div className="flex justify-end gap-2">
                            <button
                                onClick={() => setEditOpen(false)}
                                className="px-4 py-2.5 rounded-lg border border-[#E4E4E7] bg-white text-[13px] font-medium text-[#27272A] hover:bg-[#F4F4F5] transition-colors cursor-pointer"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={handleEditBoard}
                                disabled={editLoading || !editName.trim()}
                                className="px-4 py-2.5 rounded-lg border border-[#D4D4D8] bg-[#18181B] text-[13px] font-medium text-white hover:bg-[#27272A] transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                            >
                                {editLoading && <Loader2 className="h-4 w-4 animate-spin" />}
                                Save Changes
                            </button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
