import React, { useEffect, useState } from "react";
import { NavLink } from "react-router-dom";
import { Shell } from "./Shell";
import { Badge } from "../ui/Badge";
import { Button } from "../ui/Button";
import { useAuthStore } from "../../store/useAuthStore";
import { useAppStore } from "../../store/useAppStore";
import { connectSocket } from "../../socket/socket";
import { api } from "../../api/client";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars, faMoon, faRightFromBracket, faSun } from "@fortawesome/free-solid-svg-icons";
import { AlertToastStack } from "../ui/AlertToastStack";

export const AppLayout = ({ children }: { children: React.ReactNode }) => {
  const logout = useAuthStore((s) => s.logout);
  const qbit = useAppStore((s) => s.qbit);
  const setSnapshot = useAppStore((s) => s.setSnapshot);
  const [connected, setConnected] = useState(false);
  const [theme, setTheme] = useState<"light" | "dark">("light");
  const [menuOpen, setMenuOpen] = useState(false);

  const applyTheme = (next: "light" | "dark") => {
    document.documentElement.classList.toggle("dark", next === "dark");
    localStorage.setItem("theme", next);
    setTheme(next);
  };

  useEffect(() => {
    const stored = localStorage.getItem("theme");
    if (stored === "light" || stored === "dark") {
      applyTheme(stored);
    } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
      applyTheme("dark");
    }
    const socket = connectSocket();
    socket.on("connect", () => setConnected(true));
    socket.on("disconnect", () => setConnected(false));
    return () => {
      socket.disconnect();
    };
  }, []);

  useEffect(() => {
    let active = true;
    const fetchStatus = async () => {
      try {
        const response = await api.get("/api/status");
        if (active) {
          setSnapshot(response.data);
        }
      } catch (error) {
        if (active) {
          // Ignore transient network errors; socket will update when available.
        }
      }
    };
    fetchStatus();
    const interval = setInterval(fetchStatus, connected ? 15000 : 5000);
    return () => {
      active = false;
      clearInterval(interval);
    };
  }, [connected, setSnapshot]);

  return (
    <Shell>
      <header className="rounded-xl border border-slate-200 bg-white/80 px-4 py-3">
        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div>
            <div className="flex items-start justify-between gap-3">
              <div className="text-lg font-semibold text-slate-900">q-buffer</div>
              <button
                className={`inline-flex items-center justify-center rounded-md border border-slate-300 px-2 py-2 text-xs font-semibold text-slate-700 md:hidden transition-opacity ${menuOpen ? "pointer-events-none opacity-0" : "opacity-100"}`}
                onClick={() => setMenuOpen(true)}
                type="button"
                aria-label="Menü"
              >
                <FontAwesomeIcon icon={faBars} />
              </button>
            </div>
            <div className="text-xs text-slate-500">
              qBittorrent {qbit.version ?? "unknown"}
            </div>
            <div className="mt-2 flex flex-wrap items-center gap-2">
              <Badge variant={qbit.ok ? "success" : "danger"}>
                {qbit.ok ? "Qbit OK" : "Qbit Down"}
              </Badge>
              <Badge variant={connected ? "success" : "warn"}>
                {connected ? "Live" : "Offline"}
              </Badge>
            </div>
          </div>
          <div className="hidden md:flex md:flex-row md:items-center gap-3">
            <nav className="flex flex-wrap items-center gap-2 rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-600">
              <NavLink
                to="/buffer"
                className={({ isActive }) =>
                  `rounded-full px-3 py-1 ${
                    isActive ? "bg-slate-900 text-white" : "hover:bg-white"
                  }`
                }
              >
                Buffer
              </NavLink>
              <NavLink
                to="/timer"
                className={({ isActive }) =>
                  `rounded-full px-3 py-1 ${
                    isActive ? "bg-slate-900 text-white" : "hover:bg-white"
                  }`
                }
              >
                Timer
              </NavLink>
              <NavLink
                to="/watcher"
                className={({ isActive }) =>
                  `rounded-full px-3 py-1 ${
                    isActive ? "bg-slate-900 text-white" : "hover:bg-white"
                  }`
                }
              >
                Watcher
              </NavLink>
            </nav>
            <Button
              variant="outline"
              onClick={() => applyTheme(theme === "dark" ? "light" : "dark")}
              title={theme === "dark" ? "Light" : "Dark"}
            >
              <FontAwesomeIcon
                icon={theme === "dark" ? faSun : faMoon}
              />
            </Button>
            <Button variant="outline" onClick={logout} title="Logout">
              <FontAwesomeIcon icon={faRightFromBracket} />
            </Button>
          </div>
        </div>
      </header>
      <AlertToastStack />
      <div
        className={`fixed inset-0 z-50 md:hidden transition-opacity duration-500 ${menuOpen ? "opacity-100" : "pointer-events-none opacity-0"}`}
      >
        <div
          className="absolute inset-0 bg-slate-900/30"
          onClick={() => setMenuOpen(false)}
        />
        <div
          className={`absolute right-0 top-0 flex h-full w-64 flex-col gap-6 bg-white p-5 shadow-xl transition-transform duration-500 ease-out ${menuOpen ? "translate-x-0" : "translate-x-full"}`}
          onClick={(event) => event.stopPropagation()}
        >
          <div className="text-sm font-semibold text-slate-700">Menü</div>
          <nav className="flex flex-col gap-2 text-sm font-semibold text-slate-700">
            <NavLink
              to="/buffer"
              onClick={() => setMenuOpen(false)}
              className={({ isActive }) =>
                `rounded-lg border px-3 py-2 ${
                  isActive ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white"
                }`
              }
            >
              Buffer
            </NavLink>
            <NavLink
              to="/timer"
              onClick={() => setMenuOpen(false)}
              className={({ isActive }) =>
                `rounded-lg border px-3 py-2 ${
                  isActive ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white"
                }`
              }
            >
              Timer
            </NavLink>
            <NavLink
              to="/watcher"
              onClick={() => setMenuOpen(false)}
              className={({ isActive }) =>
                `rounded-lg border px-3 py-2 ${
                  isActive ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white"
                }`
              }
            >
              Watcher
            </NavLink>
          </nav>
          <div className="mt-auto flex items-center gap-3">
            <Button
              variant="outline"
              onClick={() => {
                applyTheme(theme === "dark" ? "light" : "dark");
                setMenuOpen(false);
              }}
              title={theme === "dark" ? "Light" : "Dark"}
              className="h-10 w-10 px-0"
            >
              <FontAwesomeIcon icon={theme === "dark" ? faSun : faMoon} />
            </Button>
            <Button
              variant="outline"
              onClick={() => {
                logout();
                setMenuOpen(false);
              }}
              title="Logout"
              className="h-10 w-10 px-0"
            >
              <FontAwesomeIcon icon={faRightFromBracket} />
            </Button>
          </div>
        </div>
      </div>
      {children}
    </Shell>
  );
};
