import { useState, useEffect, useRef } from 'react';
import { Search } from 'lucide-react';
import { useAppContext } from '../../context/AppContext';
import { useNavigate } from 'react-router-dom';
import { fetchMarketIndices, type IndexSnapshot } from '../../lib/marketApi';


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

  // 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 style={{
      height: 56,
      background: '#ffffff',
      borderBottom: '1px solid #E5E7EB',
      display: 'flex',
      alignItems: 'center',
      paddingLeft: 20,
      paddingRight: 24,
      gap: 16,
      flexShrink: 0,
    }}>
      {/* Search bar */}
      <div style={{ position: 'relative', width: 300 }}>
        <Search
          size={15}
          style={{
            position: 'absolute',
            left: 11,
            top: '50%',
            transform: 'translateY(-50%)',
            color: '#9CA3AF',
            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,
            paddingTop: 8,
            paddingBottom: 8,
            border: '1px solid #E5E7EB',
            borderRadius: 8,
            fontSize: 13,
            outline: 'none',
            color: '#374151',
            background: '#F9FAFB',
            boxSizing: 'border-box',
            fontFamily: 'inherit',
          }}
        />
      </div>

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

      {/* Market indices */}
      <div 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: '#6B7280', fontWeight: 500 }}>{label}</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: '#D1D5DB' }}>—</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: '#6B7280', fontWeight: 500, lineHeight: 1.3 }}>
                  {idx.label}
                </div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
                  <span style={{ fontSize: 12, fontWeight: 600, color: '#111827', lineHeight: 1.3 }}>
                    ${idx.price.toFixed(2)}
                  </span>
                  <span style={{
                    fontSize: 12, fontWeight: 700, lineHeight: 1.3,
                    color: idx.positive ? '#16A34A' : '#DC2626',
                  }}>
                    {signStr}{idx.changePct.toFixed(2)}%
                  </span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Live indicator */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginLeft: 8 }}>
        <span style={{
          width: 7,
          height: 7,
          borderRadius: '50%',
          background: connected ? '#22C55E' : '#EF4444',
          display: 'inline-block',
          flexShrink: 0,
        }} />
        <span style={{ fontSize: 11, color: '#9CA3AF', whiteSpace: 'nowrap' }}>
          {connected ? 'Live' : 'Reconnecting'}
        </span>
      </div>
    </header>
  );
}
