import { useAuth } from "@/_core/hooks/useAuth";
import { useMode } from "@/contexts/ModeContext";
import { trpc } from "@/lib/trpc";
import { useEffect, useRef, useState } from "react";
import { Link, useLocation } from "wouter";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "./ui/dropdown-menu";

export default function Topbar() {
  const [, navigate] = useLocation();
  const { user, logout } = useAuth();
  const { mode, setMode } = useMode();

  const [searchQuery, setSearchQuery] = useState("");
  const [debouncedQuery, setDebouncedQuery] = useState("");
  const [open, setOpen] = useState(false);

  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handle = setTimeout(
      () => setDebouncedQuery(searchQuery.trim()),
      300
    );

    return () => clearTimeout(handle);
  }, [searchQuery]);

  const { data } = trpc.podcast.buscar.useQuery(
    { query: debouncedQuery },
    { enabled: debouncedQuery.length > 1 }
  );

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        setOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);

    return () =>
      document.removeEventListener(
        "mousedown",
        handleClickOutside
      );
  }, []);

  const hasResults =
    !!data &&
    (
      data.episodios.length > 0 ||
      data.apresentadores.length > 0 ||
      data.programas.length > 0
    );

  const goTo = (path: string) => {
    setOpen(false);
    setSearchQuery("");
    navigate(path);
  };

  return (
    <div
      className="
        fixed
        top-0
        left-0
        lg:left-64
        right-0
        h-16
        flex
        items-center
        justify-between
        px-4
        lg:px-8
        gap-4
        z-40
        bg-sof-topbar
        border-b
        border-white/5
      "
    >
      {/* Busca — só a partir do desktop; no mobile já existe "Buscar" no rodapé */}
      <div
        ref={containerRef}
        className="hidden sm:block flex-1 min-w-0 max-w-xl relative"
      >
        <div className="relative">
          <span
            className="
              absolute
              left-4
              top-1/2
              -translate-y-1/2
              text-white/40
              pointer-events-none
            "
          >
            🔍
          </span>

          <Input
            type="text"
            placeholder="Buscar episódios, apresentadores e séries"
            value={searchQuery}
            onChange={e => {
              setSearchQuery(e.target.value);
              setOpen(true);
            }}
            onFocus={() => setOpen(true)}
            className="
              h-11
              rounded-full
              border
              border-white/10
              bg-white/5
              backdrop-blur-xl
              pl-12
              pr-4
              text-sm
              text-white
              placeholder:text-white/35
              transition-all
              focus:border-sof-gold
              focus:ring-1
              focus:ring-sof-gold
            "
          />
        </div>

        {open && debouncedQuery.length > 1 && (
          <div
            className="
              absolute
              top-full
              mt-3
              w-full
              rounded-2xl
              border
              border-white/10
              bg-[#111]
              shadow-2xl
              overflow-hidden
              max-h-[420px]
              overflow-y-auto
              backdrop-blur-2xl
              z-50
            "
          >
            {!hasResults && (
              <p className="p-5 text-sm text-white/45">
                Nenhum resultado encontrado.
              </p>
            )}

            {!!data?.episodios.length && (
              <div className="py-2">
                <p
                  className="
                    px-5
                    py-2
                    text-[11px]
                    uppercase
                    tracking-[0.25em]
                    text-white/35
                    font-semibold
                  "
                >
                  Episódios
                </p>

                {data.episodios.map(ep => (
                  <button
                    key={`ep-${ep.id}`}
                    onClick={() =>
                      goTo(`/episodio/${ep.id}`)
                    }
                    className="
                      w-full
                      px-5
                      py-3
                      text-left
                      text-sm
                      text-white
                      hover:bg-white/6
                      transition-colors
                      truncate
                    "
                  >
                    {ep.titulo}
                  </button>
                ))}
              </div>
            )}

            {!!data?.apresentadores.length && (
              <div className="border-t border-white/5 py-2">
                <p
                  className="
                    px-5
                    py-2
                    text-[11px]
                    uppercase
                    tracking-[0.25em]
                    text-white/35
                    font-semibold
                  "
                >
                  Apresentadores
                </p>

                {data.apresentadores.map(ap => (
                  <button
                    key={`ap-${ap.id}`}
                    onClick={() =>
                      goTo(`/apresentador/${ap.id}`)
                    }
                    className="
                      w-full
                      px-5
                      py-3
                      text-left
                      text-sm
                      text-white
                      hover:bg-white/6
                      transition-colors
                      truncate
                    "
                  >
                    {ap.nome}
                  </button>
                ))}
              </div>
            )}

            {!!data?.programas.length && (
              <div className="border-t border-white/5 py-2">
                <p
                  className="
                    px-5
                    py-2
                    text-[11px]
                    uppercase
                    tracking-[0.25em]
                    text-white/35
                    font-semibold
                  "
                >
                  Séries
                </p>

                {data.programas.map(prog => (
                  <button
                    key={`prog-${prog.id}`}
                    onClick={() =>
                      goTo(`/serie/${prog.id}`)
                    }
                    className="
                      w-full
                      px-5
                      py-3
                      text-left
                      text-sm
                      text-white
                      hover:bg-white/6
                      transition-colors
                      truncate
                    "
                  >
                    {prog.titulo}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Ações */}
      <div className="flex items-center gap-3">
        <div
          className="
            flex
            items-center
            rounded-full
            bg-white/6
            p-1
            gap-1
            flex-shrink-0
          "
          role="tablist"
          aria-label="Alternar entre Podcast e Música"
        >
          <button
            role="tab"
            aria-selected={mode === "podcast"}
            onClick={() => {
              setMode("podcast");
              navigate("/");
            }}
            className={`
              flex items-center gap-1.5 rounded-full px-2 sm:px-3 py-1 sm:py-1.5 text-[10px] sm:text-[11px] font-bold uppercase
              tracking-wide sm:tracking-widest transition-colors whitespace-nowrap
              ${mode === "podcast" ? "bg-sof-gold text-sof-borgonha" : "text-white/60 hover:text-white"}
            `}
          >
            {mode === "podcast" && (
              <span className="hidden sm:inline-block w-2 h-2 rounded-full bg-sof-borgonha animate-pulse" />
            )}
            Podcast
          </button>
          <button
            role="tab"
            aria-selected={mode === "musica"}
            onClick={() => {
              setMode("musica");
              navigate("/");
            }}
            className={`
              flex items-center gap-1.5 rounded-full px-2 sm:px-3 py-1 sm:py-1.5 text-[10px] sm:text-[11px] font-bold uppercase
              tracking-wide sm:tracking-widest transition-colors whitespace-nowrap
              ${mode === "musica" ? "bg-sof-gold text-sof-borgonha" : "text-white/60 hover:text-white"}
            `}
          >
            {mode === "musica" && (
              <span className="hidden sm:inline-block w-2 h-2 rounded-full bg-sof-borgonha animate-pulse" />
            )}
            Música
          </button>
        </div>

        <a
          href="https://filadelfia.onfide.com.br/"
          target="_blank"
          rel="noopener noreferrer"
          className="
            hidden
            md:block
            text-sm
            text-white/65
            hover:text-sof-gold
            transition-colors
          "
        >
          Comunidade
        </a>

        {user ? (
          <div className="flex items-center gap-3">
            <div
              className="
                hidden
                sm:flex
                w-9
                h-9
                rounded-full
                bg-sof-gold
                items-center
                justify-center
                text-sof-borgonha
                font-bold
                text-sm
              "
            >
              {user.name?.charAt(0).toUpperCase()}
            </div>

            <Button
              size="sm"
              variant="outline"
              onClick={() => logout()}
              className="
                rounded-full
                border-white/10
                bg-white/5
                text-white
                hover:bg-white/10
              "
            >
              Sair
            </Button>
          </div>
        ) : (
          <>
            {/* Desktop — botões normais */}
            <div className="hidden sm:flex items-center gap-2">
              <Link href="/entrar">
                <Button
                  size="sm"
                  variant="outline"
                  className="
                    rounded-full
                    border-white/10
                    bg-white/5
                    text-white
                    hover:bg-white/10
                  "
                >
                  Entrar
                </Button>
              </Link>

              <Link href="/cadastro">
                <Button
                  size="sm"
                  className="
                    rounded-full
                    bg-sof-gold
                    text-sof-borgonha
                    hover:bg-sof-gold-light
                  "
                >
                  Cadastrar
                </Button>
              </Link>
            </div>

            {/* Mobile — menu hambúrguer com as mesmas 2 opções */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button
                  type="button"
                  aria-label="Menu"
                  className="sm:hidden w-9 h-9 flex items-center justify-center rounded-full text-white/70 hover:text-white hover:bg-white/6 transition-colors flex-shrink-0"
                >
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5" />
                  </svg>
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="end"
                className="bg-sof-borgonha-light border-sof-border text-sof-text sm:hidden"
              >
                <DropdownMenuItem asChild className="cursor-pointer focus:bg-sof-surface focus:text-sof-gold">
                  <Link href="/entrar">Entrar</Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild className="cursor-pointer focus:bg-sof-surface focus:text-sof-gold">
                  <Link href="/cadastro">Cadastrar</Link>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </>
        )}
      </div>
    </div>
  );
}