import { ReactNode, useState } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { commandsApi, Command } from "../api/client";
import {
  LayoutDashboard,
  Server,
  Settings,
  LogOut,
  Menu,
  X,
  Building2,
  MapPin,
  History,
  CheckCircle,
  XCircle,
  Clock,
  Loader2,
} from "lucide-react";
import { useAuth } from "../hooks/useAuth";
import { Button } from "./Button";

interface LayoutProps {
  children: ReactNode;
}

const navItems = [
  { path: "/", label: "Dashboard", icon: LayoutDashboard },
  { path: "/clients", label: "Clients", icon: Building2 },
  { path: "/sites", label: "Sites", icon: MapPin },
  { path: "/agents", label: "Agents", icon: Server },
  { path: "/settings", label: "Settings", icon: Settings },
];

const APP_VERSION = "0.2.0";
const SERVER_VERSION = "0.1.0";

function CommandStatusIcon({ status }: { status: Command["status"] }) {
  const config = {
    pending: { icon: Clock, color: "text-amber-500" },
    running: { icon: Loader2, color: "text-cyan-500 animate-spin" },
    completed: { icon: CheckCircle, color: "text-emerald-500" },
    failed: { icon: XCircle, color: "text-rose-500" },
  };
  const { icon: Icon, color } = config[status];
  return <Icon className={`h-3 w-3 ${color}`} />;
}

export function Layout({ children }: LayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout } = useAuth();

  const { data: commands = [] } = useQuery({
    queryKey: ["commands"],
    queryFn: () => commandsApi.list().then((res) => res.data),
    refetchInterval: 15000,
  });

  const recentCommands = commands.slice(0, 4);

  const handleLogout = () => {
    logout();
    navigate("/login");
  };

  return (
    <div className="min-h-screen bg-slate-950">
      {/* Subtle grid pattern background */}
      <div
        className="fixed inset-0 pointer-events-none"
        style={{
          backgroundImage: `
            linear-gradient(rgba(6, 182, 212, 0.03) 1px, transparent 1px),
            linear-gradient(90deg, rgba(6, 182, 212, 0.03) 1px, transparent 1px)
          `,
          backgroundSize: "50px 50px",
        }}
      />

      {/* Mobile header */}
      <div className="lg:hidden fixed top-0 left-0 right-0 z-50 flex items-center justify-between px-4 py-3 bg-slate-900/80 backdrop-blur-xl border-b border-cyan-500/20">
        <span className="font-bold text-lg tracking-wider bg-gradient-to-r from-cyan-400 to-blue-500 bg-clip-text text-transparent">
          GURUR<span className="text-cyan-400">MM</span>
        </span>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => setSidebarOpen(!sidebarOpen)}
          className="text-slate-400 hover:text-cyan-400 hover:bg-cyan-500/10 transition-all duration-300"
        >
          {sidebarOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </Button>
      </div>

      {/* Mobile menu overlay with blur */}
      <div
        className={`fixed inset-0 z-40 lg:hidden transition-all duration-300 ${
          sidebarOpen
            ? "opacity-100 pointer-events-auto"
            : "opacity-0 pointer-events-none"
        }`}
      >
        <div
          className="absolute inset-0 bg-slate-950/80 backdrop-blur-md"
          onClick={() => setSidebarOpen(false)}
        />
      </div>

      <div className="flex relative">
        {/* Sidebar - Mission Control Aesthetic */}
        <aside
          className={`fixed inset-y-0 left-0 z-50 w-60 transform transition-all duration-300 ease-out lg:translate-x-0 lg:static ${
            sidebarOpen ? "translate-x-0" : "-translate-x-full"
          }`}
        >
          {/* Glassmorphism sidebar container */}
          <div className="flex flex-col h-full bg-slate-900/60 backdrop-blur-xl border-r border-cyan-500/20 shadow-[inset_0_0_30px_rgba(6,182,212,0.05)]">
            {/* Cyan left border glow */}
            <div className="absolute left-0 top-0 bottom-0 w-[2px] bg-gradient-to-b from-transparent via-cyan-500/50 to-transparent" />

            {/* Logo section */}
            <div className="p-4 hidden lg:block">
              <div className="flex items-center gap-3">
                {/* Logo icon with glow */}
                <div className="relative">
                  <div className="absolute inset-0 bg-cyan-500/30 blur-lg rounded-lg" />
                  <div className="relative h-8 w-8 rounded-lg bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center shadow-lg shadow-cyan-500/20">
                    <LayoutDashboard className="h-4 w-4 text-white" />
                  </div>
                </div>
                {/* Logo text with gradient */}
                <div>
                  <h1 className="text-lg font-bold tracking-wider">
                    <span className="bg-gradient-to-r from-cyan-400 via-cyan-300 to-blue-400 bg-clip-text text-transparent">
                      GURU
                    </span>
                    <span className="text-slate-300">RMM</span>
                  </h1>
                  <p className="text-[10px] uppercase tracking-[0.2em] text-slate-500">
                    Mission Control
                  </p>
                </div>
              </div>
            </div>

            {/* Navigation */}
            <nav className="flex-1 px-2 space-y-0.5 mt-4 lg:mt-2 pt-16 lg:pt-0">
              {navItems.map((item) => {
                const isActive = location.pathname === item.path;
                return (
                  <Link
                    key={item.path}
                    to={item.path}
                    onClick={() => setSidebarOpen(false)}
                    className={`group relative flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-semibold uppercase tracking-wider transition-all duration-300 ${
                      isActive
                        ? "text-cyan-400"
                        : "text-slate-400 hover:text-slate-200"
                    }`}
                  >
                    {/* Active/Hover background glow */}
                    <div
                      className={`absolute inset-0 rounded-lg transition-all duration-300 ${
                        isActive
                          ? "bg-cyan-500/10 shadow-[inset_0_0_20px_rgba(6,182,212,0.1)]"
                          : "bg-transparent group-hover:bg-cyan-500/5"
                      }`}
                    />

                    {/* Active left border indicator */}
                    <div
                      className={`absolute left-0 top-2 bottom-2 w-[3px] rounded-full transition-all duration-300 ${
                        isActive
                          ? "bg-cyan-400 shadow-[0_0_10px_rgba(6,182,212,0.8)]"
                          : "bg-transparent"
                      }`}
                    />

                    {/* Icon with conditional glow */}
                    <div className="relative z-10">
                      <item.icon
                        className={`h-4 w-4 transition-all duration-300 ${
                          isActive
                            ? "text-cyan-400 drop-shadow-[0_0_8px_rgba(6,182,212,0.8)]"
                            : "text-slate-500 group-hover:text-slate-300"
                        }`}
                      />
                    </div>

                    {/* Label */}
                    <span className="relative z-10">{item.label}</span>

                    {/* Active indicator dot */}
                    {isActive && (
                      <div className="absolute right-4 h-1.5 w-1.5 rounded-full bg-cyan-400 shadow-[0_0_6px_rgba(6,182,212,0.8)]" />
                    )}
                  </Link>
                );
              })}
            </nav>

            {/* User profile section */}
            <div className="p-3 border-t border-cyan-500/10">
              <div className="flex items-center gap-2 mb-3 p-2 rounded-lg bg-slate-800/30">
                {/* Avatar with cyan ring glow */}
                <div className="relative">
                  {/* Glow ring */}
                  <div className="absolute -inset-1 bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full opacity-50 blur-sm" />
                  {/* Avatar */}
                  <div className="relative h-8 w-8 rounded-full bg-gradient-to-br from-slate-700 to-slate-800 ring-2 ring-cyan-500/50 flex items-center justify-center text-cyan-400 text-sm font-bold shadow-lg">
                    {user?.name?.[0] || user?.email?.[0] || "U"}
                  </div>
                  {/* Online indicator */}
                  <div className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full bg-emerald-500 ring-2 ring-slate-900 shadow-[0_0_8px_rgba(16,185,129,0.6)]" />
                </div>

                {/* User info */}
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-slate-200 truncate">
                    {user?.name || user?.email}
                  </p>
                  <p className="text-xs text-cyan-500/70 uppercase tracking-wider truncate">
                    {user?.role || "Operator"}
                  </p>
                </div>
              </div>

              {/* Sign out button */}
              <Button
                variant="ghost"
                className="w-full justify-start gap-2 px-3 py-2 text-xs font-semibold uppercase tracking-wider text-slate-400 hover:text-red-400 hover:bg-red-500/10 rounded-lg transition-all duration-300 group"
                onClick={handleLogout}
              >
                <LogOut className="h-4 w-4 transition-all duration-300 group-hover:text-red-400 group-hover:drop-shadow-[0_0_6px_rgba(239,68,68,0.6)]" />
                Sign Out
              </Button>

              {/* History log */}
              <div className="mt-2 pt-2 border-t border-slate-800/50">
                <Link
                  to="/history"
                  className="flex items-center gap-1.5 px-1 py-1 text-[10px] font-mono text-slate-500 hover:text-cyan-400 transition-colors"
                >
                  <History className="h-3 w-3" />
                  <span>History</span>
                </Link>

                <div className="mt-1 space-y-0.5">
                  {recentCommands.length === 0 ? (
                    <p className="text-[10px] text-slate-600 px-1">No recent activity</p>
                  ) : (
                    recentCommands.map((cmd: Command) => (
                      <Link
                        key={cmd.id}
                        to={`/history/${cmd.id}`}
                        className="flex items-center gap-1.5 px-1 py-0.5 rounded text-[10px] hover:bg-slate-800/50 transition-colors"
                        title={cmd.command_text}
                      >
                        <CommandStatusIcon status={cmd.status} />
                        <span className="text-slate-500 hover:text-slate-400 truncate flex-1 font-mono">
                          {cmd.command_text.length > 18
                            ? cmd.command_text.slice(0, 18) + "..."
                            : cmd.command_text}
                        </span>
                      </Link>
                    ))
                  )}
                </div>
              </div>

              {/* Version info */}
              <div className="mt-2 pt-2 border-t border-slate-800/50 text-[10px] font-mono text-slate-600 flex justify-between px-1">
                <span>UI v{APP_VERSION}</span>
                <span>API v{SERVER_VERSION}</span>
              </div>
            </div>
          </div>
        </aside>

        {/* Main content area */}
        <main className="flex-1 min-h-screen pt-16 lg:pt-0">
          <div className="p-4 lg:p-6 transition-all duration-300">
            {children}
          </div>
        </main>
      </div>
    </div>
  );
}
