import { useEffect, useState } from 'react';
import type { BatchMergeResult } from '../../lib/orchestratorApi';

/**
 * Results overlay for a "merge all" batch: shows each branch's outcome, which
 * one (if any) conflicted and halted the batch, and which were left unattempted.
 *
 * A success means the merge landed; `alreadyMerged` is a no-op; `ok:false` is a
 * conflict that stopped the run. Branches after the conflict are simply absent
 * from `items` (the server didn't attempt them) — surfaced via the `haltedOn`
 * banner so the operator knows to resolve and re-run.
 */
interface MergeAllModalProps {
  result: BatchMergeResult | null;
  busy: boolean;
  onClose: () => void;
}

export function MergeAllModal({ result, busy, onClose }: MergeAllModalProps) {
  // Close on Escape.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div
        className="max-h-[80vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-border bg-surface p-6 shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-4 flex items-center gap-2">
          <h2 className="m-0 text-lg text-fg-bright">Merge all agent branches</h2>
          <button
            className="ml-auto cursor-pointer rounded border border-border bg-transparent px-2 py-0.5 text-muted hover:text-fg"
            onClick={onClose}
          >
            ✕
          </button>
        </div>

        {busy && !result && (
          <p className="m-0 text-[0.85rem] text-fg-dim">Merging branches sequentially…</p>
        )}

        {result && (
          <>
            <p className="m-0 mb-3 text-[0.82rem] text-fg-dim">
              Target branch: <code className="font-mono text-cyan">{result.target}</code>
              {' · '}
              {result.items.filter((i) => i.ok && !i.alreadyMerged).length} merged
              {result.items.some((i) => i.conflict && i.ok) &&
                ` · ${result.items.filter((i) => i.conflict && i.ok).length} conflicts resolved by agent`}
              {result.items.some((i) => i.alreadyMerged) &&
                ` · ${result.items.filter((i) => i.alreadyMerged).length} already in`}
              {result.items.some((i) => i.skipped) &&
                ` · ${result.items.filter((i) => i.skipped).length} skipped`}
              {result.haltedOn && ' · halted on conflict'}
            </p>

            {result.aborted && result.reason && (
              <div style={bannerStyle('var(--red)')}>⚠ {result.reason}</div>
            )}

            {result.haltedOn && (
              <div style={bannerStyle('var(--red)')}>
                ⚠ Conflict merging <code style={monoStyle}>{result.haltedOn}</code> could not be
                resolved automatically — batch stopped, {result.target} left clean. Resolve or drop
                that branch, then re-run.
              </div>
            )}

            {!result.aborted && !result.haltedOn && result.items.length > 0 && (
              <div style={bannerStyle('var(--green)')}>
                ✓ All reviewable branches merged into {result.target}.
              </div>
            )}

            {result.items.length === 0 && !result.aborted && (
              <p className="m-0 text-[0.85rem] italic text-muted">
                No branches needed merging — everything is already in {result.target}.
              </p>
            )}

            {result.recoveryRef && (
              <div style={bannerStyle('var(--fg-dim)')}>
                Recovery ref created at pre-batch HEAD:{' '}
                <code style={monoStyle}>{result.recoveryRef}</code>. Roll back the whole batch with{' '}
                <code style={monoStyle}>git reset --hard {result.recoveryRef}</code>.
              </div>
            )}

            {result.items.length > 0 && (
              <div className="flex flex-col gap-2">
                {result.items.map((item) => {
                  const tone = item.skipped
                    ? 'var(--muted)'
                    : item.alreadyMerged
                      ? 'var(--muted)'
                      : item.ok
                        ? 'var(--green)'
                        : 'var(--red)';
                  const label = item.skipped
                    ? 'skipped (branch gone)'
                    : item.alreadyMerged
                      ? 'already in target'
                      : item.conflict && item.ok
                        ? 'conflict resolved by agent'
                        : item.ok
                          ? 'merged'
                          : 'conflict';
                  const glyph = item.skipped
                    ? '⤳'
                    : item.alreadyMerged
                      ? '⇢'
                      : item.conflict && item.ok
                        ? '🤖'
                        : item.ok
                          ? '✓'
                          : '⚠';
                  return (
                    <div
                      key={item.runId}
                      style={{
                        border: `1px solid ${tone}33`,
                        background: `${tone}0f`,
                        borderRadius: 'var(--radius-sm)',
                        padding: '8px 10px',
                      }}
                    >
                      <div className="flex items-center gap-2">
                        <span style={{ color: tone, fontWeight: 600, fontSize: '0.8rem' }}>
                          {glyph}
                        </span>
                        <code style={monoStyle}>{item.branch}</code>
                        <span className="text-[0.7rem] text-muted">{label}</span>
                        {item.resolutionRunId && (
                          <span className="text-[0.62rem] text-muted" title={item.resolutionRunId}>
                            ↳ {item.resolutionRunId.slice(0, 8)}
                          </span>
                        )}
                      </div>
                      {!item.ok && item.output && (
                        <pre
                          className="m-1 mt-2 overflow-x-auto text-[0.66rem] text-fg-dim"
                          style={preStyle}
                        >
                          {item.output}
                        </pre>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

// --- styles ----------------------------------------------------------------

const overlayStyle: React.CSSProperties = {
  position: 'fixed',
  inset: 0,
  background: 'rgba(0,0,0,0.6)',
  backdropFilter: 'blur(2px)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  zIndex: 60,
  padding: 'var(--sp-4)',
};

function bannerStyle(color: string): React.CSSProperties {
  return {
    padding: '8px 12px',
    marginBottom: 'var(--sp-3)',
    border: `1px solid ${color}33`,
    background: `${color}0f`,
    borderRadius: 'var(--radius-sm)',
    borderLeft: `2px solid ${color}`,
    color: 'var(--fg-dim)',
    fontSize: '0.8rem',
    lineHeight: 1.5,
  };
}

const monoStyle: React.CSSProperties = {
  fontFamily: 'var(--font-mono)',
  fontSize: '0.74rem',
  color: 'var(--fg)',
};

const preStyle: React.CSSProperties = {
  background: 'var(--bg)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
  padding: '6px 8px',
  whiteSpace: 'pre-wrap',
  wordBreak: 'break-word',
  maxHeight: '140px',
  overflowY: 'auto',
};
