import { NavLink, Link, Outlet, useMatch } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import {
  FiHome,
  FiMessageCircle,
  FiUsers,
  FiUser,
  FiBookmark,
  FiLogOut,
  FiArrowLeft,
} from "react-icons/fi";
import { useAuth } from "@/hooks/useAuth";
import { useApiSocialChatsList } from "@/api/generated/private/chat/chat";
import Avatar from "@/components/ui/Avatar";

interface NavItem {
  to: string;
  icon: React.ReactNode;
  labelKey: string;
}

function buildItems(username?: string): NavItem[] {
  return [
    { to: "/social/feed",   icon: <FiHome size={22} />,          labelKey: "nav.feed" },
    { to: "/social/chats",  icon: <FiMessageCircle size={22} />, labelKey: "nav.chats" },
    { to: "/social/hubs",   icon: <FiUsers size={22} />,         labelKey: "nav.hubs" },
    { to: "/social/saved",  icon: <FiBookmark size={22} />,      labelKey: "nav.saved" },
    {
      to: username ? `/social/profile/${username}` : "/social/feed",
      icon: <FiUser size={22} />,
      labelKey: "nav.profile",
    },
  ];
}

// Height of the mobile bottom tab bar (keep in sync with the nav below)
const BOTTOM_NAV_H = "3.5rem";

export default function SocialLayout() {
  const { t } = useTranslation("social");
  const { user } = useAuth();
  const items = buildItems(user?.username);
  const isChat = !!useMatch("/social/chats/*");

  const { data: chatsData } = useApiSocialChatsList();
  const totalUnread = useMemo(
    () => (chatsData?.results ?? []).reduce((s, c) => s + (c.unread_count ?? 0), 0),
    [chatsData],
  );

  return (
    /*
     * Full-height flex column:
     *   [mobile top bar — shrinks to content]
     *   [content row     — flex-1, fills the rest]
     *   [bottom spacer   — same height as the fixed bottom nav, mobile only]
     *
     * This ensures the middle row is always exactly the right height so
     * nothing is hidden behind the fixed bottom nav.
     */
    <div className="flex flex-col" style={{ height: "100svh", paddingTop: "var(--top-banner-h, 0px)" }}>

      {/* ── Mobile top bar ── */}
      <div
        className="md:hidden flex-shrink-0 relative flex items-center px-4 py-2.5 border-b border-brand-lines/15"
        style={{
          background: "color-mix(in hsl, var(--c-background-light), transparent 15%)",
          backdropFilter: "blur(12px)",
          zIndex: 40,
        }}
      >
        <Link
          to="/"
          className="flex items-center gap-1.5 text-brand-text/60 hover:text-brand-text transition-colors text-sm font-medium"
        >
          <FiArrowLeft size={15} />
          vontor.cz
        </Link>
        {/* Absolutely centered title so it's always exactly in the middle */}
        <span className="absolute left-1/2 -translate-x-1/2 text-sm font-bold text-rainbow pointer-events-none">
          Social
        </span>
      </div>

      {/* ── Content row ── */}
      <div className={[
        "flex-1 overflow-hidden",
        "mx-auto flex w-full max-w-[1280px] gap-6 sm:px-6",
      ].join(" ")}>

        {/* Left sidebar — desktop only */}
        <aside className="sticky top-0 hidden h-full w-[72px] flex-shrink-0 flex-col items-center justify-between py-6 md:flex md:w-[220px] md:items-start">
          <div className="flex w-full flex-col gap-1.5">
            <div className="mb-1 px-2 text-xl font-bold text-rainbow hidden md:block">
              vontor.cz
            </div>
            <Link
              to="/"
              className="hidden md:flex items-center gap-2 px-2 mb-3 text-xs text-brand-text/50 hover:text-brand-text/80 transition-colors"
            >
              <FiArrowLeft size={12} /> Back to site
            </Link>
            {items.map((it) => (
              <NavLink
                key={it.to}
                to={it.to}
                className={({ isActive }) =>
                  [
                    "flex items-center gap-3 rounded-2xl px-3 py-2.5 transition-colors",
                    "text-brand-text/80 hover:bg-brand-lines/10 hover:text-brand-text",
                    isActive ? "bg-brand-lines/10 text-brand-accent font-semibold" : "",
                  ].join(" ")
                }
              >
                {it.icon}
                <span className="hidden md:inline">{t(it.labelKey)}</span>
                {it.to === "/social/chats" && totalUnread > 0 && (
                  <span className="ml-auto rounded-full bg-brand-accent px-1.5 py-0.5 text-[10px] font-bold leading-none text-brand-bg">
                    {totalUnread > 99 ? "99+" : totalUnread}
                  </span>
                )}
              </NavLink>
            ))}
          </div>

          <div className="flex w-full items-center gap-3 rounded-2xl px-2 py-2 hover:bg-brand-lines/10">
            <Avatar name={user?.username ?? user?.email ?? "?"} src={(user as any)?.avatar ?? null} size={36} />
            <div className="hidden min-w-0 md:block">
              <div className="truncate text-sm font-semibold text-brand-text">
                {user?.username ?? "—"}
              </div>
              <NavLink
                to="/social/logout"
                className="flex items-center gap-1 text-xs text-brand-text/60 hover:text-brand-accent"
              >
                <FiLogOut size={12} /> {t("nav.logout")}
              </NavLink>
            </div>
          </div>
        </aside>

        {/* Main column */}
        <main
          className={
            isChat
              ? "w-full md:flex-1 overflow-hidden h-full"
              : "w-full md:flex-1 md:border-x border-brand-lines/15 md:max-w-[640px] overflow-y-auto"
          }
        >
          <Outlet />
        </main>

        {/* Right rail — desktop only, not in chat */}
        {!isChat && (
          <aside className="sticky top-0 hidden h-full w-[300px] shrink-0 py-6 lg:block overflow-y-auto">
            <div className="glass rounded-2xl p-4 text-sm text-brand-text/70">
              <div className="font-semibold text-brand-text mb-2">
                {t("nav.hubs")}
              </div>
              <p className="text-xs">—</p>
            </div>
          </aside>
        )}
      </div>

      {/* ── Bottom spacer — pushes content above the fixed nav on mobile ── */}
      <div
        className="md:hidden flex-shrink-0"
        style={{ height: BOTTOM_NAV_H }}
      />

      {/* ── Fixed bottom tab bar — mobile only ── */}
      <nav
        className="flex md:hidden"
        style={{
          position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 50,
          height: BOTTOM_NAV_H,
          background: "color-mix(in hsl, var(--c-background-light), transparent 8%)",
          backdropFilter: "blur(20px)",
          WebkitBackdropFilter: "blur(20px)",
          borderTop: "1px solid color-mix(in hsl, var(--c-lines), transparent 65%)",
        }}
      >
        {items.map((it) => (
          <NavLink
            key={it.to}
            to={it.to}
            style={{
              flex: 1, display: "flex", flexDirection: "column" as const,
              alignItems: "center", justifyContent: "center",
              padding: "0.5rem 0", gap: "0.2rem",
              textDecoration: "none", position: "relative",
            }}
            className={({ isActive }) => isActive ? "bottom-nav-active" : "bottom-nav-item"}
          >
            {it.icon}
            <span style={{ fontSize: "0.62rem", fontWeight: 500 }}>{t(it.labelKey)}</span>
            {it.to === "/social/chats" && totalUnread > 0 && (
              <span style={{
                position: "absolute", top: "0.35rem", right: "calc(50% - 1.4rem)",
                background: "var(--c-other)", color: "#031D44",
                fontSize: "0.6rem", fontWeight: 700,
                padding: "0.1em 0.4em", borderRadius: "9999px", lineHeight: 1.4,
              }}>
                {totalUnread > 99 ? "99+" : totalUnread}
              </span>
            )}
          </NavLink>
        ))}
      </nav>

      <style>{`
        .bottom-nav-item  { color: color-mix(in hsl, var(--c-text), transparent 45%); transition: color 0.15s; }
        .bottom-nav-active { color: var(--c-other); }
        .bottom-nav-item:hover { color: var(--c-text); }
      `}</style>
    </div>
  );
}
