import { useState, useEffect, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, GitMerge, X } from 'lucide-react';
import { experimentsApi, backtestApi } from '../api/client';

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

function SleevePill({
  label, value, color,
}: { label: string; value: string; color: string }) {
  return (
    <span style={{
      fontFamily: 'var(--font-mono)', fontSize: 12,
      background: `color-mix(in srgb, ${color} 12%, transparent)`,
      color,
      border: `1px solid color-mix(in srgb, ${color} 28%, transparent)`,
      padding: '2px 10px', borderRadius: 5,
    }}>
      {label}: {value}
    </span>
  );
}

export function ComposeStrategyPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const qc = useQueryClient();

  const [base, setBase] = useState(searchParams.get('base') ?? '');
  const [baseInput, setBaseInput] = useState(searchParams.get('base') ?? '');
  const [showBaseDrop, setShowBaseDrop] = useState(false);
  const [name, setName] = useState('');
  const [changelog, setChangelog] = useState('');
  const [parking, setParking] = useState('');
  const [idleAlpha, setIdleAlpha] = useState('');
  const [form4Sleeve, setForm4Sleeve] = useState('');
  const [ownershipSleeve, setOwnershipSleeve] = useState('');
  const baseInputRef = useRef<HTMLInputElement>(null);
  const dropRef = useRef<HTMLDivElement>(null);

  // Sleeve presets
  const { data: parkingData } = useQuery({
    queryKey: ['parking-presets'],
    queryFn: () => backtestApi.parkingPresets(),
    staleTime: 60_000,
  });
  const { data: idleAlphaData } = useQuery({
    queryKey: ['idle-alpha-presets'],
    queryFn: () => backtestApi.idleAlphaPresets(),
    staleTime: 60_000,
  });
  const { data: form4Data } = useQuery({
    queryKey: ['form4-capture-presets'],
    queryFn: () => backtestApi.form4CapturePresets(),
    staleTime: 60_000,
  });
  const { data: ownershipData } = useQuery({
    queryKey: ['ownership-capture-presets'],
    queryFn: () => backtestApi.ownershipCapturePresets(),
    staleTime: 60_000,
  });

  // Base experiment search
  const { data: baseSearchData } = useQuery({
    queryKey: ['exp-search-compose', baseInput],
    queryFn: () => experimentsApi.list({ pattern: baseInput, limit: 10 }),
    enabled: baseInput.length >= 1 && !base,
    staleTime: 3000,
  });
  const baseSuggestions = (baseSearchData?.experiments ?? []).slice(0, 10);

  // Close dropdown on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (
        baseInputRef.current && !baseInputRef.current.contains(e.target as Node) &&
        dropRef.current && !dropRef.current.contains(e.target as Node)
      ) setShowBaseDrop(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const selectBase = (expName: string) => {
    setBase(expName);
    setBaseInput(expName);
    setShowBaseDrop(false);
    if (!name) setName(expName + '_composed');
  };

  const clearBase = () => {
    setBase('');
    setBaseInput('');
    setName('');
    setShowBaseDrop(false);
    baseInputRef.current?.focus();
  };

  const composeMutation = useMutation({
    mutationFn: () => experimentsApi.compose({
      base,
      name,
      changelog: changelog || undefined,
      parking: parking || null,
      idle_alpha: idleAlpha || null,
      form4_sleeve: form4Sleeve || null,
      ownership_sleeve: ownershipSleeve || null,
    }),
    onSuccess: (data) => {
      qc.invalidateQueries({ queryKey: ['experiments'] });
      navigate(`/experiments/${encodeURIComponent(data.name)}`);
    },
  });

  const activeSleeves = [
    parking && { label: 'parking', value: parking, color: 'var(--orange)' },
    idleAlpha && { label: 'idle_alpha', value: idleAlpha, color: 'var(--green)' },
    form4Sleeve && { label: 'form4', value: form4Sleeve, color: 'var(--cyan)' },
    ownershipSleeve && { label: 'ownership', value: ownershipSleeve, color: 'var(--violet, var(--cyan))' },
  ].filter(Boolean) as { label: string; value: string; color: string }[];

  const canSubmit = !!base && !!name && !composeMutation.isPending;

  return (
    <div style={{ padding: '36px 40px', maxWidth: 760 }} className="fade-up">
      {/* Back */}
      <button
        onClick={() => navigate('/experiments')}
        style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: 'none', border: 'none', cursor: 'pointer',
          color: 'var(--text3)', fontSize: 13, fontFamily: 'var(--font-mono)',
          padding: 0, marginBottom: 24,
        }}
        onMouseEnter={e => (e.currentTarget.style.color = 'var(--text1)')}
        onMouseLeave={e => (e.currentTarget.style.color = 'var(--text3)')}
      >
        <ArrowLeft size={14} /> back to strategies
      </button>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
        <GitMerge size={22} style={{ color: 'var(--cyan)' }} />
        <h1 style={{ fontSize: 28, fontWeight: 700, color: 'var(--text1)', letterSpacing: '-0.02em' }}>
          Compose Strategy
        </h1>
      </div>
      <p style={{ fontSize: 14, color: 'var(--text3)', marginBottom: 36, lineHeight: 1.6 }}>
        베이스 전략에 슬리브(Parking, Idle Alpha, Form4, Ownership)를 조합해 새 전략을 생성합니다.
        슬리브 설정은 새 전략 config에 bake-in되어 백테스트/페이퍼트레이딩 시 자동 적용됩니다.
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>

        {/* ── Base strategy ──────────────────────────────────────────── */}
        <section>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: 10 }}>
            Base Strategy *
          </div>
          <div style={{ position: 'relative' }}>
            <input
              ref={baseInputRef}
              type="text"
              placeholder="Search strategy..."
              value={baseInput}
              onChange={e => {
                setBaseInput(e.target.value);
                setBase('');
                setShowBaseDrop(true);
              }}
              onFocus={() => { if (!base) setShowBaseDrop(true); }}
              style={{
                ...inputStyle,
                maxWidth: 480,
                borderColor: base ? 'var(--cyan)' : 'var(--border-md)',
                paddingRight: base ? 36 : 12,
              }}
            />
            {base && (
              <button
                onClick={clearBase}
                style={{
                  position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
                  background: 'none', border: 'none', cursor: 'pointer',
                  color: 'var(--text3)', display: 'flex', alignItems: 'center', padding: 0,
                }}
              >
                <X size={14} />
              </button>
            )}
            {showBaseDrop && baseSuggestions.length > 0 && (
              <div ref={dropRef} style={{
                position: 'absolute', top: '100%', left: 0, marginTop: 4,
                background: 'var(--bg1)', border: '1px solid var(--border-md)',
                borderRadius: 10, width: 480, maxWidth: '90vw',
                boxShadow: '0 8px 28px rgba(0,0,0,0.18)', zIndex: 50, overflow: 'hidden',
              }}>
                {baseSuggestions.map(e => (
                  <button
                    key={e.name}
                    onMouseDown={() => selectBase(e.name)}
                    style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      width: '100%', padding: '9px 14px',
                      background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
                      cursor: 'pointer', textAlign: 'left', gap: 12,
                    }}
                    onMouseEnter={ev => (ev.currentTarget.style.background = 'var(--cyan-dim)')}
                    onMouseLeave={ev => (ev.currentTarget.style.background = 'none')}
                  >
                    <div>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text1)' }}>{e.name}</div>
                      {e.version_family && (
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>{e.version_family}</div>
                      )}
                    </div>
                    {e.sqs_score != null && (
                      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--gold)', flexShrink: 0, fontWeight: 600 }}>
                        SQS {e.sqs_score.toFixed(1)}
                      </span>
                    )}
                  </button>
                ))}
              </div>
            )}
          </div>
          {base && (
            <div style={{ marginTop: 8, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--green)' }}>
              ✓ {base}
            </div>
          )}
        </section>

        {/* ── Sleeves ──────────────────────────────────────────────────── */}
        <section>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: 12 }}>
            Sleeves
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            {/* Parking */}
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', marginBottom: 6 }}>
                Cash Parking
              </label>
              <select
                value={parking}
                onChange={e => setParking(e.target.value)}
                style={{ ...inputStyle, color: parking ? 'var(--orange)' : 'var(--text3)', fontSize: 13 }}
              >
                <option value="">— none —</option>
                {parkingData ? Object.entries(parkingData.groups).map(([group, names]) => (
                  <optgroup key={group} label={group}>
                    {names.map(n => <option key={n} value={n}>{n}</option>)}
                  </optgroup>
                )) : null}
              </select>
            </div>

            {/* Idle Alpha */}
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', marginBottom: 6 }}>
                Idle Alpha
              </label>
              <select
                value={idleAlpha}
                onChange={e => setIdleAlpha(e.target.value)}
                style={{ ...inputStyle, color: idleAlpha ? 'var(--green)' : 'var(--text3)', fontSize: 13 }}
              >
                <option value="">— none —</option>
                {idleAlphaData ? Object.entries(idleAlphaData.groups).map(([group, names]) => (
                  <optgroup key={group} label={group}>
                    {names.map(n => <option key={n} value={n}>{n}</option>)}
                  </optgroup>
                )) : null}
              </select>
            </div>

            {/* Form4 */}
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', marginBottom: 6 }}>
                Form 4 Sleeve
              </label>
              <select
                value={form4Sleeve}
                onChange={e => setForm4Sleeve(e.target.value)}
                style={{ ...inputStyle, color: form4Sleeve ? 'var(--cyan)' : 'var(--text3)', fontSize: 13 }}
              >
                <option value="">— none —</option>
                {form4Data ? Object.entries(form4Data.groups).map(([group, names]) => (
                  <optgroup key={group} label={group}>
                    {names.map(n => <option key={n} value={n}>{n}</option>)}
                  </optgroup>
                )) : null}
              </select>
            </div>

            {/* Ownership */}
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', marginBottom: 6 }}>
                Ownership Sleeve
              </label>
              <select
                value={ownershipSleeve}
                onChange={e => setOwnershipSleeve(e.target.value)}
                style={{ ...inputStyle, color: ownershipSleeve ? 'var(--violet, var(--cyan))' : 'var(--text3)', fontSize: 13 }}
              >
                <option value="">— none —</option>
                {ownershipData ? Object.entries(ownershipData.groups).map(([group, names]) => (
                  <optgroup key={group} label={group}>
                    {names.map(n => <option key={n} value={n}>{n}</option>)}
                  </optgroup>
                )) : null}
              </select>
            </div>
          </div>

          {/* Active sleeves preview */}
          {activeSleeves.length > 0 && (
            <div style={{ marginTop: 12, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {activeSleeves.map(s => (
                <SleevePill key={s.label} label={s.label} value={s.value} color={s.color} />
              ))}
            </div>
          )}
        </section>

        {/* ── New name + changelog ─────────────────────────────────────── */}
        <section>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: 12 }}>
            New Strategy
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', marginBottom: 6 }}>
                Name *
              </label>
              <input
                type="text"
                placeholder="e.g. return_max_long_v17.1_composed"
                value={name}
                onChange={e => setName(e.target.value)}
                style={{ ...inputStyle, maxWidth: 480 }}
              />
            </div>
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', marginBottom: 6 }}>
                Changelog (optional)
              </label>
              <textarea
                placeholder="Describe the composition..."
                value={changelog}
                onChange={e => setChangelog(e.target.value)}
                rows={3}
                style={{ ...inputStyle, maxWidth: 480, resize: 'vertical', minHeight: 72 }}
              />
            </div>
          </div>
        </section>

        {/* ── Preview card ─────────────────────────────────────────────── */}
        {(base || activeSleeves.length > 0 || name) && (
          <section style={{
            background: 'var(--bg1)', border: '1px solid var(--border)',
            borderRadius: 12, padding: '18px 20px',
          }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: 12 }}>
              Preview
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ display: 'flex', gap: 10, fontSize: 13 }}>
                <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text3)', minWidth: 80 }}>base</span>
                <span style={{ fontFamily: 'var(--font-mono)', color: base ? 'var(--text1)' : 'var(--text3)' }}>
                  {base || '—'}
                </span>
              </div>
              {activeSleeves.map(s => (
                <div key={s.label} style={{ display: 'flex', gap: 10, fontSize: 13 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text3)', minWidth: 80 }}>{s.label}</span>
                  <span style={{ fontFamily: 'var(--font-mono)', color: s.color }}>{s.value}</span>
                </div>
              ))}
              <div style={{ display: 'flex', gap: 10, fontSize: 13 }}>
                <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text3)', minWidth: 80 }}>name</span>
                <span style={{ fontFamily: 'var(--font-mono)', color: name ? 'var(--cyan)' : 'var(--text3)' }}>
                  {name || '—'}
                </span>
              </div>
            </div>
          </section>
        )}

        {/* ── Error ────────────────────────────────────────────────────── */}
        {composeMutation.isError && (
          <div style={{
            padding: '12px 16px', background: 'var(--red-dim)',
            border: '1px solid rgba(220,38,38,0.25)', borderRadius: 8,
            color: 'var(--red)', fontSize: 13, fontFamily: 'var(--font-mono)',
          }}>
            {(composeMutation.error as Error).message}
          </div>
        )}

        {/* ── Submit ───────────────────────────────────────────────────── */}
        <div style={{ display: 'flex', gap: 10 }}>
          <button
            onClick={() => composeMutation.mutate()}
            disabled={!canSubmit}
            style={{
              display: 'flex', alignItems: 'center', gap: 7,
              padding: '10px 24px', fontSize: 15, fontWeight: 600, borderRadius: 9,
              cursor: canSubmit ? 'pointer' : 'not-allowed',
              background: canSubmit ? 'var(--cyan-dim)' : 'var(--bg2)',
              border: `1px solid ${canSubmit ? 'rgba(0,119,182,0.35)' : 'var(--border)'}`,
              color: canSubmit ? 'var(--cyan)' : 'var(--text3)',
              transition: 'all 0.12s',
            }}
            onMouseEnter={e => { if (canSubmit) (e.currentTarget as HTMLButtonElement).style.background = 'var(--cyan-mid)'; }}
            onMouseLeave={e => { if (canSubmit) (e.currentTarget as HTMLButtonElement).style.background = 'var(--cyan-dim)'; }}
          >
            <GitMerge size={15} />
            {composeMutation.isPending ? 'Creating...' : 'Create Strategy'}
          </button>
          <button
            onClick={() => navigate('/experiments')}
            style={{
              padding: '10px 20px', fontSize: 15, borderRadius: 9,
              background: 'none', border: '1px solid var(--border-md)',
              color: 'var(--text3)', cursor: 'pointer',
            }}
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
