import React, { useState, useEffect } from 'react';
import { format, formatDistance } from 'date-fns';

interface Snapshot {
  id: string;
  name: string;
  description?: string;
  timestamp: Date;
  userId: string;
  userName: string;
  userAvatar?: string;
  data: Record<string, any>;
  size: number; // in bytes
  isAutomatic: boolean;
}

interface SnapshotManagerProps {
  documentId: string;
  snapshots: Snapshot[];
  onCreateSnapshot: (name: string, description?: string) => Promise<void>;
  onRestoreSnapshot: (snapshotId: string) => Promise<void>;
  onDeleteSnapshot: (snapshotId: string) => Promise<void>;
  onCompareSnapshots: (snapshot1Id: string, snapshot2Id: string) => void;
  isLoading?: boolean;
  className?: string;
}

/**
 * Snapshot Manager Component
 * Manages document snapshots and versioning
 */
export const SnapshotManager: React.FC<SnapshotManagerProps> = ({
  documentId,
  snapshots,
  onCreateSnapshot,
  onRestoreSnapshot,
  onDeleteSnapshot,
  onCompareSnapshots,
  isLoading = false,
  className = ''
}) => {
  const [isCreating, setIsCreating] = useState(false);
  const [newSnapshotName, setNewSnapshotName] = useState('');
  const [newSnapshotDescription, setNewSnapshotDescription] = useState('');
  const [selectedSnapshots, setSelectedSnapshots] = useState<Set<string>>(new Set());
  const [sortBy, setSortBy] = useState<'timestamp' | 'name' | 'size'>('timestamp');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');

  // Sort snapshots
  const sortedSnapshots = [...snapshots].sort((a, b) => {
    let comparison = 0;
    
    switch (sortBy) {
      case 'timestamp':
        comparison = a.timestamp.getTime() - b.timestamp.getTime();
        break;
      case 'name':
        comparison = a.name.localeCompare(b.name);
        break;
      case 'size':
        comparison = a.size - b.size;
        break;
    }
    
    return sortOrder === 'asc' ? comparison : -comparison;
  });

  // Handle snapshot creation
  const handleCreateSnapshot = async () => {
    if (!newSnapshotName.trim()) return;
    
    try {
      await onCreateSnapshot(newSnapshotName.trim(), newSnapshotDescription.trim() || undefined);
      setNewSnapshotName('');
      setNewSnapshotDescription('');
      setIsCreating(false);
    } catch (error) {
      console.error('Failed to create snapshot:', error);
    }
  };

  // Handle snapshot selection
  const toggleSnapshotSelection = (snapshotId: string) => {
    setSelectedSnapshots(prev => {
      const next = new Set(prev);
      if (next.has(snapshotId)) {
        next.delete(snapshotId);
      } else {
        next.add(snapshotId);
      }
      return next;
    });
  };

  // Handle comparison
  const handleCompare = () => {
    const selectedArray = Array.from(selectedSnapshots);
    if (selectedArray.length === 2) {
      onCompareSnapshots(selectedArray[0], selectedArray[1]);
    }
  };

  // Format file size
  const formatSize = (bytes: number): string => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  // Auto-generate snapshot name based on current date
  useEffect(() => {
    if (isCreating && !newSnapshotName) {
      const now = new Date();
      setNewSnapshotName(`Snapshot ${format(now, 'MMM d, yyyy h:mm a')}`);
    }
  }, [isCreating]);

  return (
    <div className={`snapshot-manager ${className}`}>
      <div className="snapshot-manager__header">
        <div className="snapshot-manager__title-section">
          <h2 className="snapshot-manager__title">Document Snapshots</h2>
          <p className="snapshot-manager__subtitle">
            {snapshots.length} snapshot{snapshots.length !== 1 ? 's' : ''} available
          </p>
        </div>
        
        <div className="snapshot-manager__actions">
          <button
            className="snapshot-manager__create"
            onClick={() => setIsCreating(true)}
            disabled={isLoading}
          >
            📸 Create Snapshot
          </button>
          
          {selectedSnapshots.size === 2 && (
            <button
              className="snapshot-manager__compare"
              onClick={handleCompare}
            >
              🔍 Compare Selected
            </button>
          )}
          
          {selectedSnapshots.size > 0 && (
            <button
              className="snapshot-manager__clear"
              onClick={() => setSelectedSnapshots(new Set())}
            >
              Clear Selection
            </button>
          )}
        </div>
      </div>

      {/* Create Snapshot Form */}
      {isCreating && (
        <div className="snapshot-manager__create-form">
          <div className="snapshot-manager__form-group">
            <label htmlFor="snapshot-name">Snapshot Name</label>
            <input
              id="snapshot-name"
              type="text"
              value={newSnapshotName}
              onChange={(e) => setNewSnapshotName(e.target.value)}
              placeholder="Enter snapshot name..."
              className="snapshot-manager__input"
            />
          </div>
          
          <div className="snapshot-manager__form-group">
            <label htmlFor="snapshot-description">Description (optional)</label>
            <textarea
              id="snapshot-description"
              value={newSnapshotDescription}
              onChange={(e) => setNewSnapshotDescription(e.target.value)}
              placeholder="Describe what changed in this version..."
              className="snapshot-manager__textarea"
              rows={3}
            />
          </div>
          
          <div className="snapshot-manager__form-actions">
            <button
              className="snapshot-manager__form-cancel"
              onClick={() => {
                setIsCreating(false);
                setNewSnapshotName('');
                setNewSnapshotDescription('');
              }}
            >
              Cancel
            </button>
            <button
              className="snapshot-manager__form-save"
              onClick={handleCreateSnapshot}
              disabled={!newSnapshotName.trim() || isLoading}
            >
              Create Snapshot
            </button>
          </div>
        </div>
      )}

      {/* Controls */}
      <div className="snapshot-manager__controls">
        <div className="snapshot-manager__sort">
          <label>Sort by:</label>
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as any)}
            className="snapshot-manager__select"
          >
            <option value="timestamp">Date</option>
            <option value="name">Name</option>
            <option value="size">Size</option>
          </select>
          
          <button
            className="snapshot-manager__sort-order"
            onClick={() => setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc')}
            title={`Sort ${sortOrder === 'asc' ? 'descending' : 'ascending'}`}
          >
            {sortOrder === 'asc' ? '↑' : '↓'}
          </button>
        </div>
        
        {selectedSnapshots.size > 0 && (
          <div className="snapshot-manager__selection-info">
            {selectedSnapshots.size} selected
          </div>
        )}
      </div>

      {/* Snapshots List */}
      <div className="snapshot-manager__list">
        {sortedSnapshots.length === 0 ? (
          <div className="snapshot-manager__empty">
            <span>📸</span>
            <h3>No snapshots yet</h3>
            <p>Create your first snapshot to save the current state of this document.</p>
          </div>
        ) : (
          sortedSnapshots.map((snapshot) => (
            <div 
              key={snapshot.id}
              className={`snapshot-manager__item ${
                selectedSnapshots.has(snapshot.id) ? 'selected' : ''
              } ${snapshot.isAutomatic ? 'automatic' : ''}`}
            >
              <div className="snapshot-manager__item-select">
                <input
                  type="checkbox"
                  checked={selectedSnapshots.has(snapshot.id)}
                  onChange={() => toggleSnapshotSelection(snapshot.id)}
                  disabled={selectedSnapshots.size >= 2 && !selectedSnapshots.has(snapshot.id)}
                />
              </div>
              
              <div className="snapshot-manager__item-content">
                <div className="snapshot-manager__item-header">
                  <div className="snapshot-manager__item-title">
                    <span className="snapshot-manager__item-name">
                      {snapshot.name}
                    </span>
                    {snapshot.isAutomatic && (
                      <span className="snapshot-manager__item-badge">Auto</span>
                    )}
                  </div>
                  
                  <div className="snapshot-manager__item-meta">
                    <span className="snapshot-manager__item-size">
                      {formatSize(snapshot.size)}
                    </span>
                    <span className="snapshot-manager__item-time">
                      {formatDistance(snapshot.timestamp, new Date(), { addSuffix: true })}
                    </span>
                  </div>
                </div>
                
                <div className="snapshot-manager__item-user">
                  {snapshot.userAvatar ? (
                    <img src={snapshot.userAvatar} alt={snapshot.userName} />
                  ) : (
                    <div className="snapshot-manager__user-initial">
                      {snapshot.userName.charAt(0).toUpperCase()}
                    </div>
                  )}
                  <span>Created by {snapshot.userName}</span>
                </div>
                
                {snapshot.description && (
                  <div className="snapshot-manager__item-description">
                    {snapshot.description}
                  </div>
                )}
                
                <div className="snapshot-manager__item-timestamp">
                  {format(snapshot.timestamp, 'MMM d, yyyy h:mm a')}
                </div>
              </div>
              
              <div className="snapshot-manager__item-actions">
                <button
                  className="snapshot-manager__item-restore"
                  onClick={() => onRestoreSnapshot(snapshot.id)}
                  title="Restore to this snapshot"
                  disabled={isLoading}
                >
                  🔄
                </button>
                
                {!snapshot.isAutomatic && (
                  <button
                    className="snapshot-manager__item-delete"
                    onClick={() => onDeleteSnapshot(snapshot.id)}
                    title="Delete this snapshot"
                    disabled={isLoading}
                  >
                    🗑️
                  </button>
                )}
              </div>
            </div>
          ))
        )}
      </div>
      
      <style jsx>{`
        .snapshot-manager {
          background: white;
          border: 1px solid #e0e0e0;
          border-radius: 12px;
          overflow: hidden;
        }
        
        .snapshot-manager__header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          padding: 20px;
          border-bottom: 1px solid #e0e0e0;
          background: #f8f9fa;
        }
        
        .snapshot-manager__title {
          margin: 0 0 4px 0;
          font-size: 20px;
          font-weight: 600;
          color: #333;
        }
        
        .snapshot-manager__subtitle {
          margin: 0;
          font-size: 14px;
          color: #666;
        }
        
        .snapshot-manager__actions {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
        }
        
        .snapshot-manager__create,
        .snapshot-manager__compare,
        .snapshot-manager__clear {
          padding: 8px 16px;
          border: none;
          border-radius: 6px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s ease;
        }
        
        .snapshot-manager__create {
          background: #4ECDC4;
          color: white;
        }
        
        .snapshot-manager__create:hover:not(:disabled) {
          background: #45B7D1;
        }
        
        .snapshot-manager__compare {
          background: #2196f3;
          color: white;
        }
        
        .snapshot-manager__compare:hover {
          background: #1976d2;
        }
        
        .snapshot-manager__clear {
          background: #f5f5f5;
          color: #666;
        }
        
        .snapshot-manager__clear:hover {
          background: #e0e0e0;
        }
        
        .snapshot-manager__create-form {
          padding: 20px;
          background: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .snapshot-manager__form-group {
          margin-bottom: 16px;
        }
        
        .snapshot-manager__form-group:last-of-type {
          margin-bottom: 20px;
        }
        
        .snapshot-manager__form-group label {
          display: block;
          margin-bottom: 6px;
          font-weight: 500;
          color: #555;
          font-size: 14px;
        }
        
        .snapshot-manager__input,
        .snapshot-manager__textarea {
          width: 100%;
          padding: 10px 12px;
          border: 1px solid #ddd;
          border-radius: 6px;
          font-size: 14px;
          background: white;
          transition: border-color 0.2s ease;
        }
        
        .snapshot-manager__input:focus,
        .snapshot-manager__textarea:focus {
          outline: none;
          border-color: #4ECDC4;
        }
        
        .snapshot-manager__textarea {
          resize: vertical;
          font-family: inherit;
        }
        
        .snapshot-manager__form-actions {
          display: flex;
          justify-content: flex-end;
          gap: 12px;
        }
        
        .snapshot-manager__form-cancel,
        .snapshot-manager__form-save {
          padding: 10px 20px;
          border: none;
          border-radius: 6px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s ease;
        }
        
        .snapshot-manager__form-cancel {
          background: #f5f5f5;
          color: #666;
        }
        
        .snapshot-manager__form-cancel:hover {
          background: #e0e0e0;
        }
        
        .snapshot-manager__form-save {
          background: #4ECDC4;
          color: white;
        }
        
        .snapshot-manager__form-save:hover:not(:disabled) {
          background: #45B7D1;
        }
        
        .snapshot-manager__form-save:disabled {
          background: #ccc;
          cursor: not-allowed;
        }
        
        .snapshot-manager__controls {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 20px;
          background: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .snapshot-manager__sort {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
        }
        
        .snapshot-manager__sort label {
          color: #666;
          font-weight: 500;
        }
        
        .snapshot-manager__select {
          padding: 4px 8px;
          border: 1px solid #ddd;
          border-radius: 4px;
          font-size: 13px;
          background: white;
        }
        
        .snapshot-manager__sort-order {
          background: none;
          border: 1px solid #ddd;
          border-radius: 4px;
          padding: 4px 8px;
          cursor: pointer;
          font-size: 14px;
          background: white;
        }
        
        .snapshot-manager__sort-order:hover {
          background: #f0f0f0;
        }
        
        .snapshot-manager__selection-info {
          font-size: 13px;
          color: #666;
          font-weight: 500;
        }
        
        .snapshot-manager__list {
          max-height: 600px;
          overflow-y: auto;
        }
        
        .snapshot-manager__empty {
          text-align: center;
          padding: 48px 20px;
          color: #666;
        }
        
        .snapshot-manager__empty span {
          font-size: 48px;
          display: block;
          margin-bottom: 16px;
        }
        
        .snapshot-manager__empty h3 {
          margin: 0 0 8px 0;
          color: #333;
        }
        
        .snapshot-manager__empty p {
          margin: 0;
          font-size: 14px;
        }
        
        .snapshot-manager__item {
          display: flex;
          align-items: flex-start;
          gap: 16px;
          padding: 16px 20px;
          border-bottom: 1px solid #f0f0f0;
          transition: background 0.2s ease;
        }
        
        .snapshot-manager__item:hover {
          background: #f8f9fa;
        }
        
        .snapshot-manager__item.selected {
          background: #e3f2fd;
          border-color: #2196f3;
        }
        
        .snapshot-manager__item.automatic {
          opacity: 0.8;
        }
        
        .snapshot-manager__item:last-child {
          border-bottom: none;
        }
        
        .snapshot-manager__item-select {
          padding-top: 2px;
        }
        
        .snapshot-manager__item-content {
          flex: 1;
        }
        
        .snapshot-manager__item-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 8px;
        }
        
        .snapshot-manager__item-title {
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .snapshot-manager__item-name {
          font-weight: 600;
          color: #333;
          font-size: 15px;
        }
        
        .snapshot-manager__item-badge {
          background: #e0e0e0;
          color: #666;
          padding: 2px 6px;
          border-radius: 3px;
          font-size: 11px;
          text-transform: uppercase;
          letter-spacing: 0.5px;
          font-weight: 500;
        }
        
        .snapshot-manager__item-meta {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: #666;
        }
        
        .snapshot-manager__item-user {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
          font-size: 13px;
          color: #666;
        }
        
        .snapshot-manager__item-user img {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          object-fit: cover;
        }
        
        .snapshot-manager__user-initial {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background: #4ECDC4;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          font-weight: bold;
        }
        
        .snapshot-manager__item-description {
          margin-bottom: 8px;
          font-size: 14px;
          color: #555;
          line-height: 1.4;
        }
        
        .snapshot-manager__item-timestamp {
          font-size: 12px;
          color: #999;
        }
        
        .snapshot-manager__item-actions {
          display: flex;
          gap: 4px;
        }
        
        .snapshot-manager__item-restore,
        .snapshot-manager__item-delete {
          background: none;
          border: none;
          padding: 6px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 16px;
          transition: background 0.2s ease;
        }
        
        .snapshot-manager__item-restore:hover {
          background: #e8f5e9;
        }
        
        .snapshot-manager__item-delete:hover {
          background: #ffebee;
        }
        
        .snapshot-manager__item-restore:disabled,
        .snapshot-manager__item-delete:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
        
        @media (max-width: 768px) {
          .snapshot-manager__header {
            flex-direction: column;
            gap: 16px;
            align-items: stretch;
          }
          
          .snapshot-manager__actions {
            justify-content: flex-start;
          }
          
          .snapshot-manager__controls {
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;
          }
          
          .snapshot-manager__item {
            flex-direction: column;
            gap: 12px;
          }
          
          .snapshot-manager__item-actions {
            align-self: flex-end;
          }
        }
      `}</style>
    </div>
  );
};