import { type Component, createSignal, onCleanup, onMount } from "solid-js";
import { store } from "@/store";
import { Plus, X } from "lucide-solid";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { QuickEntryForm } from "./QuickEntryForm";

export const QuickEntry: Component = () => {
    const [isOpen, setIsOpen] = createSignal(false);

    const handleKeyDown = (e: KeyboardEvent) => {
        if ((e.metaKey || e.ctrlKey) && e.key === "k") {
            e.preventDefault();
            setIsOpen(prev => !prev);
        }
        if (e.key === "Escape") {
            setIsOpen(false);
        }
    };

    onMount(() => window.addEventListener("keydown", handleKeyDown));
    onCleanup(() => window.removeEventListener("keydown", handleKeyDown));

    return (
        <>
            <Button
                size="icon"
                onClick={() => setIsOpen(true)}
                class={cn(
                    "fixed bottom-20 left-[80%] -translate-x-1/2 md:bottom-10 md:right-10 md:left-auto md:translate-x-0 w-14 h-14 rounded-full shadow-2xl z-50 group hover:scale-110 transition-all duration-300",
                    store.isNotepadMode ? "hidden md:flex" : "flex"
                )}
            >
                <Plus size={28} class="group-hover:rotate-90 transition-transform duration-300" />
            </Button>

            {isOpen() && (
                <div class="fixed inset-0 z-[100] flex items-start justify-center md:pt-[15vh] px-0 md:px-4 pb-0 md:pb-4">
                    <div class="absolute inset-0 bg-background/80 backdrop-blur-sm" onClick={() => setIsOpen(false)} />

                    <div class="relative w-full max-w-xl max-h-[100vh] md:max-h-[80vh] bg-card border border-border rounded-b-2xl md:rounded-2xl shadow-2xl overflow-hidden animate-in fade-in slide-in-from-top-4 md:slide-in-from-bottom-0 md:zoom-in-95 duration-200 flex flex-col">
                        <div class="absolute top-3 right-4 z-[101]">
                            <Button
                                size="icon"
                                variant="ghost"
                                onClick={() => setIsOpen(false)}
                                class="md:hidden h-9 w-9 rounded-full text-muted-foreground hover:text-foreground hover:bg-muted"
                            >
                                <X size={20} />
                            </Button>
                        </div>

                        <div class="flex-1 overflow-hidden">
                            <QuickEntryForm
                                onSuccess={() => setIsOpen(false)}
                                autoFocus={true}
                            />
                        </div>
                    </div>
                </div>
            )}
        </>
    );
};
