import React, { useMemo } from 'react';
import { format } from 'date-fns';

interface VersionData {
  id: string;
  timestamp: Date;
  userId: string;
  userName: string;
  userAvatar?: string;
  data: Record<string, any>;
  changeCount: number;
}

interface VersionComparisonProps {
  versionA: VersionData;
  versionB: VersionData;
  onRestore?: (versionId: string) => void;
  onClose?: () => void;
  className?: string;
}

/**
 * Version Comparison Component
 * Side-by-side comparison of two document versions
 */
export const VersionComparison: React.FC<VersionComparisonProps> = ({
  versionA,
  versionB,
  onRestore,
  onClose,
  className = ''
}) => {
  // Calculate differences between versions
  const differences = useMemo(() => {
    const diffs: Array<{
      field: string;
      type: 'added' | 'removed' | 'modified';
      oldValue: any;
      newValue: any;
    }> = [];

    const allFields = new Set([
      ...Object.keys(versionA.data),
      ...Object.keys(versionB.data)
    ]);

    allFields.forEach(field => {
      const valueA = versionA.data[field];
      const valueB = versionB.data[field];

      if (valueA === undefined && valueB !== undefined) {
        diffs.push({ field, type: 'added', oldValue: undefined, newValue: valueB });
      } else if (valueA !== undefined && valueB === undefined) {
        diffs.push({ field, type: 'removed', oldValue: valueA, newValue: undefined });
      } else if (JSON.stringify(valueA) !== JSON.stringify(valueB)) {
        diffs.push({ field, type: 'modified', oldValue: valueA, newValue: valueB });
      }
    });

    return diffs;
  }, [versionA.data, versionB.data]);

  // Format field name for display
  const formatFieldName = (field: string) => {
    return field
      .replace(/([A-Z])/g, ' $1')
      .replace(/^./, str => str.toUpperCase())
      .trim();
  };

  // Format value for display
  const formatValue = (value: any): string => {
    if (value === null || value === undefined) {
      return '(empty)';
    }
    
    if (typeof value === 'object') {
      return JSON.stringify(value, null, 2);
    }
    
    if (typeof value === 'string' && value.length === 0) {
      return '(empty)';
    }
    
    return String(value);
  };

  // Get diff type icon and color
  const getDiffStyle = (type: 'added' | 'removed' | 'modified') => {
    switch (type) {
      case 'added':
        return { icon: '➕', color: '#4caf50', bg: '#e8f5e9' };
      case 'removed':
        return { icon: '➖', color: '#f44336', bg: '#ffebee' };
      case 'modified':
        return { icon: '📝', color: '#ff9800', bg: '#fff3e0' };
      default:
        return { icon: '📄', color: '#666', bg: '#f5f5f5' };
    }
  };

  // Render version header
  const renderVersionHeader = (version: VersionData, label: string) => (
    <div className="version-comparison__header">
      <div className="version-comparison__label">{label}</div>
      <div className="version-comparison__meta">
        <div className="version-comparison__user">
          {version.userAvatar ? (
            <img src={version.userAvatar} alt={version.userName} />
          ) : (
            <div className="version-comparison__user-initial">
              {version.userName.charAt(0).toUpperCase()}
            </div>
          )}
          <span>{version.userName}</span>
        </div>
        <div className="version-comparison__timestamp">
          {format(version.timestamp, 'MMM d, yyyy h:mm a')}
        </div>
        <div className="version-comparison__changes">
          {version.changeCount} changes
        </div>
      </div>
      {onRestore && (
        <button
          className="version-comparison__restore"
          onClick={() => onRestore(version.id)}
          title={`Restore to this version`}
        >
          Restore
        </button>
      )}
    </div>
  );

  // Render field comparison
  const renderFieldComparison = (diff: typeof differences[0]) => {
    const style = getDiffStyle(diff.type);
    
    return (
      <div 
        key={diff.field}
        className="version-comparison__field"
        style={{ borderColor: style.color }}
      >
        <div className="version-comparison__field-header">
          <span className="version-comparison__field-icon" style={{ color: style.color }}>
            {style.icon}
          </span>
          <span className="version-comparison__field-name">
            {formatFieldName(diff.field)}
          </span>
          <span className="version-comparison__field-type" style={{ color: style.color }}>
            {diff.type}
          </span>
        </div>
        
        <div className="version-comparison__field-values">
          <div className="version-comparison__value version-comparison__value--old">
            <div className="version-comparison__value-label">Version A</div>
            <pre className="version-comparison__value-content">
              {formatValue(diff.oldValue)}
            </pre>
          </div>
          
          <div className="version-comparison__value version-comparison__value--new">
            <div className="version-comparison__value-label">Version B</div>
            <pre className="version-comparison__value-content">
              {formatValue(diff.newValue)}
            </pre>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={`version-comparison ${className}`}>
      <div className="version-comparison__toolbar">
        <h2 className="version-comparison__title">Version Comparison</h2>
        {onClose && (
          <button className="version-comparison__close" onClick={onClose}>
            ✕
          </button>
        )}
      </div>

      <div className="version-comparison__versions">
        <div className="version-comparison__version">
          {renderVersionHeader(versionA, 'Version A')}
        </div>
        
        <div className="version-comparison__version">
          {renderVersionHeader(versionB, 'Version B')}
        </div>
      </div>

      <div className="version-comparison__summary">
        <div className="version-comparison__stats">
          <span className="version-comparison__stat">
            {differences.length} differences found
          </span>
          <span className="version-comparison__stat">
            {differences.filter(d => d.type === 'added').length} additions
          </span>
          <span className="version-comparison__stat">
            {differences.filter(d => d.type === 'removed').length} removals
          </span>
          <span className="version-comparison__stat">
            {differences.filter(d => d.type === 'modified').length} modifications
          </span>
        </div>
      </div>

      <div className="version-comparison__differences">
        {differences.length === 0 ? (
          <div className="version-comparison__no-differences">
            <span>🎉</span>
            <h3>No differences found</h3>
            <p>These versions contain identical data.</p>
          </div>
        ) : (
          <>
            <h3 className="version-comparison__differences-title">
              Differences ({differences.length})
            </h3>
            <div className="version-comparison__differences-list">
              {differences.map(renderFieldComparison)}
            </div>
          </>
        )}
      </div>
      
      <style jsx>{`
        .version-comparison {
          background: white;
          border: 1px solid #e0e0e0;
          border-radius: 12px;
          overflow: hidden;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .version-comparison__toolbar {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 20px;
          background: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .version-comparison__title {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          color: #333;
        }
        
        .version-comparison__close {
          background: none;
          border: none;
          font-size: 18px;
          color: #666;
          cursor: pointer;
          padding: 4px;
          border-radius: 4px;
        }
        
        .version-comparison__close:hover {
          background: #e0e0e0;
        }
        
        .version-comparison__versions {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 1px;
          background: #e0e0e0;
        }
        
        .version-comparison__version {
          background: white;
        }
        
        .version-comparison__header {
          padding: 16px;
          background: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .version-comparison__label {
          font-size: 14px;
          font-weight: 600;
          color: #4ECDC4;
          margin-bottom: 8px;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        
        .version-comparison__meta {
          display: flex;
          flex-direction: column;
          gap: 4px;
        }
        
        .version-comparison__user {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          font-weight: 500;
        }
        
        .version-comparison__user img {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          object-fit: cover;
        }
        
        .version-comparison__user-initial {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background: #4ECDC4;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          font-weight: bold;
        }
        
        .version-comparison__timestamp {
          font-size: 13px;
          color: #666;
        }
        
        .version-comparison__changes {
          font-size: 12px;
          color: #999;
        }
        
        .version-comparison__restore {
          margin-top: 8px;
          background: #4ECDC4;
          color: white;
          border: none;
          padding: 6px 12px;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          transition: background 0.2s ease;
        }
        
        .version-comparison__restore:hover {
          background: #45B7D1;
        }
        
        .version-comparison__summary {
          padding: 16px 20px;
          background: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .version-comparison__stats {
          display: flex;
          gap: 16px;
          flex-wrap: wrap;
        }
        
        .version-comparison__stat {
          font-size: 13px;
          color: #666;
          padding: 4px 8px;
          background: white;
          border-radius: 4px;
          border: 1px solid #e0e0e0;
        }
        
        .version-comparison__differences {
          padding: 20px;
        }
        
        .version-comparison__differences-title {
          margin: 0 0 16px 0;
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
        
        .version-comparison__differences-list {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }
        
        .version-comparison__field {
          border: 1px solid #e0e0e0;
          border-radius: 8px;
          overflow: hidden;
          border-left-width: 4px;
        }
        
        .version-comparison__field-header {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 12px 16px;
          background: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .version-comparison__field-icon {
          font-size: 16px;
        }
        
        .version-comparison__field-name {
          font-weight: 500;
          flex: 1;
        }
        
        .version-comparison__field-type {
          font-size: 12px;
          text-transform: uppercase;
          letter-spacing: 0.5px;
          font-weight: 600;
        }
        
        .version-comparison__field-values {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 1px;
          background: #e0e0e0;
        }
        
        .version-comparison__value {
          background: white;
          padding: 16px;
        }
        
        .version-comparison__value-label {
          font-size: 12px;
          font-weight: 600;
          color: #666;
          margin-bottom: 8px;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        
        .version-comparison__value-content {
          margin: 0;
          font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
          font-size: 13px;
          line-height: 1.4;
          white-space: pre-wrap;
          word-break: break-word;
          background: #f8f9fa;
          padding: 8px;
          border-radius: 4px;
          border: 1px solid #e0e0e0;
        }
        
        .version-comparison__value--old .version-comparison__value-content {
          background: #ffebee;
          border-color: #ffcdd2;
        }
        
        .version-comparison__value--new .version-comparison__value-content {
          background: #e8f5e9;
          border-color: #c8e6c9;
        }
        
        .version-comparison__no-differences {
          text-align: center;
          padding: 48px 20px;
          color: #666;
        }
        
        .version-comparison__no-differences span {
          font-size: 48px;
          display: block;
          margin-bottom: 16px;
        }
        
        .version-comparison__no-differences h3 {
          margin: 0 0 8px 0;
          color: #333;
        }
        
        .version-comparison__no-differences p {
          margin: 0;
          font-size: 14px;
        }
        
        @media (max-width: 768px) {
          .version-comparison__versions {
            grid-template-columns: 1fr;
          }
          
          .version-comparison__field-values {
            grid-template-columns: 1fr;
          }
          
          .version-comparison__stats {
            flex-direction: column;
            gap: 8px;
          }
        }
      `}</style>
    </div>
  );
};