"use client";

import { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { signOut, useSession } from "next-auth/react";
import { Search } from "lucide-react";
import { locationOptions } from "@/lib/mock";
import { cn, DATE_RANGE_LABELS, ROLE_LABELS } from "@/lib/utils";
import { useUIStore } from "@/lib/store/ui-store";
import type { UserRole } from "@/lib/types";

export default function Topbar() {
  const pathname = usePathname();
  const [isHiddenOnScrollDown, setIsHiddenOnScrollDown] = useState(false);
  const lastScrollY = useRef(0);
  const { data: session } = useSession();

  const role = useUIStore((state) => state.role);
  const dateRange = useUIStore((state) => state.dateRange);
  const locationId = useUIStore((state) => state.locationId);
  const search = useUIStore((state) => state.search);

  const setRole = useUIStore((state) => state.setRole);
  const setDateRange = useUIStore((state) => state.setDateRange);
  const setLocationId = useUIStore((state) => state.setLocationId);
  const setSearch = useUIStore((state) => state.setSearch);
  const sessionRole = session?.user?.role as UserRole | undefined;

  useEffect(() => {
    if (!sessionRole || role === sessionRole) {
      return;
    }
    setRole(sessionRole);
  }, [role, sessionRole, setRole]);

  useEffect(() => {
    const onScroll = () => {
      const currentY = window.scrollY;

      if (currentY < 16) {
        setIsHiddenOnScrollDown(false);
        lastScrollY.current = currentY;
        return;
      }

      const scrollingDown = currentY > lastScrollY.current + 8;
      const scrollingUp = currentY < lastScrollY.current - 8;

      if (scrollingDown) {
        setIsHiddenOnScrollDown(true);
      } else if (scrollingUp) {
        setIsHiddenOnScrollDown(false);
      }

      lastScrollY.current = currentY;
    };

    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const selectedRole = sessionRole ?? role;

  if (pathname.startsWith("/departments/projects") || pathname.startsWith("/settings") || pathname.startsWith("/dashboard/print")) {
    return null;
  }

  return (
    <header
      className={cn(
        "sticky top-0 z-20 border-b border-benell-stroke bg-benell-surface/95 px-4 py-3 backdrop-blur transition-transform duration-200 will-change-transform",
        isHiddenOnScrollDown ? "-translate-y-full lg:translate-y-0" : "translate-y-0"
      )}
    >
      <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-[minmax(0,180px)_minmax(0,180px)_minmax(220px,1fr)_auto_auto]">
        <label className="sr-only" htmlFor="date-range-select">
          Rango de fecha
        </label>
        <select
          id="date-range-select"
          className="min-w-0 rounded-xl border border-benell-stroke bg-white px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
          value={dateRange}
          onChange={(event) => setDateRange(event.target.value as typeof dateRange)}
        >
          {Object.entries(DATE_RANGE_LABELS).map(([value, label]) => (
            <option key={value} value={value}>
              {label}
            </option>
          ))}
        </select>

        <label className="sr-only" htmlFor="location-select">
          Sucursal
        </label>
        <select
          id="location-select"
          className="min-w-0 rounded-xl border border-benell-stroke bg-white px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
          value={locationId}
          onChange={(event) => setLocationId(event.target.value)}
        >
          {locationOptions.map((location) => (
            <option key={location.id} value={location.id}>
              {location.name}
            </option>
          ))}
        </select>

        <label className="group relative min-w-0 sm:col-span-2 xl:col-span-1" htmlFor="search-input">
          <span className="sr-only">Buscar</span>
          <Search className="pointer-events-none absolute left-3 top-2.5 size-4 text-benell-text-soft" aria-hidden />
          <input
            id="search-input"
            value={search}
            onChange={(event) => setSearch(event.target.value)}
            className="w-full min-w-0 rounded-xl border border-benell-stroke bg-white py-2 pl-10 pr-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
            placeholder="Buscar..."
          />
        </label>

        <label className="inline-flex items-center gap-2 text-sm font-semibold">
          Vista:
          <span
            className="min-w-0 rounded-xl border border-benell-stroke bg-white px-3 py-2 text-sm text-benell-text-soft"
            title="El rol se toma de la invitación y sesión autenticada."
          >
            {ROLE_LABELS[selectedRole]}
          </span>
        </label>

        <button
          type="button"
          onClick={() => signOut({ callbackUrl: "/login" })}
          className="inline-flex size-10 items-center justify-center justify-self-end rounded-full bg-benell-brown text-sm font-semibold text-white outline-none focus-visible:ring-2 focus-visible:ring-benell-brown focus-visible:ring-offset-2"
          aria-label="Cerrar sesión"
        >
          {session?.user?.name?.[0]?.toUpperCase() ?? "U"}
        </button>
      </div>
    </header>
  );
}
