import { Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState, type ReactNode, type FormEvent } from "react";
import { listCategories } from "@/lib/games.functions";
import { useSite } from "./site-context";

type ShellProps = {
  children: ReactNode;
  search?: string;
  onSearchChange?: (v: string) => void;
  onSearchSubmit?: () => void;
};

export function SiteShell({ children, search, onSearchChange, onSearchSubmit }: ShellProps) {
  const site = useSite();
  const [menuOpen, setMenuOpen] = useState(false);
  const fetchCats = useServerFn(listCategories);
  const { data: categories = [] } = useQuery({
    queryKey: ["categories"],
    queryFn: () => fetchCats(),
    staleTime: 60_000,
  });

  function onSearch(e: FormEvent) {
    e.preventDefault();
    onSearchSubmit?.();
  }

  return (
    <div className="min-h-screen bg-bg text-text flex flex-col">
      <header className="sticky top-0 z-50 border-b border-white/8 bg-bg/90 backdrop-blur-xl">
        <div className="max-w-7xl mx-auto px-4 py-3 flex items-center gap-3">
          <button type="button" className="md:hidden p-2 rounded-lg border border-white/10" onClick={() => setMenuOpen((v) => !v)} aria-label="Меню">
            <span className="block w-5 h-0.5 bg-white mb-1" />
            <span className="block w-5 h-0.5 bg-white mb-1" />
            <span className="block w-5 h-0.5 bg-white" />
          </button>

          <Link to="/" className="font-display text-xl sm:text-2xl text-white shrink-0">
            {site.logo_primary}<span className="text-accent">{site.logo_accent}</span>
          </Link>

          <form onSubmit={onSearch} className="flex-1 max-w-xl ml-auto flex gap-2">
            <input
              type="search"
              value={search ?? ""}
              onChange={(e) => onSearchChange?.(e.target.value)}
              placeholder="Поиск игр..."
              className="w-full rounded-xl bg-surface border border-white/10 py-2.5 px-4 text-sm focus:outline-none focus:border-accent/50"
            />
            <button type="submit" className="hidden sm:block px-4 rounded-xl bg-accent text-white text-xs font-bold uppercase">Найти</button>
          </form>
        </div>

        {menuOpen && (
          <div className="md:hidden border-t border-white/8 px-4 py-3 flex flex-col gap-2">
            <Link to="/" onClick={() => setMenuOpen(false)}>Главная</Link>
            <Link to="/categories" onClick={() => setMenuOpen(false)}>Категории</Link>
          </div>
        )}

        <div className="max-w-7xl mx-auto px-4 pb-3">
          <div className="flex gap-2 overflow-x-auto no-scrollbar">
            <Link
              to="/"
              search={{ sort: "new" }}
              activeOptions={{ exact: true }}
              activeProps={{ className: "bg-accent text-white border-accent" }}
              className="px-4 py-1.5 rounded-full bg-surface border border-white/10 text-xs font-bold uppercase whitespace-nowrap"
            >
              Все
            </Link>
            {categories.map((c) => (
              <Link
                key={c.id}
                to="/"
                search={{ category: c.slug }}
                activeProps={{ className: "bg-accent text-white border-accent" }}
                className="px-4 py-1.5 rounded-full bg-surface border border-white/10 text-xs font-bold uppercase whitespace-nowrap hover:border-accent/40"
              >
                {c.name}
              </Link>
            ))}
          </div>
        </div>
      </header>

      <main className="flex-1 max-w-7xl mx-auto w-full px-4 py-6">{children}</main>

      <footer className="border-t border-white/8 bg-surface/40 mt-auto">
        <div className="max-w-7xl mx-auto px-4 py-6 flex flex-wrap justify-between gap-4 items-center text-xs text-text-muted">
          <p className="font-display text-white">{site.logo_primary}<span className="text-accent">{site.logo_accent}</span> · {site.gameCount} игр</p>
          <Link to="/admin" className="hover:text-white uppercase tracking-widest font-bold">Админ</Link>
        </div>
      </footer>

      <nav className="sm:hidden fixed bottom-0 inset-x-0 z-40 border-t border-white/10 bg-bg/95 backdrop-blur-lg">
        <div className="grid grid-cols-2 text-center text-[10px] font-bold uppercase">
          <Link to="/" className="py-3">Игры</Link>
          <Link to="/categories" className="py-3">Разделы</Link>
        </div>
      </nav>
      <div className="h-12 sm:hidden" />
    </div>
  );
}

export function GameCard({
  slug,
  title,
  thumb,
  category,
  featured,
}: {
  slug: string;
  title: string;
  thumb: string;
  category?: { slug: string; name: string } | null;
  featured?: boolean;
}) {
  return (
    <Link to="/game/$slug" params={{ slug }} className="group block">
      <div className="relative aspect-[3/4] rounded-2xl overflow-hidden bg-surface border border-white/8 hover:border-accent/40 transition-colors">
        <img src={thumb} alt={title} loading="lazy" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-transparent to-transparent" />
        {featured && <span className="absolute top-2 left-2 px-2 py-0.5 rounded-md bg-accent text-[10px] font-black uppercase">Hot</span>}
        <div className="absolute bottom-0 p-3">
          <h3 className="text-sm font-bold text-white line-clamp-2">{title}</h3>
          {category && <p className="text-[10px] text-neon uppercase mt-1">{category.name}</p>}
        </div>
      </div>
    </Link>
  );
}
