import type { LucideIcon } from 'lucide-react';
import { NavLink } from 'react-router';
import { Bell, Building2, CircleDot, Compass, GitBranch, GitPullRequest, Plug } from 'lucide-react';
import { useServiceConnection } from '../../hooks/useServiceConnection';
import { GITEA_SECTIONS, giteaSectionPath, type GiteaSectionId } from './shared';
import { useGiteaNotifications, useGiteaRepos, useGiteaViewer } from './useGiteaData';

// Left panel of /gitea: who the token belongs to, then the sections.
//
// Sections are real links (cmd-click, back button, reload) with active state from react-router's NavLink —
// per docs/navigation-audit.md, the URL is the selection, not a channel.

const ICONS: Record<GiteaSectionId, LucideIcon> = {
  repositories: GitBranch,
  issues: CircleDot,
  pulls: GitPullRequest,
  notifications: Bell,
  explore: Compass,
  organizations: Building2,
  connection: Plug,
};

const ROW = 'group relative flex items-center gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors';

export const GiteaNav = () => {
  const { data: connectionState } = useServiceConnection('gitea');
  const configured = !!connectionState?.configured;
  // Both are gated on there being a connection at all: unconfigured, the sidecar 503s and every row would
  // be a failed request behind a form the owner has not filled in yet.
  const { data: viewer } = useGiteaViewer({ enabled: configured });
  const { data: repos } = useGiteaRepos({ enabled: configured });
  const { data: notifications } = useGiteaNotifications({ enabled: configured });

  return (
    <div className="flex h-full flex-col overflow-y-auto bg-muted/30">
      <div className="flex items-center gap-3 px-4 py-4">
        <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-success/15 text-success ring-1 ring-border">
          <GitBranch className="h-5 w-5" />
        </div>
        <div className="min-w-0">
          <div className="truncate text-sm font-semibold leading-tight">Gitea</div>
          <div className="truncate text-xs text-muted-foreground">
            {viewer ? `@${viewer.login}` : configured ? 'connecting…' : 'not connected'}
          </div>
        </div>
      </div>

      <nav className="flex flex-col gap-0.5 px-2 pb-3">
        {GITEA_SECTIONS.map(({ id, label }) => {
          const Icon = ICONS[id];
          return (
            <NavLink
              key={id}
              to={giteaSectionPath(id)}
              className={({ isActive }) =>
                `${ROW} ${
                  isActive
                    ? 'bg-primary/10 font-medium text-primary'
                    : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                }`
              }
            >
              {({ isActive }) => (
                <>
                  {isActive && (
                    <span className="absolute left-0 top-1/2 h-5 w-1 -translate-y-1/2 rounded-r-full bg-primary" />
                  )}
                  <Icon
                    className={`h-4 w-4 shrink-0 ${isActive ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground'}`}
                  />
                  <span className="flex-1">{label}</span>
                  {id === 'repositories' && !!repos?.length && (
                    <span className="text-xs tabular-nums text-muted-foreground">{repos.length}</span>
                  )}
                  {id === 'notifications' && !!notifications?.length && (
                    <span className="rounded-full bg-success/15 px-1.5 py-0.5 text-xs font-medium tabular-nums text-success">
                      {notifications.length}
                    </span>
                  )}
                </>
              )}
            </NavLink>
          );
        })}
      </nav>
    </div>
  );
};
