"use client";
import { useRouterNavigation } from "@/hooks/useRouterNavigation";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { forwardRef, useEffect, useState } from "react";
import { createPortal } from "react-dom";

interface SearchProps {
    placeholder: string;
    onFocus?: () => void;
    onBlur?: () => void;
}

const SearchBar = forwardRef<HTMLInputElement, SearchProps>(
    ({ placeholder, onFocus, onBlur }, ref) => {
        const [query, setQuery] = useState("");
        const [isFocused, setIsFocused] = useState(false);
        const [history, setHistory] = useState<string[]>([]);
        const router = useRouter();
        const pathname = usePathname();
        const searchParams = useSearchParams();
        const { navigate } = useRouterNavigation();

        useEffect(() => {
            const saved = localStorage.getItem("search-history");
            if (saved) setHistory(JSON.parse(saved));
        }, []);

        const saveHistory = (value: string) => {
            if (!value) return;
            const updated = [
                value,
                ...history.filter((item) => item !== value),
            ].slice(0, 5);

            setHistory(updated);
            localStorage.setItem("search-history", JSON.stringify(updated));
        };

        const handleSelect = (value: string) => {
            setQuery(value);
            doSearch(value);
        };

        const doSearch = (value: string) => {
            if (!value.trim()) {
                const params = new URLSearchParams(searchParams.toString());
                params.delete("search");
                params.set("page", "1");

                navigate(`/novel?${params.toString()}`);
                return;
            }

            saveHistory(value);

            const params = new URLSearchParams(searchParams.toString());

            params.set("search", value);
            params.set("page", "1");

            navigate(`/novel?${params.toString()}`);
            setIsFocused(false);
        };

        useEffect(() => {
            const current = searchParams.get("search") || "";
            setQuery(current);
        }, [searchParams]);

        return (
            <>
                {isFocused &&
                    typeof document !== "undefined" &&
                    createPortal(
                        <div
                            className="fixed inset-0 z-30 bg-black/30"
                            onMouseDown={() => setIsFocused(false)}
                        />,
                        document.body
                    )}

                <div className="relative w-full z-40">
                    <input
                        ref={ref}
                        type="text"
                        placeholder={placeholder}
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                        onFocus={() => {
                            setIsFocused(true);
                            onFocus?.();
                        }}
                        onBlur={() => {
                            setTimeout(() => setIsFocused(false), 150);
                            onBlur?.();
                        }}
                        onKeyDown={(e) => {
                            if (e.key === "Enter") {
                                doSearch(query);
                            }
                        }}
                        className="w-full h-10 px-4 pr-10 rounded-full border border-kb-line bg-white shadow-sm transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-primary-500"
                    />

                    <button
                        type="button"
                        aria-label="Search"
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => doSearch(query)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer p-1 text-kb-ink/70 hover:text-primary-600"
                    >
                        <svg
                            width="18"
                            height="18"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                        >
                            <circle cx="11" cy="11" r="7" />
                            <line x1="21" y1="21" x2="16.65" y2="16.65" />
                        </svg>
                    </button>

                    {isFocused && (
                        <div className="absolute left-0 right-0 top-full mt-2 bg-white border border-kb-line rounded-2xl shadow-xl p-4 space-y-3 z-40">
                            {history.length > 0 && !query && (
                                <>
                                    <p className="text-xs font-semibold text-kb-muted px-1">
                                        Recent Search
                                    </p>
                                    <ul className="space-y-0.5">
                                        {history.map((item) => (
                                            <li
                                                key={item}
                                                onMouseDown={() => handleSelect(item)}
                                                className="px-3 py-2 rounded-lg text-sm text-kb-ink hover:bg-kb-paper-alt cursor-pointer"
                                            >
                                                {item}
                                            </li>
                                        ))}
                                    </ul>
                                </>
                            )}

                            {query && (
                                <p className="text-sm text-kb-muted px-1">
                                    Tekan Enter untuk mencari “{query}”
                                </p>
                            )}

                            {!query && history.length === 0 && (
                                <p className="text-sm text-kb-muted px-1">
                                    Ketik untuk mencari novel
                                </p>
                            )}
                        </div>
                    )}
                </div>
            </>
        );
    }
);

export default SearchBar;
