/**
 * Conflict Detection Alert Component
 * Displays toast notifications when merge conflicts occur
 */

import { Component, createSignal, createEffect, For, onMount } from 'solid-js';
import { Conflict, MergeLogic, ConflictEvent } from '../../lib/collaboration/merge-logic';

export interface ConflictAlert {
  id: string;
  conflict: Conflict;
  timestamp: Date;
  dismissed: boolean;
}

export interface ConflictDetectionAlertsProps {
  mergeLogic?: MergeLogic;
  onResolve?: (conflictId: string, strategy: 'accept-local' | 'accept-remote' | 'manual') => void;
  maxVisible?: number;
  autoDismissMs?: number;
}

export const ConflictDetectionAlerts: Component<ConflictDetectionAlertsProps> = (
  props
) => {
  const [alerts, setAlerts] = createSignal<ConflictAlert[]>([]);
  const [isExpanded, setIsExpanded] = createSignal(false);

  const maxVisible = props.maxVisible ?? 3;
  const autoDismissMs = props.autoDismissMs ?? 10000; // 10 seconds

  // Listen for conflict events from MergeLogic
  onMount(() => {
    if (props.mergeLogic) {
      props.mergeLogic.onConflict((event: ConflictEvent) => {
        if (event.type === 'conflict-detected' && event.conflict) {
          addConflict(event.conflict);
        }
      });
    }
  });

  /**
   * Add a conflict alert
   */
  const addConflict = (conflict: Conflict): void => {
    const alert: ConflictAlert = {
      id: `conflict-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      conflict,
      timestamp: new Date(),
      dismissed: false,
    };

    setAlerts((prev) => [alert, ...prev]);

    // Auto-dismiss after timeout
    if (autoDismissMs > 0) {
      setTimeout(() => {
        dismissAlert(alert.id);
      }, autoDismissMs);
    }
  };

  /**
   * Dismiss an alert
   */
  const dismissAlert = (alertId: string): void => {
    setAlerts((prev) => prev.filter((a) => a.id !== alertId));
  };

  /**
   * Resolve a conflict
   */
  const resolveConflict = (
    alertId: string,
    strategy: 'accept-local' | 'accept-remote' | 'manual'
  ): void => {
    const alert = alerts().find((a) => a.id === alertId);
    if (alert && props.onResolve) {
      props.onResolve(alert.conflict.id, strategy);
      dismissAlert(alertId);
    }
  };

  /**
   * Get conflict type icon
   */
  const getConflictIcon = (type: string): string => {
    switch (type) {
      case 'concurrent-edit':
        return '✏️';
      case 'format-conflict':
        return '🎨';
      case 'structure-conflict':
        return '📐';
      default:
        return '⚠️';
    }
  };

  /**
   * Get conflict type label
   */
  const getConflictLabel = (type: string): string => {
    switch (type) {
      case 'concurrent-edit':
        return 'Concurrent Edit';
      case 'format-conflict':
        return 'Format Conflict';
      case 'structure-conflict':
        return 'Structure Conflict';
      default:
        return 'Conflict';
    }
  };

  /**
   * Format timestamp
   */
  const formatTime = (date: Date): string => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  /**
   * Clear all alerts
   */
  const clearAll = (): void => {
    setAlerts([]);
  };

  return (
    <div class="conflict-detection-alerts">
      <For each={alerts().slice(0, maxVisible)}>
        {(alert) => (
          <div class={`conflict-alert ${alert.dismissed ? 'dismissed' : ''}`}>
            <div class="conflict-alert-header">
              <span class="conflict-icon">
                {getConflictIcon(alert.conflict.type)}
              </span>
              <span class="conflict-label">
                {getConflictLabel(alert.conflict.type)}
              </span>
              <span class="conflict-time">{formatTime(alert.timestamp)}</span>
              <button
                class="conflict-dismiss"
                onClick={() => dismissAlert(alert.id)}
              >
                ×
              </button>
            </div>
            <div class="conflict-alert-body">
              <p class="conflict-description">
                Edit conflict detected between your changes and{' '}
                <strong>{alert.conflict.remoteChange.userName}</strong>
              </p>
              <div class="conflict-actions">
                <button
                  class="btn btn-accept-local"
                  onClick={() =>
                    resolveConflict(alert.id, 'accept-local')
                  }
                >
                  Keep Mine
                </button>
                <button
                  class="btn btn-accept-remote"
                  onClick={() =>
                    resolveConflict(alert.id, 'accept-remote')
                  }
                >
                  Accept Theirs
                </button>
                <button
                  class="btn btn-manual"
                  onClick={() => resolveConflict(alert.id, 'manual')}
                >
                  Review
                </button>
              </div>
            </div>
          </div>
        )}
      </For>

      {alerts().length > maxVisible && (
        <div class="conflict-alert-more">
          +{alerts().length - maxVisible} more conflicts
          <button onClick={() => setIsExpanded(!isExpanded())}>
            {isExpanded() ? '▲' : '▼'}
          </button>
        </div>
      )}

      {isExpanded() && (
        <div class="conflict-alert-expanded">
          <For each={alerts().slice(maxVisible)}>
            {(alert) => (
              <div class="conflict-alert compact">
                <div class="conflict-alert-header">
                  <span class="conflict-icon">
                    {getConflictIcon(alert.conflict.type)}
                  </span>
                  <span class="conflict-label">
                    {getConflictLabel(alert.conflict.type)}
                  </span>
                  <button
                    class="conflict-dismiss"
                    onClick={() => dismissAlert(alert.id)}
                  >
                    ×
                  </button>
                </div>
              </div>
            )}
          </For>
        </div>
      )}

      {alerts().length > 0 && (
        <button class="conflict-clear-all" onClick={clearAll}>
          Clear All
        </button>
      )}

      <style>{`
        .conflict-detection-alerts {
          position: fixed;
          bottom: 20px;
          right: 20px;
          z-index: 9999;
          display: flex;
          flex-direction: column;
          gap: 12px;
          max-width: 400px;
        }

        .conflict-alert {
          background: white;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          border-left: 4px solid #f59e0b;
          padding: 12px 16px;
          animation: slideIn 0.3s ease;
          transition: all 0.3s ease;
        }

        .conflict-alert.dismissed {
          opacity: 0;
          transform: translateX(100%);
        }

        .conflict-alert.compact {
          padding: 8px 12px;
          font-size: 13px;
        }

        @keyframes slideIn {
          from {
            opacity: 0;
            transform: translateX(100%);
          }
          to {
            opacity: 1;
            transform: translateX(0);
          }
        }

        .conflict-alert-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
        }

        .conflict-icon {
          font-size: 16px;
        }

        .conflict-label {
          font-weight: 600;
          font-size: 14px;
          color: #1f2937;
        }

        .conflict-time {
          font-size: 12px;
          color: #9ca3af;
          margin-left: auto;
        }

        .conflict-dismiss {
          background: none;
          border: none;
          font-size: 20px;
          color: #9ca3af;
          cursor: pointer;
          padding: 0 4px;
          line-height: 1;
        }

        .conflict-dismiss:hover {
          color: #4b5563;
        }

        .conflict-alert-body {
          margin-top: 8px;
        }

        .conflict-description {
          margin: 0 0 12px 0;
          font-size: 13px;
          color: #4b5563;
          line-height: 1.5;
        }

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

        .btn {
          padding: 6px 12px;
          border: none;
          border-radius: 4px;
          font-size: 12px;
          font-weight: 500;
          cursor: pointer;
          transition: background 0.2s ease;
        }

        .btn-accept-local {
          background: #3b82f6;
          color: white;
        }

        .btn-accept-local:hover {
          background: #2563eb;
        }

        .btn-accept-remote {
          background: #10b981;
          color: white;
        }

        .btn-accept-remote:hover {
          background: #059669;
        }

        .btn-manual {
          background: #f3f4f6;
          color: #374151;
        }

        .btn-manual:hover {
          background: #e5e7eb;
        }

        .conflict-alert-more {
          background: #fef3c7;
          border: 1px solid #f59e0b;
          border-radius: 6px;
          padding: 8px 12px;
          font-size: 13px;
          color: #92400e;
          display: flex;
          justify-content: space-between;
          align-items: center;
          cursor: pointer;
        }

        .conflict-alert-more button {
          background: none;
          border: none;
          cursor: pointer;
          font-size: 14px;
        }

        .conflict-alert-expanded {
          background: white;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          margin-top: 8px;
          overflow: hidden;
        }

        .conflict-clear-all {
          margin-top: 8px;
          padding: 8px 16px;
          background: #f3f4f6;
          border: none;
          border-radius: 6px;
          font-size: 13px;
          color: #374151;
          cursor: pointer;
          transition: background 0.2s ease;
        }

        .conflict-clear-all:hover {
          background: #e5e7eb;
        }
      `}</style>
    </div>
  );
};

export default ConflictDetectionAlerts;
