import { useState } from 'react';
import { NavLink } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useAuthStore } from '../../stores/authStore';
import { check as healthCheck } from '../../api/health';
import { getRunningJobs } from '../../api/jobs';
import { useMarketRegime } from '../../hooks/useMarketRegime';
import { useSystemEventSummary, useAcknowledgeSystemEvents } from '../../hooks/useAdmin';
import { regimeDot, regimeHeadline } from '../../lib/regime';
import TickerSearch from './TickerSearch';

const navItems = [
  { to: '/', label: 'Overview', end: true },
  { to: '/market', label: 'Market', end: false },
  { to: '/signals', label: 'Signals', end: false },
  { to: '/regime', label: 'Regime', end: false },
];

const linkClasses = (isActive: boolean) =>
  `pb-0.5 text-[13.5px] font-medium transition-colors border-b ${
    isActive
      ? 'border-blue-500 text-gray-100'
      : 'border-transparent text-gray-400 hover:text-gray-200'
  }`;

/** Desktop command bar — the mockup's top navigation. MobileNav covers <lg. */
export default function TopBar() {
  const { role, username, logout } = useAuthStore();
  const [alertsOpen, setAlertsOpen] = useState(false);

  const health = useQuery({
    queryKey: ['health'],
    queryFn: healthCheck,
    refetchInterval: 30_000,
    retry: 1,
  });

  const isBackendUp = health.isSuccess;

  const jobs = useQuery({
    queryKey: ['jobs', 'running'],
    queryFn: getRunningJobs,
    refetchInterval: 10_000,
    retry: 1,
    enabled: isBackendUp,
  });

  const eventSummary = useSystemEventSummary(7);
  const ackEvents = useAcknowledgeSystemEvents();
  const unacked = eventSummary.data?.unacknowledged ?? 0;
  const unackedErrors = eventSummary.data?.unacknowledged_errors ?? 0;

  const running = jobs.data?.running ?? [];
  const regime = useMarketRegime();

  return (
    <header className="glass sticky top-0 z-40 hidden items-center gap-7 rounded-none border-x-0 border-t-0 px-8 py-3 lg:flex">
      {/* Wordmark */}
      <NavLink to="/" className="flex items-center" aria-label="Signal — overview">
        <span className="font-display text-[15px] font-bold tracking-[0.4em] text-gray-100">
          SIGNAL
        </span>
        <span
          className="ml-0.5 inline-block h-[7px] w-[7px] rounded-full bg-[#ff6a45]"
          style={{ boxShadow: '0 0 10px rgba(255,106,69,.7)' }}
        />
      </NavLink>

      <nav className="flex items-center gap-6" aria-label="Sections">
        {navItems.map(({ to, label, end }) => (
          <NavLink key={to} to={to} end={end} className={({ isActive }) => linkClasses(isActive)}>
            {label}
          </NavLink>
        ))}
        {role === 'admin' && (
          <NavLink to="/admin" className={({ isActive }) => linkClasses(isActive)}>
            Admin
          </NavLink>
        )}
      </nav>

      <div className="w-56">
        <TickerSearch />
      </div>

      <div className="ml-auto flex items-center gap-5">
        {/* Market regime — ambient status; the full picture lives on /regime */}
        {regime.data && (
          <NavLink
            to="/regime"
            className="group flex items-center gap-2"
            title={`${regimeHeadline(regime.data)}${
              regime.data.label === 'bearish'
                ? ' — be cautious on new longs'
                : regime.data.label === 'bullish'
                  ? ' — shorts are counter-trend'
                  : ''
            }`}
          >
            <span className={`inline-block h-1.5 w-1.5 rounded-full ${regimeDot(regime.data.label)}`} />
            <span className="text-[11px] capitalize text-gray-500 transition-colors group-hover:text-gray-300">
              {regime.data.label} regime
            </span>
          </NavLink>
        )}
        {/* Live background-job activity, condensed */}
        {running.length > 0 && (
          <span className="flex max-w-[220px] items-center gap-2" title={running.map((j) => j.label).join(' · ')}>
            <span className="inline-block h-1.5 w-1.5 shrink-0 animate-signal-pulse rounded-full bg-blue-400" />
            <span className="truncate text-[11px] text-gray-400">
              {running[0].label}
              {running[0].progress_pct != null && (
                <span className="num text-gray-500"> {Math.round(running[0].progress_pct)}%</span>
              )}
              {running.length > 1 && <span className="text-gray-500"> +{running.length - 1}</span>}
            </span>
          </span>
        )}

        {/* System alerts badge — open issues from jobs / ingestion */}
        <div className="relative">
          <button
            type="button"
            onClick={() => setAlertsOpen((v) => !v)}
            className={`relative flex items-center gap-1.5 rounded-md px-1.5 py-1 text-[11px] transition-colors ${
              unacked > 0
                ? unackedErrors > 0
                  ? 'text-red-300 hover:bg-red-500/10'
                  : 'text-amber-300 hover:bg-amber-500/10'
                : 'text-gray-500 hover:bg-white/[0.04] hover:text-gray-300'
            }`}
            title={unacked > 0 ? `${unacked} open system alert${unacked === 1 ? '' : 's'}` : 'No open system alerts'}
            aria-label={unacked > 0 ? `${unacked} open system alerts` : 'System alerts'}
            aria-expanded={alertsOpen}
          >
            <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.4-1.4A2 2 0 0118 14.2V11a6 6 0 10-12 0v3.2c0 .5-.2 1-.6 1.4L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
            </svg>
            {unacked > 0 && (
              <span className={`num min-w-[1.1rem] rounded-full px-1 text-center text-[10px] font-semibold ${
                unackedErrors > 0 ? 'bg-red-500/25 text-red-200' : 'bg-amber-500/25 text-amber-100'
              }`}>
                {unacked > 99 ? '99+' : unacked}
              </span>
            )}
          </button>
          {alertsOpen && (
            <>
              <button
                type="button"
                className="fixed inset-0 z-40 cursor-default"
                aria-label="Close alerts"
                onClick={() => setAlertsOpen(false)}
              />
              <div className="absolute right-0 top-full z-50 mt-2 w-72 rounded-xl border border-white/[0.08] bg-[#12141c] p-3 shadow-xl">
                <p className="text-[11px] font-medium text-gray-300">
                  {unacked > 0
                    ? `${unacked} open alert${unacked === 1 ? '' : 's'} (last 7 days)`
                    : 'No open alerts'}
                </p>
                {eventSummary.data && eventSummary.data.total > 0 && (
                  <p className="mt-0.5 text-[10px] text-gray-500">
                    {eventSummary.data.unacknowledged_errors} error
                    {eventSummary.data.unacknowledged_errors === 1 ? '' : 's'}
                    {' · '}
                    {eventSummary.data.unacknowledged_warnings} warning
                    {eventSummary.data.unacknowledged_warnings === 1 ? '' : 's'} open
                  </p>
                )}
                <div className="mt-3 flex flex-col gap-1.5">
                  {role === 'admin' && (
                    <NavLink
                      to="/admin"
                      onClick={() => setAlertsOpen(false)}
                      className="rounded-md px-2 py-1.5 text-[12px] text-blue-300 transition-colors hover:bg-white/[0.04]"
                    >
                      View in Admin → Alerts
                    </NavLink>
                  )}
                  <button
                    type="button"
                    disabled={unacked === 0 || ackEvents.isPending}
                    onClick={() => {
                      ackEvents.mutate(7, {
                        onSuccess: () => setAlertsOpen(false),
                      });
                    }}
                    className="rounded-md px-2 py-1.5 text-left text-[12px] text-gray-300 transition-colors hover:bg-white/[0.04] disabled:opacity-40"
                  >
                    {ackEvents.isPending ? 'Dismissing…' : 'Dismiss open alerts'}
                  </button>
                </div>
              </div>
            </>
          )}
        </div>

        <span
          className={`inline-block h-2 w-2 rounded-full ${
            isBackendUp ? 'bg-emerald-400 shadow-lg shadow-emerald-400/50' : 'bg-red-400 shadow-lg shadow-red-400/50'
          }`}
          title={isBackendUp ? 'Backend online' : 'Backend offline'}
          aria-label={isBackendUp ? 'Backend online' : 'Backend offline'}
        />
        {username && <span className="max-w-[140px] truncate text-xs text-gray-500">{username}</span>}
        <button
          onClick={logout}
          className="text-[13px] text-gray-400 transition-colors hover:text-gray-200"
        >
          Logout
        </button>
      </div>
    </header>
  );
}
