import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { LayoutGrid, Loader2, Plus } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { boardCreate, boardList } from '@/client';
import { useProject } from '@/contexts';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

export function ProjectBoards() {
    const { project } = useProject();
    const navigate = useNavigate();
    const [createOpen, setCreateOpen] = useState(false);
    const [createLoading, setCreateLoading] = useState(false);
    const [newName, setNewName] = useState('');
    const [newDesc, setNewDesc] = useState('');

    const { data: boards, isLoading } = useQuery({
        queryKey: ['projectBoards', project?.name],
        queryFn: async () => {
            const resp = await boardList({ path: { project_name: project!.name } });
            return resp.data?.data ?? [];
        },
        enabled: !!project?.name,
    });

    const handleCreate = async () => {
        if (!project?.name || !newName.trim()) return;
        setCreateLoading(true);
        try {
            const resp = await boardCreate({
                path: { project_name: project.name },
                body: { name: newName.trim(), description: newDesc.trim() || undefined },
            });
            setCreateOpen(false);
            setNewName('');
            setNewDesc('');
            if (resp.data?.data) {
                navigate(`/project/${project.name}/boards/${resp.data.data.id}`);
            }
        } catch {
            toast.error('Failed to create board');
        } finally {
            setCreateLoading(false);
        }
    };

    if (!project) return null;

    return (
        <div className="mx-auto flex min-h-full w-full max-w-[1200px] flex-col gap-6 px-6 pt-6 pb-8">
            {/* Header */}
            <div className="border-b border-[#E4E4E7] pb-4">
                <div className="flex items-center gap-3">
                    <h1 className="text-[17px] font-semibold tracking-tight flex items-center gap-2">
                        Boards
                        <span className="inline-flex items-center rounded-full border border-[#E4E4E7] bg-[#F4F4F5] px-2.5 py-0.5 text-[12px] font-medium text-[#52525B]">
                            {boards?.length ?? 0}
                        </span>
                    </h1>
                </div>
            </div>

            {/* Toolbar */}
            <div className="flex items-center justify-end">
                <button
                    onClick={() => setCreateOpen(true)}
                    className="inline-flex items-center justify-center gap-2 rounded-lg border border-[#D4D4D8] bg-[#18181B] px-4 py-2.5 text-[13px] font-medium text-white transition-colors hover:bg-[#27272A] cursor-pointer"
                >
                    <Plus className="h-3.5 w-3.5" />
                    New Board
                </button>
            </div>

            {/* Board Grid */}
            {isLoading ? (
                <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
                    {[1, 2].map((i) => (
                        <div key={i} className="h-28 rounded-xl border border-[#E4E4E7] bg-white animate-pulse" />
                    ))}
                </div>
            ) : boards?.length === 0 ? (
                <div className="flex flex-1 flex-col items-center justify-center pb-20 text-center">
                    <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl border border-dashed border-[#D4D4D8]">
                        <LayoutGrid className="h-5 w-5 text-[#8B8B94]" />
                    </div>
                    <h3 className="mb-1.5 text-[14px] font-semibold text-[#52525B]">No boards yet</h3>
                    <p className="text-[13px] text-[#71717A]">
                        Create a board to organize your project work.
                    </p>
                </div>
            ) : (
                <div className="grid grid-cols-2 gap-3 lg:grid-cols-3 pb-8">
                    {boards?.map((board) => (
                        <button
                            key={board.id}
                            type="button"
                            onClick={() => navigate(`/project/${project.name}/boards/${board.id}`)}
                            className="group flex flex-col rounded-xl border border-[#E4E4E7] bg-white p-4 text-left transition-all hover:border-[#D4D4D8] hover:bg-[#F4F4F5]/40 hover:shadow-sm cursor-pointer"
                        >
                            <div className="mb-2 flex items-center gap-2">
                                <LayoutGrid className="h-5 w-5 text-[#18181B]" />
                                <span className="font-semibold text-[14px] text-[#18181B]">{board.name}</span>
                            </div>
                            {board.description && (
                                <p className="text-[13px] text-[#52525B] line-clamp-2">{board.description}</p>
                            )}
                            <p className="mt-auto pt-2 text-[12px] text-[#8B8B94]">
                                Updated {new Date(board.updated_at).toLocaleDateString()}
                            </p>
                        </button>
                    ))}
                </div>
            )}

            {/* Create Dialog */}
            <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                <DialogContent className="max-w-sm">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-[15px] font-semibold">
                            <LayoutGrid className="h-4 w-4 text-[#18181B]" />
                            New Board
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <div className="space-y-1.5">
                            <Label htmlFor="board-name" className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]">
                                Name
                            </Label>
                            <Input
                                id="board-name"
                                value={newName}
                                onChange={(e) => setNewName(e.target.value)}
                                placeholder="e.g. Sprint Planning"
                                className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                                autoFocus
                            />
                        </div>
                        <div className="space-y-1.5">
                            <Label htmlFor="board-desc" className="text-[12px] font-semibold uppercase tracking-[0.08em] text-[#71717A]">
                                Description
                            </Label>
                            <Input
                                id="board-desc"
                                value={newDesc}
                                onChange={(e) => setNewDesc(e.target.value)}
                                placeholder="Optional"
                                className="h-10 border-[#E4E4E7] focus:border-[#D4D4D8]"
                            />
                        </div>
                        <div className="flex justify-end gap-2 pt-2">
                            <button
                                onClick={() => setCreateOpen(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={handleCreate}
                                disabled={createLoading || !newName.trim()}
                                className="inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border border-[#D4D4D8] bg-[#18181B] text-[13px] font-medium text-white transition-colors hover:bg-[#27272A] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                            >
                                {createLoading && <Loader2 className="h-4 w-4 animate-spin" />}
                                Create Board
                            </button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
