import { Link, useParams } from "react-router-dom";
import { Settings, LayoutDashboard } from "lucide-react";
import clsx from "clsx";

import { useServers } from "@/hooks/useServers";
import { StatusLed } from "@/components/ui/StatusLed";

export function Sidebar() {
  const { data: servers, isLoading } = useServers();
  const { serverId } = useParams();
  const activeId = serverId ? parseInt(serverId) : null;

  return (
    <nav className="w-64 h-screen bg-surface-base border-r border-surface-raised flex flex-col" data-testid="sidebar">
      <div className="px-6 py-5 border-b border-surface-raised">
        <h1 className="text-text-primary font-bold text-lg tracking-tight">
          <span className="text-accent">Languard</span>
          <span className="text-text-secondary font-normal text-sm ml-2">
            Server Manager
          </span>
        </h1>
      </div>

      <div className="px-3 py-4 border-b border-surface-raised">
        <Link
          to="/"
          className="flex items-center gap-2 px-3 py-2 rounded-lg text-text-secondary
                     hover:text-text-primary hover:bg-surface-overlay transition-colors"
        >
          <LayoutDashboard size={16} />
          <span className="text-sm">Dashboard</span>
        </Link>
      </div>

      <div className="flex-1 overflow-y-auto px-3 py-3">
        <p className="text-text-muted text-xs uppercase tracking-widest px-3 mb-2">
          Servers
        </p>

        {isLoading && (
          <div className="text-text-muted text-sm px-3">Loading...</div>
        )}

        {servers?.map((server) => (
          <Link
            key={server.id}
            to={`/servers/${server.id}`}
            className={clsx(
              "flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors mb-1",
              activeId === server.id
                ? "bg-surface-overlay text-text-primary shadow-neu-recessed"
                : "text-text-secondary hover:text-text-primary hover:bg-surface-overlay",
            )}
          >
            <StatusLed status={server.status} size="sm" />
            <span className="text-sm font-medium truncate flex-1">{server.name}</span>
            <span className="text-xs text-text-muted uppercase">{server.game_type}</span>
          </Link>
        ))}
      </div>

      <div className="px-3 py-4 border-t border-surface-raised">
        <Link
          to="/settings"
          className="flex items-center gap-2 px-3 py-2 rounded-lg text-text-secondary
                     hover:text-text-primary hover:bg-surface-overlay transition-colors"
        >
          <Settings size={16} />
          <span className="text-sm">Settings</span>
        </Link>
      </div>
    </nav>
  );
}