/**
 * Version History Panel Component
 * Displays document snapshots and allows restoration
 */

import { Component, createSignal, createEffect, For, onMount } from 'solid-js';
import { ChangeTracker, Snapshot } from '../../lib/collaboration/change-tracker';

export interface VersionHistoryPanelProps {
  changeTracker: ChangeTracker;
  onRestore?: (snapshot: Snapshot) => void;
  onClose?: () => void;
}

export const VersionHistoryPanel: Component<VersionHistoryPanelProps> = (props) => {
  const [snapshots, setSnapshots] = createSignal<Snapshot[]>([]);
  const [selectedSnapshot, setSelectedSnapshot] = createSignal<Snapshot | null>(null);
  const [isLoading, setIsLoading] = createSignal(true);
  const [isExpanded, setIsExpanded] = createSignal(true);

  onMount(() => {
    refreshSnapshots();
  });

  const refreshSnapshots = () => {
    setIsLoading(true);
    const allSnapshots = props.changeTracker.getSnapshots();
    setSnapshots(allSnapshots.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime()));
    setIsLoading(false);
  };

  const handleSelectSnapshot = (snapshot: Snapshot) => {
    setSelectedSnapshot(snapshot);
  };

  const handleRestore = () => {
    const snapshot = selectedSnapshot();
    if (snapshot) {
      props.changeTracker.restoreSnapshot(snapshot);
      if (props.onRestore) {
        props.onRestore(snapshot);
      }
    }
  };

  const handleCreateSnapshot = () => {
    const description = prompt('Snapshot description (optional):') || undefined;
    props.changeTracker.createSnapshot(description);
    refreshSnapshots();
  };

  const formatTimestamp = (date: Date): string => {
    return new Intl.DateTimeFormat('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    }).format(date);
  };

  const formatRelativeTime = (date: Date): string => {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    return `${diffDays}d ago`;
  };

  return (
    <div class={`version-history-panel ${isExpanded() ? 'expanded' : 'collapsed'}`}>
      <div class="version-history-header">
        <h3>Version History</h3>
        <div class="version-history-actions">
          <button onClick={handleCreateSnapshot} class="btn-create-snapshot" title="Create snapshot">
            📸
          </button>
          <button onClick={refreshSnapshots} class="btn-refresh" title="Refresh">
            🔄
          </button>
          <button onClick={() => setIsExpanded(!isExpanded())} class="btn-collapse">
            {isExpanded() ? '◀' : '▶'}
          </button>
        </div>
      </div>

      {isExpanded() && (
        <div class="version-history-content">
          {isLoading() ? (
            <div class="loading">Loading...</div>
          ) : snapshots().length === 0 ? (
            <div class="empty-state">
              <p>No snapshots yet</p>
              <p class="hint">Click 📸 to create your first snapshot</p>
            </div>
          ) : (
            <div class="snapshot-list">
              <For each={snapshots()}>
                {(snapshot) => (
                  <div
                    class={`snapshot-item ${selectedSnapshot()?.id === snapshot.id ? 'selected' : ''}`}
                    onClick={() => handleSelectSnapshot(snapshot)}
                  >
                    <div class="snapshot-info">
                      <div class="snapshot-description">
                        {snapshot.description || 'Untitled snapshot'}
                      </div>
                      <div class="snapshot-metadata">
                        <span class="snapshot-time">{formatTimestamp(snapshot.timestamp)}</span>
                        <span class="snapshot-relative">{formatRelativeTime(snapshot.timestamp)}</span>
                      </div>
                      <div class="snapshot-author">
                        by {snapshot.userName}
                      </div>
                    </div>
                    <div class="snapshot-changes">
                      {snapshot.changes.length} changes
                    </div>
                  </div>
                )}
              </For>
            </div>
          )}

          {selectedSnapshot() && (
            <div class="snapshot-preview">
              <h4>Preview</h4>
              <div class="snapshot-details">
                <p><strong>Created:</strong> {formatTimestamp(selectedSnapshot()!.timestamp)}</p>
                <p><strong>Author:</strong> {selectedSnapshot()!.userName}</p>
                <p><strong>Changes:</strong> {selectedSnapshot()!.changes.length}</p>
                {selectedSnapshot()!.description && (
                  <p><strong>Description:</strong> {selectedSnapshot()!.description}</p>
                )}
              </div>
              <button onClick={handleRestore} class="btn-restore">
                Restore this version
              </button>
            </div>
          )}
        </div>
      )}

      <style>{`
        .version-history-panel {
          position: fixed;
          right: 0;
          top: 0;
          bottom: 0;
          width: 320px;
          background: white;
          border-left: 1px solid #e0e0e0;
          box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
          z-index: 1000;
          display: flex;
          flex-direction: column;
          transition: transform 0.3s ease;
        }

        .version-history-panel.collapsed {
          transform: translateX(280px);
        }

        .version-history-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          border-bottom: 1px solid #e0e0e0;
          background: #f5f5f5;
        }

        .version-history-header h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
        }

        .version-history-actions {
          display: flex;
          gap: 8px;
        }

        .version-history-actions button {
          padding: 4px 8px;
          border: 1px solid #ccc;
          border-radius: 4px;
          background: white;
          cursor: pointer;
          font-size: 14px;
        }

        .version-history-actions button:hover {
          background: #f0f0f0;
        }

        .version-history-content {
          flex: 1;
          overflow-y: auto;
          padding: 12px;
        }

        .loading {
          text-align: center;
          padding: 20px;
          color: #666;
        }

        .empty-state {
          text-align: center;
          padding: 40px 20px;
          color: #999;
        }

        .empty-state .hint {
          font-size: 12px;
          margin-top: 8px;
        }

        .snapshot-list {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .snapshot-item {
          padding: 12px;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .snapshot-item:hover {
          border-color: #3b82f6;
          background: #f0f7ff;
        }

        .snapshot-item.selected {
          border-color: #3b82f6;
          background: #e0efff;
        }

        .snapshot-info {
          margin-bottom: 8px;
        }

        .snapshot-description {
          font-weight: 500;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .snapshot-metadata {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: #666;
          margin-bottom: 4px;
        }

        .snapshot-author {
          font-size: 12px;
          color: #888;
        }

        .snapshot-changes {
          font-size: 11px;
          color: #999;
          background: #f0f0f0;
          padding: 2px 6px;
          border-radius: 4px;
          display: inline-block;
        }

        .snapshot-preview {
          margin-top: 16px;
          padding: 16px;
          border-top: 1px solid #e0e0e0;
          background: #fafafa;
        }

        .snapshot-preview h4 {
          margin: 0 0 12px 0;
          font-size: 14px;
          font-weight: 600;
        }

        .snapshot-details p {
          margin: 6px 0;
          font-size: 13px;
        }

        .btn-restore {
          width: 100%;
          padding: 10px;
          margin-top: 12px;
          border: none;
          border-radius: 6px;
          background: #3b82f6;
          color: white;
          font-weight: 500;
          cursor: pointer;
          transition: background 0.2s ease;
        }

        .btn-restore:hover {
          background: #2563eb;
        }
      `}</style>
    </div>
  );
};

export default VersionHistoryPanel;
