import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import {
  BookOpen,
  CalendarDays,
  RadioTower,
  LogIn,
  Menu,
  Search,
  UserRound,
  X,
} from "lucide-react";
import { useState } from "react";
import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import { useSession } from "../store/session";
import { Button } from "../../shared/ui/Button";
import { DstuLogo } from "../../shared/ui/DstuLogo";
import { ThemeToggle } from "../../shared/ui/ThemeToggle";
import { PageTransition } from "../../shared/ui/PageTransition";
import { cn } from "../../shared/lib/cn";

const links = [
  { to: "/materials", label: "Материалы", icon: BookOpen },
  { to: "/events", label: "События", icon: CalendarDays },
  { to: "/media", label: "Медиаканалы", icon: RadioTower },
  { to: "/about", label: "Об университете" },
];

export function PublicLayout() {
  const [menuOpen, setMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const user = useSession((state) => state.user);
  const location = useLocation();
  const navigate = useNavigate();
  const reduceMotion = useReducedMotion();

  return (
    <div className="min-h-screen bg-paper">
      <header className="sticky top-0 z-40 border-b border-dstu-menu-line bg-dstu-menu text-white shadow-sm">
        <div className="page-shell flex h-18 items-center gap-5">
          <Link className="flex shrink-0 items-center gap-3" to="/" viewTransition>
            <DstuLogo className="size-10" />
            <span>
              <span className="block font-serif text-lg leading-none">ДГТУ МЕДИА</span>
              <span className="mt-1 hidden text-xs font-bold uppercase tracking-[0.12em] text-white/55 sm:block">
                Университетское медиа
              </span>
            </span>
          </Link>

          <nav className="ml-8 hidden items-center gap-7 lg:flex" aria-label="Основная навигация">
            {links.map(({ to, label }) => (
              <NavLink
                key={to}
                to={to}
                viewTransition
                className={({ isActive }) =>
                  cn(
                    "text-sm font-semibold transition hover:text-dstu-menu-accent",
                    isActive ? "text-dstu-menu-accent" : "text-white/75",
                  )
                }
              >
                {label}
              </NavLink>
            ))}
          </nav>

          <div className="ml-auto flex items-center gap-2">
            <ThemeToggle className="text-white/75 hover:bg-white/10 hover:text-white" />
            <button
              className="grid size-10 place-items-center rounded-md text-white/75 transition hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-dstu-menu-accent"
              onClick={() => setSearchOpen((value) => !value)}
              aria-label="Открыть поиск"
            >
              <Search className="size-5" />
            </button>
            {user ? (
              <Button
                className="hidden border-white/25 bg-white/10 text-white hover:border-dstu-menu-accent hover:text-dstu-menu-accent sm:inline-flex"
                variant="secondary"
                icon={<UserRound className="size-4" />}
                onClick={() => navigate("/cabinet")}
              >
                Кабинет
              </Button>
            ) : (
              <Button
                className="hidden border-white/25 bg-white/10 text-white hover:border-dstu-menu-accent hover:text-dstu-menu-accent sm:inline-flex"
                variant="secondary"
                icon={<LogIn className="size-4" />}
                onClick={() => navigate("/login", { state: { from: location.pathname } })}
              >
                Войти
              </Button>
            )}
            <button
              className="grid size-10 place-items-center rounded-md text-white/80 hover:bg-white/10 hover:text-white lg:hidden"
              onClick={() => setMenuOpen(true)}
              aria-label="Открыть меню"
            >
              <Menu className="size-5" />
            </button>
          </div>
        </div>

        <AnimatePresence>
          {searchOpen && (
            <motion.form
              initial={reduceMotion ? false : { opacity: 0, y: -8 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -8 }}
              onSubmit={(event) => {
                event.preventDefault();
                const data = new FormData(event.currentTarget);
                navigate(`/materials?q=${encodeURIComponent(String(data.get("q") ?? ""))}`);
                setSearchOpen(false);
              }}
              className="border-t border-line bg-surface"
            >
              <div className="page-shell flex gap-3 py-4">
                <input
                  autoFocus
                  name="q"
                  placeholder="Что вы хотите найти?"
                  className="min-w-0 flex-1 rounded-md border border-line bg-white px-4 py-2.5 text-ink outline-none focus:border-primary focus:ring-2 focus:ring-primary/15 dark:bg-paper"
                />
                <Button type="submit">Найти</Button>
              </div>
            </motion.form>
          )}
        </AnimatePresence>
      </header>

      <AnimatePresence>
        {menuOpen && (
          <>
            <motion.button
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 z-40 bg-ink/30 lg:hidden"
              onClick={() => setMenuOpen(false)}
              aria-label="Закрыть меню"
            />
            <motion.aside
              initial={reduceMotion ? false : { x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ duration: 0.22 }}
              className="fixed inset-y-0 right-0 z-50 w-[min(88vw,24rem)] bg-dstu-menu p-6 text-white shadow-2xl lg:hidden"
            >
              <div className="flex items-center justify-between">
                <span className="font-serif text-2xl">Навигация</span>
                <button
                  className="grid size-10 place-items-center rounded-md hover:bg-white/10"
                  onClick={() => setMenuOpen(false)}
                  aria-label="Закрыть меню"
                >
                  <X className="size-5" />
                </button>
              </div>
              <nav className="mt-8 grid gap-2">
                {links.map(({ to, label, icon: Icon }) => (
                  <NavLink
                    key={to}
                    to={to}
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center gap-3 rounded-md px-3 py-3 font-semibold text-white/80 hover:bg-white/10 hover:text-white"
                  >
                    {Icon && <Icon className="size-5 text-dstu-menu-accent" />}
                    {label}
                  </NavLink>
                ))}
                <NavLink
                  to={user ? "/cabinet" : "/login"}
                  onClick={() => setMenuOpen(false)}
                  className="mt-4 rounded-md bg-dstu-menu-accent px-4 py-3 text-center font-semibold text-dstu-menu"
                >
                  {user ? "Личный кабинет" : "Войти"}
                </NavLink>
              </nav>
            </motion.aside>
          </>
        )}
      </AnimatePresence>

      <main className="overflow-x-clip">
        <AnimatePresence mode="wait" initial={false}>
          <PageTransition key={location.pathname} routeKey={location.pathname}>
            <Outlet />
          </PageTransition>
        </AnimatePresence>
      </main>

      <footer className="mt-20 bg-dstu-menu text-white">
        <div className="page-shell grid gap-10 py-14 md:grid-cols-3">
          <div>
            <p className="font-serif text-2xl">ДГТУ МЕДИА</p>
            <p className="mt-3 max-w-sm text-sm leading-6 text-white/65">
              Новости, исследования и события Донского государственного технического университета.
            </p>
          </div>
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-white/50">Разделы</p>
            <div className="mt-4 grid gap-2 text-sm">
              <Link to="/materials">Материалы</Link>
              <Link to="/events">События</Link>
              <Link to="/media">Медиаканалы</Link>
              <Link to="/about">Об университете</Link>
            </div>
          </div>
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-white/50">Контакты</p>
            <p className="mt-4 text-sm leading-6 text-white/75">
              пл. Гагарина, 1, Ростов-на-Дону
              <br />
              media@dstu.ru
            </p>
          </div>
        </div>
        <div className="border-t border-white/10 px-4 py-5 text-center text-xs text-white/45">
          © 2026 ДГТУ. Учебный проект.
        </div>
      </footer>
    </div>
  );
}
