import { useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Search, AlertTriangle, Info } from 'lucide-react';
import {
  advisorApi,
  type AdvisorRequest,
  type AdvisorResponse,
  type AdvisorSignal,
  type StrategyVerdict,
} from '../api/client';

const card: React.CSSProperties = {
  background: 'var(--bg1)',
  border: '1px solid var(--border)',
  borderRadius: 12,
  overflow: 'hidden',
};

const inputStyle: React.CSSProperties = {
  width: '100%',
  padding: '8px 11px',
  fontSize: 14,
  fontFamily: 'var(--font-mono)',
  background: 'var(--bg2)',
  border: '1px solid var(--border-md)',
  borderRadius: 7,
  color: 'var(--text1)',
  outline: 'none',
};

const btn = (variant: 'primary' | 'outline' = 'outline'): React.CSSProperties => ({
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '8px 16px', fontSize: 13, fontWeight: 600,
  borderRadius: 7, border: '1px solid', cursor: 'pointer',
  transition: 'all 0.12s', whiteSpace: 'nowrap',
  background: variant === 'primary' ? 'var(--cyan)' : 'transparent',
  color: variant === 'primary' ? '#fff' : 'var(--text2)',
  borderColor: variant === 'primary' ? 'var(--cyan)' : 'var(--border-md)',
});

const SIGNAL_COLORS: Record<AdvisorSignal, { bg: string; fg: string; border: string }> = {
  BUY:        { bg: 'color-mix(in srgb, var(--green)  18%, transparent)', fg: 'var(--green)',  border: 'var(--green)'  },
  SELL:       { bg: 'color-mix(in srgb, var(--red)    18%, transparent)', fg: 'var(--red)',    border: 'var(--red)'    },
  HOLD:       { bg: 'var(--bg2)',                                          fg: 'var(--text2)',  border: 'var(--border-md)' },
  NO_SIGNAL:  { bg: 'color-mix(in srgb, var(--orange) 14%, transparent)', fg: 'var(--orange)', border: 'var(--orange)' },
  ERROR:      { bg: 'color-mix(in srgb, var(--red)    14%, transparent)', fg: 'var(--red)',    border: 'var(--red)'    },
};

function todayET(): string {
  const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit' });
  return fmt.format(new Date());
}

export function AdvisorPage() {
  const [ticker, setTicker] = useState('');
  const [asof, setAsof] = useState(todayET());
  const [holds, setHolds] = useState(false);
  const [holdStrategy, setHoldStrategy] = useState<'pead' | 'orb'>('pead');
  const [entryDate, setEntryDate] = useState(todayET());
  const [entryPrice, setEntryPrice] = useState('');

  const champions = useQuery({
    queryKey: ['advisor-champions'],
    queryFn: advisorApi.champions,
    staleTime: 60_000 * 60,
  });

  const evalMut = useMutation({
    mutationFn: advisorApi.evaluate,
  });

  const handleSubmit = () => {
    if (!ticker.trim()) {
      return;
    }
    const req: AdvisorRequest = {
      ticker: ticker.trim().toUpperCase(),
      asof: asof || null,
    };
    if (holds && entryPrice && Number(entryPrice) > 0) {
      req.held = {
        strategy: holdStrategy,
        entry_date: entryDate,
        entry_price: Number(entryPrice),
      };
    }
    evalMut.mutate(req);
  };

  const result = evalMut.data;

  return (
    <div style={{ padding: '24px 28px', maxWidth: 1200, margin: '0 auto' }}>
      <header style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 600, margin: 0, color: 'var(--text1)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Search size={20} />
          Single Ticker Advisor
        </h1>
        <p style={{ marginTop: 6, color: 'var(--text3)', fontSize: 13 }}>
          Get BUY / SELL / HOLD verdicts from both PEAD and ORB champion strategies for any ticker.
        </p>
        {champions.data && (
          <div style={{ marginTop: 8, fontSize: 12, color: 'var(--text3)', fontFamily: 'var(--font-mono)' }}>
            PEAD champion: <code>{champions.data.pead.split('/').pop()}</code> · ORB champion:{' '}
            <code>{champions.data.orb.split('/').pop()}</code>
          </div>
        )}
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 24, alignItems: 'start' }}>
        {/* Form */}
        <section style={{ ...card, padding: 18 }}>
          <h3 style={{ fontSize: 14, margin: '0 0 14px', color: 'var(--text2)', fontWeight: 600 }}>Query</h3>

          <label style={{ display: 'block', marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 5 }}>Ticker</div>
            <input
              style={inputStyle}
              placeholder="AAPL"
              value={ticker}
              onChange={e => setTicker(e.target.value.toUpperCase())}
              onKeyDown={e => { if (e.key === 'Enter') handleSubmit(); }}
              autoFocus
            />
          </label>

          <label style={{ display: 'block', marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 5 }}>As-of date</div>
            <input
              type="date"
              style={inputStyle}
              value={asof}
              onChange={e => setAsof(e.target.value)}
            />
          </label>

          <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={holds}
              onChange={e => setHolds(e.target.checked)}
            />
            <span style={{ fontSize: 13, color: 'var(--text2)' }}>I hold this position</span>
          </label>

          {holds && (
            <div style={{ paddingLeft: 12, borderLeft: '2px solid var(--border-md)', marginBottom: 12 }}>
              <label style={{ display: 'block', marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 5 }}>Held under strategy</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {(['pead', 'orb'] as const).map(s => (
                    <label key={s} style={{
                      flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      gap: 6, padding: '7px 10px', borderRadius: 6, cursor: 'pointer',
                      background: holdStrategy === s ? 'var(--cyan-dim)' : 'var(--bg2)',
                      border: `1px solid ${holdStrategy === s ? 'var(--cyan)' : 'var(--border-md)'}`,
                      color: holdStrategy === s ? 'var(--cyan)' : 'var(--text2)',
                      fontSize: 12, fontWeight: 600, textTransform: 'uppercase',
                    }}>
                      <input
                        type="radio"
                        name="strategy"
                        checked={holdStrategy === s}
                        onChange={() => setHoldStrategy(s)}
                        style={{ display: 'none' }}
                      />
                      {s}
                    </label>
                  ))}
                </div>
              </label>
              <label style={{ display: 'block', marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 5 }}>Entry date</div>
                <input type="date" style={inputStyle} value={entryDate} onChange={e => setEntryDate(e.target.value)} />
              </label>
              <label style={{ display: 'block' }}>
                <div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 5 }}>Entry price</div>
                <input
                  type="number"
                  step="0.01"
                  style={inputStyle}
                  placeholder="0.00"
                  value={entryPrice}
                  onChange={e => setEntryPrice(e.target.value)}
                />
              </label>
            </div>
          )}

          <button
            style={btn('primary')}
            onClick={handleSubmit}
            disabled={evalMut.isPending || !ticker.trim()}
          >
            {evalMut.isPending ? 'Evaluating…' : 'Evaluate'}
          </button>

          {evalMut.error && (
            <div style={{ marginTop: 12, padding: 10, background: 'color-mix(in srgb, var(--red) 12%, transparent)', borderRadius: 6, color: 'var(--red)', fontSize: 12 }}>
              {(evalMut.error as Error).message}
            </div>
          )}
        </section>

        {/* Results */}
        <section>
          {!result && !evalMut.isPending && (
            <div style={{ ...card, padding: 40, textAlign: 'center', color: 'var(--text3)' }}>
              Enter a ticker and press Evaluate to see PEAD + ORB verdicts.
            </div>
          )}
          {evalMut.isPending && (
            <div style={{ ...card, padding: 40, textAlign: 'center', color: 'var(--text3)' }}>
              Querying both champion strategies…
            </div>
          )}
          {result && <ResultsView result={result} />}
        </section>
      </div>
    </div>
  );
}

function ResultsView({ result }: { result: AdvisorResponse }) {
  return (
    <div>
      <div style={{ marginBottom: 14, fontSize: 12, color: 'var(--text3)', fontFamily: 'var(--font-mono)' }}>
        {result.ticker} · asof {result.asof} · evaluated {new Date(result.evaluated_at).toLocaleString()}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <VerdictCard label="PEAD" verdict={result.pead} />
        <VerdictCard label="ORB"  verdict={result.orb}  />
      </div>
    </div>
  );
}

function VerdictCard({ label, verdict }: { label: string; verdict: StrategyVerdict }) {
  const palette = SIGNAL_COLORS[verdict.signal];
  const [showDetails, setShowDetails] = useState(false);
  const detailEntries = Object.entries(verdict.details ?? {});
  return (
    <div style={{ ...card }}>
      <div style={{
        padding: '14px 18px',
        borderBottom: '1px solid var(--border)',
        background: palette.bg,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text1)', letterSpacing: '0.05em' }}>
          {label}
        </div>
        <div style={{
          padding: '4px 12px', borderRadius: 999, border: `1.5px solid ${palette.border}`,
          color: palette.fg, fontWeight: 700, fontSize: 13, fontFamily: 'var(--font-mono)',
        }}>
          {verdict.signal}
        </div>
      </div>

      <div style={{ padding: 18 }}>
        {verdict.score != null && (
          <div style={{ marginBottom: 12, fontSize: 13, color: 'var(--text2)' }}>
            Score: <code style={{ fontFamily: 'var(--font-mono)', color: 'var(--text1)' }}>{verdict.score.toFixed(3)}</code>
          </div>
        )}

        <div style={{ marginBottom: 14, fontSize: 13, color: 'var(--text1)', lineHeight: 1.5 }}>
          {verdict.reason}
        </div>

        {verdict.warning && (
          <div style={{
            display: 'flex', alignItems: 'flex-start', gap: 8,
            padding: '10px 12px', borderRadius: 6,
            background: 'color-mix(in srgb, var(--orange) 10%, transparent)',
            border: '1px solid color-mix(in srgb, var(--orange) 25%, transparent)',
            color: 'var(--orange)', fontSize: 12, marginBottom: 12,
          }}>
            <AlertTriangle size={14} style={{ flexShrink: 0, marginTop: 1 }} />
            <span>{verdict.warning}</span>
          </div>
        )}

        {detailEntries.length > 0 && (
          <div>
            <button
              onClick={() => setShowDetails(s => !s)}
              style={{
                display: 'flex', alignItems: 'center', gap: 6, padding: '4px 0',
                background: 'none', border: 'none', cursor: 'pointer',
                color: 'var(--text3)', fontSize: 12,
              }}
            >
              <Info size={12} />
              {showDetails ? 'Hide details' : 'Show details'}
            </button>
            {showDetails && (
              <pre style={{
                marginTop: 8, padding: 12, background: 'var(--bg2)',
                borderRadius: 6, fontSize: 11, fontFamily: 'var(--font-mono)',
                color: 'var(--text2)', overflow: 'auto', maxHeight: 280,
              }}>{JSON.stringify(verdict.details, null, 2)}</pre>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
