import { Component, createSignal, For, Show } from 'solid-js';
import type { RevisionTimelineEntry } from '../../lib/revisions/types';
import { formatChangeSummary, getChangeColor } from '../../lib/revisions/diff';

export interface RevisionTimelineProps {
  timeline: RevisionTimelineEntry[];
  selectedRevisionId?: number;
  onSelectRevision: (revisionId: number) => void;
  onCompare?: (baseId: number, targetId: number) => void;
}

export const RevisionTimeline: Component<RevisionTimelineProps> = (props) => {
  const [compareMode, setCompareMode] = createSignal(false);
  const [compareBase, setCompareBase] = createSignal<number | null>(null);

  const handleItemClick = (entry: RevisionTimelineEntry) => {
    if (compareMode()) {
      if (compareBase() === null) {
        setCompareBase(entry.revision.id);
      } else if (compareBase() !== entry.revision.id) {
        const base = compareBase()!;
        props.onCompare?.(base, entry.revision.id);
        setCompareBase(null);
        setCompareMode(false);
      }
    } else {
      props.onSelectRevision(entry.revision.id);
    }
  };

  const toggleCompareMode = () => {
    setCompareMode(!compareMode());
    setCompareBase(null);
  };

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'accepted':
        return '#22c55e';
      case 'rejected':
        return '#ef4444';
      case 'pending_review':
        return '#f59e0b';
      default:
        return '#6b7280';
    }
  };

  return (
    <div class="revision-timeline">
      <div class="timeline-header">
        <h3>Version History</h3>
        <div class="timeline-controls">
          <button
            class={`compare-btn ${compareMode() ? 'active' : ''}`}
            onClick={toggleCompareMode}
          >
            {compareMode()
              ? compareBase()
                ? `Comparing from v${compareBase()} — select target`
                : 'Select base revision'
              : 'Compare'}
          </button>
          <Show when={compareMode() && compareBase()}>
            <button class="cancel-btn" onClick={() => { setCompareMode(false); setCompareBase(null); }}>
              Cancel
            </button>
          </Show>
        </div>
      </div>

      <div class="timeline-list">
        <For each={props.timeline}>
          {(entry) => (
            <div
              class={`timeline-item ${
                props.selectedRevisionId === entry.revision.id ? 'selected' : ''
              } ${compareBase() === entry.revision.id ? 'compare-base' : ''}`}
              onClick={() => handleItemClick(entry)}
            >
              <div class="timeline-marker">
                <div
                  class="marker-dot"
                  style={{
                    background: getStatusColor(entry.revision.status),
                  }}
                />
                <div class="marker-line" />
              </div>

              <div class="timeline-content">
                <div class="timeline-title">
                  <span class="version-badge">v{entry.revision.versionNumber}</span>
                  <span class="title-text">{entry.revision.title}</span>
                  <span
                    class="status-badge"
                    style={{
                      background: getStatusColor(entry.revision.status) + '22',
                      color: getStatusColor(entry.revision.status),
                    }}
                  >
                    {entry.revision.status}
                  </span>
                </div>

                <div class="timeline-meta">
                  <span class="date">{formatDate(entry.revision.createdAt)}</span>
                  <span class="branch">{entry.revision.branchName}</span>
                </div>

                <div class="timeline-changes">
                  <span
                    class="change-count"
                    style={{ color: getChangeColor('addition') }}
                  >
                    +{entry.additions}
                  </span>
                  <span
                    class="change-count"
                    style={{ color: getChangeColor('deletion') }}
                  >
                    -{entry.deletions}
                  </span>
                  <span
                    class="change-count"
                    style={{ color: getChangeColor('modification') }}
                  >
                    ~{entry.modifications}
                  </span>
                </div>

                <Show when={entry.revision.summary}>
                  <div class="timeline-summary">{entry.revision.summary}</div>
                </Show>
              </div>
            </div>
          )}
        </For>
      </div>

      <Show when={props.timeline.length === 0}>
        <div class="empty-state">
          <p>No revisions yet. Create the first revision to start tracking changes.</p>
        </div>
      </Show>
    </div>
  );
};

export default RevisionTimeline;
