import { useEffect, useMemo, useState } from "react";
import { router, usePage } from "@inertiajs/react";
import {
    Check,
    ChevronsUpDown,
    Building2,
    FolderKanban,
    LayoutGrid,
    Lock,
    Unlock,
} from "lucide-react";

import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/Components/ui/popover";
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from "@/Components/ui/tooltip";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";
import { Search } from "lucide-react";
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils";
import { usePresentationMode } from "@/Components/PresentationModeProvider";
import {
    PRESENTATION_PROJECTS,
    PRESENTATION_GROUPS,
    isPresentationProject,
    presentationSlug,
} from "@/lib/presentation/presentationProjects";

const MAX_VISIBLE = 200;
const ALL_PROJECTS_KEY = "__all__";
const LOCK_STORAGE_KEY = "locked_project_scope";

const VISIBLE_ROUTES = [
    "dashboard",
    "dashboard.*",
    "relatorios",
    "relatorios.*",
    "projetos.edit",
    "projetos.dashboard-config.*",
    "integracoes.*",
];

export default function ProjectSwitcher() {
    const { props } = usePage();
    const { projectContext, projects, projectGroups, auth } = props;
    const { enabled: presentationMode, disable: disablePresentation } = usePresentationMode();
    const isMobile = useIsMobile();
    const [open, setOpen] = useState(false);
    const [search, setSearch] = useState("");
    const [pendingId, setPendingId] = useState(undefined);
    const [activeGroupId, setActiveGroupId] = useState(ALL_PROJECTS_KEY);
    const [unlockArmed, setUnlockArmed] = useState(false);
    const [exitArmed, setExitArmed] = useState(false);
    const [lockedScope, setLockedScope] = useState(() => {
        if (typeof window === "undefined") return null;
        const raw = localStorage.getItem(LOCK_STORAGE_KEY);
        if (!raw) return null;
        try {
            const parsed = JSON.parse(raw);
            if (parsed && (parsed.type === "group" || parsed.type === "project") && parsed.id) {
                return parsed;
            }
        } catch (_) {
            // ignore
        }
        return null;
    });

    useEffect(() => {
        if (lockedScope) {
            localStorage.setItem(LOCK_STORAGE_KEY, JSON.stringify(lockedScope));
        } else {
            localStorage.removeItem(LOCK_STORAGE_KEY);
        }
    }, [lockedScope]);

    if (!projectContext) return null;

    const shouldShow = VISIBLE_ROUTES.some((pattern) => route().current(pattern));
    if (!shouldShow) return null;

    const isExent = auth?.permissions?.is_exent ?? false;
    // Modo Apresentação: mostra só os 2 projetos fake (B2B/Incorp) sob o grupo "Apresentação".
    const projectList = presentationMode ? PRESENTATION_PROJECTS : projects || [];
    const groupList = presentationMode ? PRESENTATION_GROUPS : projectGroups || [];

    const lockedGroup =
        lockedScope?.type === "group"
            ? (groupList.find((g) => g.id === lockedScope.id) ?? null)
            : null;

    const lockedProject =
        lockedScope?.type === "project"
            ? (projectList.find((p) => p.id === lockedScope.id) ?? null)
            : null;

    const isLocked = Boolean(lockedGroup || lockedProject);

    useEffect(() => {
        if (!lockedScope) return;
        if (lockedScope.type === "group" && groupList.length > 0 && !lockedGroup) {
            setLockedScope(null);
        }
        if (lockedScope.type === "project" && projectList.length > 0 && !lockedProject) {
            setLockedScope(null);
        }
    }, [lockedScope, lockedGroup, lockedProject, groupList.length, projectList.length]);

    const pageProjectId = props.project?.id ?? null;

    const selectedId =
        pendingId !== undefined
            ? pendingId
            : (pageProjectId ?? projectContext.selected_project_id ?? null);

    if (projectList.length === 0 && !isExent) return null;

    const selectedProject = projectList.find((p) => p.id === selectedId) ?? null;

    const query = search.trim().toLowerCase();

    const byName = (a, b) => a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" });

    const { visibleGroups, visibleProjects } = useMemo(() => {
        if (lockedProject) {
            const list = [lockedProject].filter((p) =>
                query ? p.name.toLowerCase().includes(query) : true
            );
            return { visibleGroups: [], visibleProjects: list };
        }
        if (lockedGroup) {
            const projectsInGroup = [...lockedGroup.projects].sort(byName);
            const filtered = query
                ? projectsInGroup.filter((p) =>
                      p.name.toLowerCase().includes(query)
                  )
                : projectsInGroup;
            return { visibleGroups: [], visibleProjects: filtered };
        }

        const sortedGroups = [...groupList].sort(byName);
        const sortedProjects = [...projectList].sort(byName);

        if (!query) {
            return {
                visibleGroups: sortedGroups,
                visibleProjects:
                    activeGroupId === ALL_PROJECTS_KEY
                        ? sortedProjects.slice(0, MAX_VISIBLE)
                        : ([...(groupList.find((g) => g.id === activeGroupId)?.projects ?? [])].sort(byName)),
            };
        }

        const groupsWithMatches = sortedGroups
            .map((g) => {
                const groupMatches = g.name.toLowerCase().includes(query);
                const matchedProjects = [...g.projects]
                    .sort(byName)
                    .filter((p) => p.name.toLowerCase().includes(query));
                if (groupMatches || matchedProjects.length > 0) {
                    return {
                        ...g,
                        projects: groupMatches
                            ? [...g.projects].sort(byName)
                            : matchedProjects,
                    };
                }
                return null;
            })
            .filter(Boolean);

        const projectsMatching = sortedProjects
            .filter((p) => p.name.toLowerCase().includes(query))
            .slice(0, MAX_VISIBLE);

        let rightProjects;
        if (activeGroupId === ALL_PROJECTS_KEY) {
            rightProjects = projectsMatching;
        } else {
            const activeGroup = groupsWithMatches.find((g) => g.id === activeGroupId);
            rightProjects = activeGroup?.projects ?? [];
        }

        return { visibleGroups: groupsWithMatches, visibleProjects: rightProjects };
    }, [query, groupList, projectList, activeGroupId, lockedGroup, lockedProject]);

    const sortedVisibleProjects = useMemo(() => {
        if (!selectedId) return visibleProjects;
        const idx = visibleProjects.findIndex((p) => p.id === selectedId);
        if (idx <= 0) return visibleProjects;
        const copy = visibleProjects.slice();
        const [picked] = copy.splice(idx, 1);
        copy.unshift(picked);
        return copy;
    }, [visibleProjects, selectedId]);

    const hasMore =
        !isLocked &&
        !query &&
        activeGroupId === ALL_PROJECTS_KEY &&
        projectList.length > MAX_VISIBLE;

    function getTargetUrl(projectId) {
        if (!projectId) return route("dashboard");

        // Projetos fake do Modo Apresentação usam a rota dedicada (sem model binding).
        if (isPresentationProject(projectId)) {
            return route("dashboard.presentation", presentationSlug(projectId));
        }

        if (route().current("projetos.edit")) {
            return route("projetos.edit", projectId);
        }
        if (route().current("projetos.dashboard-config.*")) {
            return route("projetos.dashboard-config.show", projectId);
        }
        if (route().current("relatorios.config") || route().current("relatorios.config.*")) {
            return route("relatorios.config", projectId);
        }
        if (route().current("relatorios") || route().current("relatorios.*")) {
            return route("relatorios.project", projectId);
        }
        return route("dashboard.project", projectId);
    }

    function handleSelect(projectId) {
        const newId = projectId === "global" ? null : projectId;
        setPendingId(newId);
        setOpen(false);
        setSearch("");
        setActiveGroupId(ALL_PROJECTS_KEY);

        router.visit(getTargetUrl(newId), {
            onFinish: () => setPendingId(undefined),
        });
    }

    function handleLockGroup(e, group) {
        e.stopPropagation();
        setLockedScope({ type: "group", id: group.id });
        setSearch("");
        setActiveGroupId(ALL_PROJECTS_KEY);

        const currentInGroup = group.projects.some((p) => p.id === selectedId);
        if (!currentInGroup && group.projects.length > 0) {
            const firstId = group.projects[0].id;
            setPendingId(firstId);
            setOpen(false);
            router.visit(getTargetUrl(firstId), {
                onFinish: () => setPendingId(undefined),
            });
        } else {
            setOpen(false);
        }
    }

    function handleLockProject(e, project) {
        e.stopPropagation();
        setLockedScope({ type: "project", id: project.id });
        setSearch("");
        setActiveGroupId(ALL_PROJECTS_KEY);

        if (selectedId !== project.id) {
            setPendingId(project.id);
            setOpen(false);
            router.visit(getTargetUrl(project.id), {
                onFinish: () => setPendingId(undefined),
            });
        } else {
            setOpen(false);
        }
    }

    function handleUnlockClick() {
        if (unlockArmed) {
            setLockedScope(null);
            setUnlockArmed(false);
            return;
        }
        setUnlockArmed(true);
    }

    useEffect(() => {
        if (!unlockArmed) return;
        const t = setTimeout(() => setUnlockArmed(false), 3000);
        return () => clearTimeout(t);
    }, [unlockArmed]);

    useEffect(() => {
        if (!isLocked) setUnlockArmed(false);
    }, [isLocked]);

    // Botão "Teste" (modo apresentação): 2 cliques p/ sair. 1º clique arma, 2º desativa
    // o modo e volta aos projetos reais. Auto-desarma em 3s.
    function handleExitPresentation(e) {
        e.stopPropagation();
        if (exitArmed) {
            setExitArmed(false);
            setOpen(false);
            disablePresentation();
            router.visit(route("dashboard"));
            return;
        }
        setExitArmed(true);
    }

    useEffect(() => {
        if (!exitArmed) return;
        const t = setTimeout(() => setExitArmed(false), 3000);
        return () => clearTimeout(t);
    }, [exitArmed]);

    useEffect(() => {
        if (!presentationMode) setExitArmed(false);
    }, [presentationMode]);

    return (
        <div className="flex items-center gap-1.5">
        <Popover
            open={open}
            onOpenChange={(v) => {
                setOpen(v);
                if (!v) {
                    setSearch("");
                    setActiveGroupId(ALL_PROJECTS_KEY);
                }
            }}
        >
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={open}
                    className="h-8 w-[160px] sm:w-[220px] justify-between border-dashed text-xs font-normal gap-1.5"
                >
                    <span className="flex items-center gap-1.5 truncate min-w-0">
                        <Building2 className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        <span className="truncate">
                            {selectedProject ? selectedProject.name : "Selecionar projeto"}
                        </span>
                    </span>
                    <ChevronsUpDown className="h-3 w-3 shrink-0 opacity-40" />
                </Button>
            </PopoverTrigger>

            <PopoverContent
                className={cn(
                    "p-0 overflow-hidden max-w-[calc(100vw-1.5rem)]",
                    isLocked ? "w-[300px]" : "w-[520px]"
                )}
                align="start"
            >
                {/* Busca */}
                <div className="border-b p-2">
                    <div className="relative">
                        <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
                        <Input
                            placeholder={
                                lockedGroup
                                    ? "Buscar projeto..."
                                    : "Buscar grupo ou projeto..."
                            }
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                            className="h-9 pl-7 text-sm"
                        />
                    </div>
                </div>

                <div className="flex max-h-[400px]">
                    {/* Coluna esquerda: Grupos (desktop) */}
                    {!isLocked && !isMobile && (
                        <div className="w-[200px] border-r flex flex-col">
                            <div className="px-3 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground border-b">
                                Grupos
                            </div>
                            <div
                                className="flex-1 overflow-y-auto py-1"
                                style={{ scrollbarGutter: "stable" }}
                            >
                                <button
                                    type="button"
                                    onClick={() => setActiveGroupId(ALL_PROJECTS_KEY)}
                                    className={cn(
                                        "flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-accent",
                                        activeGroupId === ALL_PROJECTS_KEY && "bg-accent"
                                    )}
                                >
                                    <LayoutGrid className="h-4 w-4 text-muted-foreground shrink-0" />
                                    <span className="truncate text-left">Todos os projetos</span>
                                    <span className="ml-auto text-xs text-muted-foreground shrink-0">
                                        {projectList.length}
                                    </span>
                                </button>
                                {visibleGroups.map((group) => (
                                    <div
                                        key={group.id}
                                        className={cn(
                                            "group/row relative flex items-center hover:bg-accent",
                                            activeGroupId === group.id && "bg-accent"
                                        )}
                                    >
                                        <button
                                            type="button"
                                            onClick={() => setActiveGroupId(group.id)}
                                            className="flex flex-1 min-w-0 items-center gap-2 px-3 py-2 text-sm"
                                        >
                                            <FolderKanban className="h-4 w-4 text-muted-foreground shrink-0" />
                                            <span className="truncate text-left">{group.name}</span>
                                            <span className="ml-auto text-xs text-muted-foreground shrink-0 group-hover/row:hidden">
                                                {group.projects.length}
                                            </span>
                                        </button>
                                        <button
                                            type="button"
                                            onClick={(e) => handleLockGroup(e, group)}
                                            title="Travar visualização neste grupo"
                                            className="hidden group-hover/row:flex items-center justify-center w-7 h-7 mr-1 rounded text-muted-foreground hover:text-brand hover:bg-background"
                                        >
                                            <Lock className="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                ))}
                                {visibleGroups.length === 0 && !query && (
                                    <p className="px-3 py-2 text-xs text-muted-foreground">
                                        Nenhum grupo cadastrado.
                                    </p>
                                )}
                            </div>
                        </div>
                    )}

                    {/* Coluna direita: Projetos */}
                    <div className="flex-1 flex flex-col min-w-0">
                        {isMobile && !isLocked ? (
                            <div className="border-b p-2">
                                <Select
                                    value={activeGroupId}
                                    onValueChange={setActiveGroupId}
                                >
                                    <SelectTrigger className="h-9 text-sm">
                                        <SelectValue placeholder="Grupo" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value={ALL_PROJECTS_KEY}>
                                            Todos os projetos ({projectList.length})
                                        </SelectItem>
                                        {[...groupList].sort(byName).map((group) => (
                                            <SelectItem key={group.id} value={group.id}>
                                                {group.name} ({group.projects.length})
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                        ) : (
                            <div className="px-3 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground border-b flex items-center justify-between">
                                <span className="truncate">
                                    {lockedGroup
                                        ? lockedGroup.name
                                        : activeGroupId !== ALL_PROJECTS_KEY
                                            ? groupList.find((g) => g.id === activeGroupId)?.name
                                            : "Projetos"}
                                </span>
                            </div>
                        )}
                        <div
                            className="flex-1 overflow-y-auto py-1"
                            style={{ scrollbarGutter: "stable" }}
                        >
                            {sortedVisibleProjects.length > 0 ? (
                                sortedVisibleProjects.map((project) => (
                                    <div
                                        key={project.id}
                                        className={cn(
                                            "group/row relative flex items-center hover:bg-accent",
                                            selectedId === project.id && "bg-accent"
                                        )}
                                    >
                                        <button
                                            type="button"
                                            onClick={() => handleSelect(project.id)}
                                            className="flex flex-1 min-w-0 items-center gap-2 px-3 py-2 text-sm"
                                        >
                                            <span className="truncate text-left">{project.name}</span>
                                            {selectedId === project.id && (
                                                <Check className="ml-auto h-4 w-4 shrink-0 text-brand" />
                                            )}
                                        </button>
                                        {!isLocked && (
                                            <button
                                                type="button"
                                                onClick={(e) => handleLockProject(e, project)}
                                                title="Travar visualização neste projeto"
                                                className={cn(
                                                    "items-center justify-center w-7 h-7 mr-1 rounded text-muted-foreground hover:text-brand hover:bg-background",
                                                    isMobile ? "flex" : "hidden group-hover/row:flex"
                                                )}
                                            >
                                                <Lock className="h-3.5 w-3.5" />
                                            </button>
                                        )}
                                    </div>
                                ))
                            ) : (
                                <p className="px-3 py-4 text-center text-sm text-muted-foreground">
                                    {query
                                        ? "Nenhum resultado encontrado."
                                        : "Nenhum projeto neste grupo."}
                                </p>
                            )}
                            {hasMore && (
                                <p className="px-3 py-2 text-xs text-muted-foreground border-t mt-1">
                                    +{projectList.length - MAX_VISIBLE} projetos - use a busca
                                </p>
                            )}
                        </div>
                    </div>
                </div>

            </PopoverContent>
        </Popover>

            {isLocked && (
                <TooltipProvider delayDuration={0}>
                    <Tooltip open={unlockArmed}>
                        <TooltipTrigger asChild>
                            <button
                                type="button"
                                onClick={handleUnlockClick}
                                aria-label={
                                    unlockArmed
                                        ? "Clique novamente para destravar"
                                        : `Destravar (${lockedGroup ? lockedGroup.name : lockedProject?.name})`
                                }
                                className={cn(
                                    "group/lock flex h-8 w-8 items-center justify-center rounded-md border border-dashed text-muted-foreground transition-colors",
                                    unlockArmed
                                        ? "text-brand border-brand"
                                        : "hover:text-foreground hover:bg-accent"
                                )}
                            >
                                {unlockArmed ? (
                                    <Unlock className="h-3.5 w-3.5" />
                                ) : (
                                    <>
                                        <Lock className="h-3.5 w-3.5 group-hover/lock:hidden" />
                                        <Unlock className="hidden h-3.5 w-3.5 group-hover/lock:block" />
                                    </>
                                )}
                            </button>
                        </TooltipTrigger>
                        <TooltipContent side="bottom">
                            Clique novamente para destravar
                        </TooltipContent>
                    </Tooltip>
                </TooltipProvider>
            )}

            {/* Modo Apresentação: botão "Teste" no mesmo lugar do cadeado (ao lado do
                seletor, fora do popover). 2 cliques para sair. */}
            {presentationMode && (
                <TooltipProvider delayDuration={0}>
                    <Tooltip open={exitArmed}>
                        <TooltipTrigger asChild>
                            <button
                                type="button"
                                onClick={handleExitPresentation}
                                aria-label={
                                    exitArmed
                                        ? "Clique novamente para sair do modo apresentação"
                                        : "Modo apresentação (2 cliques para sair)"
                                }
                                className={cn(
                                    "flex h-8 items-center justify-center gap-1 rounded-md border border-dashed px-2.5 text-xs font-medium transition-colors",
                                    exitArmed
                                        ? "border-input text-foreground hover:bg-accent"
                                        : "border-amber-500 text-amber-600 hover:bg-amber-500/10"
                                )}
                            >
                                {exitArmed ? "Sair?" : "Apresentação"}
                            </button>
                        </TooltipTrigger>
                        <TooltipContent side="bottom">
                            Clique novamente para sair do modo apresentação
                        </TooltipContent>
                    </Tooltip>
                </TooltipProvider>
            )}
        </div>
    );
}
