'use client';

import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useTheme } from 'next-themes';
import { useQuery } from '@tanstack/react-query';
import { adminClient } from '@/lib/api';
import { useCommandPalette } from '@/components/CommandPalette';
import { useAuthSession } from '@/components/AuthGate';
import { useToast } from '@/components/Toast';

const NAV_ITEMS = [
  {
    name: 'Home',
    href: '/',
    d: 'M3 11l9-8 9 8v9a1 1 0 01-1 1h-5v-6H9v6H4a1 1 0 01-1-1z',
  },
  { name: 'Messages', href: '/messages', d: 'M4 5h16v11H8l-4 4z' },
  {
    name: 'Insights',
    href: '/insights',
    d: 'M4 20V10M10 20V4M16 20v-8M22 20H2',
  },
  {
    name: 'Apps',
    href: '/apps',
    d: 'M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z',
  },
  {
    name: 'Channels',
    href: '/channels',
    d: 'M9 3v6M15 3v6M6 9h12v4a6 6 0 01-12 0zM12 19v3',
  },
  {
    name: 'Templates',
    href: '/templates',
    d: 'M5 3h14v18H5zM9 8h6M9 12h6M9 16h3',
  },
  { name: 'Logs', href: '/logs', d: 'M4 6h16M4 12h16M4 18h10' },
  {
    name: 'Settings',
    href: '/settings',
    d: 'M4 6h10M18 6h2M4 12h4M12 12h8M4 18h12M20 18h0M14 4v4M10 10v4M16 16v4',
  },
];

function Icon({ d }: { d: string }) {
  return (
    <svg
      className="w-[18px] h-[18px] stroke-[1.8] fill-none stroke-current flex-none"
      viewBox="0 0 24 24"
      aria-hidden
    >
      <path d={d} strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

export function Sidebar() {
  const pathname = usePathname();
  const { theme, setTheme, resolvedTheme } = useTheme();
  const { open: openPalette } = useCommandPalette();
  const { signOut } = useAuthSession();
  const { toast } = useToast();
  const [mounted, setMounted] = React.useState(false);

  const healthQuery = useQuery({
    queryKey: ['health'],
    queryFn: () => adminClient.health(),
    refetchInterval: 15000,
    retry: false,
  });

  React.useEffect(() => {
    setMounted(true);
  }, []);

  const isDark =
    theme === 'midnight' ||
    theme === 'dark' ||
    (theme === 'system' && resolvedTheme === 'dark');

  const isHealthy = healthQuery.data?.status === 'ok';

  const handleCopyEndpoint = () => {
    const endpoint = 'http://localhost:8080/api/v1/messages';
    void navigator.clipboard?.writeText(endpoint);
    toast('Copied API endpoint: ' + endpoint);
  };

  return (
    <nav className="zy-nav">
      <div className="zy-brand justify-between">
        <div className="flex items-center gap-2.5">
          <span className="zy-mark">Z</span>
          <div className="leading-tight">
            <span className="block tracking-tight">Zyphon</span>
            <span className="block text-[11px] font-medium text-muted">Messaging Hub</span>
          </div>
        </div>
        <span
          title={isHealthy ? 'Gateway online' : 'Checking gateway'}
          className={`w-2.5 h-2.5 rounded-full ${isHealthy ? 'bg-ok zy-pulse-ok' : 'bg-warn'}`}
        />
      </div>

      <button type="button" className="zy-search" onClick={openPalette}>
        <span>Quick jump…</span>
        <kbd>Ctrl K</kbd>
      </button>

      <div className="zy-links">
        {NAV_ITEMS.map((item) => {
          const isActive =
            item.href === '/' ? pathname === '/' : pathname.startsWith(item.href);
          return (
            <Link
              key={item.href}
              href={item.href}
              className={isActive ? 'zy-link on' : 'zy-link'}
            >
              <Icon d={item.d} />
              {item.name}
            </Link>
          );
        })}
      </div>

      <div className="zy-sp" />

      {/* Developer API Endpoint Quick Copy */}
      <button
        type="button"
        onClick={handleCopyEndpoint}
        title="Click to copy Unified Dispatch API URL"
        className="w-full text-left rounded-[var(--r)] border border-line bg-bg hover:border-accent p-2.5 mb-2 text-xs transition-all cursor-pointer"
      >
        <div className="flex items-center justify-between text-muted mb-1">
          <span className="font-medium text-text">Unified API</span>
          <span className={`font-semibold text-[11px] ${isHealthy ? 'text-ok' : 'text-warn'}`}>
            {isHealthy ? '● :8080 Ready' : '○ Connecting'}
          </span>
        </div>
        <div className="text-[11px] text-muted font-mono truncate">
          POST /api/v1/messages
        </div>
      </button>

      <div className="zy-me">
        <span className="zy-av">A</span>
        <span className="zy-me-label font-medium text-text">Admin</span>
        <button
          type="button"
          className="zy-theme-btn"
          onClick={() => setTheme(isDark ? 'light' : 'dark')}
          aria-label={mounted && isDark ? 'Switch to light theme' : 'Switch to dark theme'}
          title="Toggle light / dark theme"
        >
          <Icon
            d={
              mounted && isDark
                ? 'M12 7a5 5 0 100 10 5 5 0 000-10zM12 1v3M12 20v3M1 12h3M20 12h3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1'
                : 'M21 13A9 9 0 1111 3a7 7 0 0010 10z'
            }
          />
        </button>
        <button type="button" className="zy-theme-btn" onClick={signOut} title="Sign out" aria-label="Sign out">
          <Icon d="M9 4H5a1 1 0 00-1 1v14a1 1 0 001 1h4M14 12h7M17 8l4 4-4 4" />
        </button>
      </div>
    </nav>
  );
}
