import { useState, useEffect, useRef } from 'react';
import { Moon, Search, Sun } from 'lucide-react';
import { useAppContext } from '../../context/AppContext';
import { useNavigate } from 'react-router-dom';
import { fetchMarketIndices, type IndexSnapshot } from '../../lib/marketApi';
import { useTheme } from '../theme/ThemeProvider';
import { Button, Input } from '../ui/Primitives';


export function Header() {
  const { setActiveSymbol, connected } = useAppContext();
  const [query, setQuery]     = useState('');
  const [indices, setIndices] = useState<IndexSnapshot[]>([]);
  const navigate = useNavigate();
  const inputRef = useRef<HTMLInputElement>(null);
  const { theme, toggleTheme } = useTheme();

  // Fetch live market indices while visible; hidden tabs should not burn API quota.
  useEffect(() => {
    let cancelled = false;
    const isVisible = () => typeof document === 'undefined' || document.visibilityState === 'visible';
    const load = () => {
      if (!isVisible()) return;
      fetchMarketIndices()
        .then(data => { if (!cancelled) setIndices(data); })
        .catch(() => {/* ignore — keep stale data */});
    };
    const handleVisibilityChange = () => {
      if (isVisible()) load();
    };

    load();
    const interval = setInterval(load, 60_000);
    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      cancelled = true;
      clearInterval(interval);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  const handleSearch = (raw: string) => {
    const symbol = raw.trim().toUpperCase();
    if (!symbol) return;
    setActiveSymbol(symbol);
    setQuery('');
    navigate('/');
    inputRef.current?.blur();
  };

  useEffect(() => {
    const handleShortcut = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
        event.preventDefault();
        inputRef.current?.focus();
      }
    };

    window.addEventListener('keydown', handleShortcut);
    return () => window.removeEventListener('keydown', handleShortcut);
  }, []);

  return (
    <header className="trading-header" style={{
      height: 56,
      background: 'var(--header)',
      borderBottom: '1px solid var(--border)',
      display: 'flex',
      alignItems: 'center',
      paddingLeft: 20,
      paddingRight: 24,
      gap: 16,
      flexShrink: 0,
      backdropFilter: 'blur(18px)',
    }}>
      {/* Search bar */}
      <div className="trading-header-search" style={{ position: 'relative', width: 300 }}>
        <Search
          size={15}
          style={{
            position: 'absolute',
            left: 11,
            top: '50%',
            transform: 'translateY(-50%)',
            color: 'var(--muted-foreground)',
            pointerEvents: 'none',
          }}
        />
        <Input
          ref={inputRef}
          aria-label="Search ticker"
          type="text"
          value={query}
          onChange={e => setQuery(e.target.value)}
          onKeyDown={e => {
            if (e.key === 'Enter') handleSearch(query);
          }}
          placeholder="Ask about a company... (Cmd/Ctrl K)"
          title="Focus search with Cmd/Ctrl+K"
          style={{
            width: '100%',
            paddingLeft: 34,
            paddingRight: 12,
            fontSize: 13,
            boxSizing: 'border-box',
            fontFamily: 'inherit',
          }}
        />
      </div>

      {/* Spacer */}
      <div style={{ flex: 1 }} />

      {/* Market indices */}
      <div className="trading-header-indices" style={{ display: 'flex', gap: 28, alignItems: 'center' }}>
        {indices.length === 0 ? (
          // Skeleton while loading
          ['S&P 500','Dow Jones','Nasdaq'].map(label => (
            <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--muted-foreground)', fontWeight: 500 }}>{label}</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--muted-foreground)' }}>—</div>
              </div>
            </div>
          ))
        ) : indices.map(idx => {
          const signStr = idx.positive ? '+' : '';
          return (
            <div key={idx.label} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--muted-foreground)', fontWeight: 500, lineHeight: 1.3 }}>
                  {idx.label}
                </div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
                  <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--foreground)', lineHeight: 1.3 }}>
                    ${idx.price.toFixed(2)}
                  </span>
                  <span style={{
                    fontSize: 12, fontWeight: 700, lineHeight: 1.3,
                    color: idx.positive ? 'var(--bl-success)' : 'var(--bl-danger)',
                  }}>
                    {signStr}{idx.changePct.toFixed(2)}%
                  </span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <Button
        type="button"
        variant="outline"
        size="icon"
        aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
        onClick={toggleTheme}
      >
        {theme === 'dark' ? <Sun size={16} /> : <Moon size={16} />}
      </Button>

      {/* Live indicator */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginLeft: 8 }}>
        <span style={{
          width: 7,
          height: 7,
          borderRadius: '50%',
          background: connected ? 'var(--bl-success)' : 'var(--destructive)',
          display: 'inline-block',
          flexShrink: 0,
        }} />
        <span style={{ fontSize: 11, color: 'var(--muted-foreground)', whiteSpace: 'nowrap' }}>
          {connected ? 'Live' : 'Reconnecting'}
        </span>
      </div>
    </header>
  );
}
