// ============================================================================
// Enhanced UI Components for DIGIFY Online Meeting
// Notification System, Confirmation Dialogs, and Duplicate Checking
// ============================================================================

// ============================================================================
// Notification System
// ============================================================================

const NotificationContext = React.createContext();

function NotificationProvider({ children }) {
  const [notifications, setNotifications] = React.useState([]);

  const showNotification = React.useCallback((message, type = 'info', duration = 5000) => {
    const id = Date.now();
    const notification = { id, message, type, duration };
    
    setNotifications(prev => [...prev, notification]);

    if (duration > 0) {
      setTimeout(() => {
        setNotifications(prev => prev.filter(n => n.id !== id));
      }, duration);
    }

    return id;
  }, []);

  const hideNotification = React.useCallback((id) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  }, []);

  const showSuccess = React.useCallback((message, duration) => 
    showNotification(message, 'success', duration), [showNotification]);
  
  const showError = React.useCallback((message, duration) => 
    showNotification(message, 'error', duration), [showNotification]);
  
  const showWarning = React.useCallback((message, duration) => 
    showNotification(message, 'warning', duration), [showNotification]);
  
  const showInfo = React.useCallback((message, duration) => 
    showNotification(message, 'info', duration), [showNotification]);

  const value = {
    notifications,
    showNotification,
    hideNotification,
    showSuccess,
    showError,
    showWarning,
    showInfo,
  };

  return (
    <NotificationContext.Provider value={value}>
      {children}
      <NotificationContainer notifications={notifications} onClose={hideNotification} />
    </NotificationContext.Provider>
  );
}

function NotificationContainer({ notifications, onClose }) {
  return (
    <div className="fixed top-4 right-4 z-50 space-y-2" style={{maxWidth: '400px'}}>
      {notifications.map(notification => (
        <Notification
          key={notification.id}
          {...notification}
          onClose={() => onClose(notification.id)}
        />
      ))}
    </div>
  );
}

function Notification({ id, message, type, onClose }) {
  const typeIcons = {
    success: 'fa-check-circle',
    error: 'fa-exclamation-circle',
    warning: 'fa-exclamation-triangle',
    info: 'fa-info-circle',
  };

  return (
    <div className={`sketch-toast sketch-toast--${type}`} style={{ animation: 'slideIn 0.3s ease-out' }}>
      <i className={`fas ${typeIcons[type]} text-xl mt-0.5`}></i>
      <div className="flex-1">
        <p className="font-semibold">{message}</p>
      </div>
      <button
        onClick={onClose}
        className="sketch-toast__close"
        aria-label="Close notification"
      >
        <i className="fas fa-times"></i>
      </button>
    </div>
  );
}

// Hook to use notifications
function useNotifications() {
  const context = React.useContext(NotificationContext);
  if (!context) {
    throw new Error('useNotifications must be used within NotificationProvider');
  }
  return context;
}

// ============================================================================
// Confirmation Dialog Component
// ============================================================================

function ConfirmDialog({ isOpen, title, message, onConfirm, onCancel, confirmText = 'Confirm', cancelText = 'Cancel', type = 'warning' }) {
  if (!isOpen) return null;

  const typeVariants = {
    warning: 'sketch-button--secondary',
    danger: 'sketch-button--danger',
    info: 'sketch-button--secondary',
    success: 'sketch-button--success',
  };

  const typeIcons = {
    warning: 'fa-exclamation-triangle text-yellow-500',
    danger: 'fa-exclamation-circle text-red-500',
    info: 'fa-info-circle text-blue-500',
    success: 'fa-check-circle text-emerald-500',
  };

  return (
    <div className="fixed inset-0 sketch-overlay flex items-center justify-center z-50 animate-fade-in">
      <div className="sketch-modal max-w-md w-full mx-4 p-6 animate-scale-in">
        <div className="flex items-start gap-4 mb-4">
          <i className={`fas ${typeIcons[type]} text-3xl`}></i>
          <div className="flex-1">
            <h3 className="text-xl font-bold sketch-heading mb-2">{title}</h3>
            <p className="text-slate-500">{message}</p>
          </div>
        </div>
        <div className="flex flex-wrap gap-3 mt-6">
          <button
            onClick={onCancel}
            className="sketch-button sketch-button--ghost flex-1"
          >
            {cancelText}
          </button>
          <button
            onClick={onConfirm}
            className={`sketch-button ${typeVariants[type] ?? 'sketch-button--primary'} flex-1`}
          >
            {confirmText}
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// Loading Overlay Component
// ============================================================================

function LoadingOverlay({ message = 'Loading...', visible = true }) {
  if (!visible) return null;

  return (
    <div className="fixed inset-0 sketch-overlay flex items-center justify-center z-50">
      <div className="sketch-modal p-8 flex flex-col items-center space-y-4">
        <i className="fas fa-spinner fa-spin text-5xl text-emerald-500"></i>
        <p className="text-xl sketch-heading">{message}</p>
      </div>
    </div>
  );
}

// ============================================================================
// Meeting Conflict Warning Component
// ============================================================================

function MeetingConflictWarning({ conflicts }) {
  if (!conflicts || conflicts.length === 0) return null;

  return (
    <div className="sketch-warning-banner mb-4">
      <i className="fas fa-exclamation-triangle text-xl mt-1"></i>
      <div className="flex-1">
        <h4 className="font-semibold mb-1">Time conflict detected</h4>
        <p className="text-sm mb-2">
          This meeting overlaps with {conflicts.length} existing meeting{conflicts.length > 1 ? 's' : ''}:
        </p>
        <ul className="list-disc list-inside space-y-1 text-sm">
          {conflicts.map((conflict, index) => (
            <li key={index}>
              <strong>{conflict.title}</strong> — {new Date(conflict.start_time).toLocaleString()}
            </li>
          ))}
        </ul>
        <p className="text-xs mt-2 opacity-80">
          <i className="fas fa-info-circle mr-1"></i>
          You can continue, but simultaneous attendance won't be possible.
        </p>
      </div>
    </div>
  );
}

// ============================================================================
// Error Boundary Component
// ============================================================================

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error('Error caught by boundary:', error, errorInfo);
    this.setState({ error, errorInfo });
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen sketch-background px-4">
          <div className="sketch-card max-w-2xl w-full mx-auto p-8">
            <div className="flex items-start gap-4 mb-4">
              <i className="fas fa-exclamation-triangle text-emerald-500 text-3xl"></i>
              <div>
                <h1 className="sketch-heading text-2xl">Something went wrong</h1>
                <p className="text-slate-500">We encountered an unexpected error.</p>
              </div>
            </div>

            {this.state.error && (
              <div className="sketch-alert sketch-alert--danger mb-4">
                <i className="fas fa-bug mr-2"></i>
                <span className="font-mono text-sm break-all">{this.state.error.toString()}</span>
              </div>
            )}

            <div className="flex flex-wrap gap-3">
              <button
                onClick={() => window.location.reload()}
                className="sketch-button sketch-button--primary flex-1"
              >
                <i className="fas fa-redo"></i>
                Reload Page
              </button>
              <button
                onClick={() => this.setState({ hasError: false, error: null, errorInfo: null })}
                className="sketch-button sketch-button--ghost flex-1"
              >
                Try Again
              </button>
            </div>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

// ============================================================================
// CSS Animations (injected into document)
// ============================================================================

const animationStyles = `
  @keyframes slideIn {
    from {
      transform: translateX(400px);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }

  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }

  @keyframes scaleIn {
    from {
      transform: scale(0.9);
      opacity: 0;
    }
    to {
      transform: scale(1);
      opacity: 1;
    }
  }

  .animate-slide-in {
    animation: slideIn 0.3s ease-out;
  }

  .animate-fade-in {
    animation: fadeIn 0.2s ease-out;
  }

  .animate-scale-in {
    animation: scaleIn 0.2s ease-out;
  }
`;

// Inject animations
if (typeof document !== 'undefined') {
  const style = document.createElement('style');
  style.textContent = animationStyles;
  document.head.appendChild(style);
}

// Export components
window.EnhancedComponents = {
  NotificationProvider,
  useNotifications,
  ConfirmDialog,
  LoadingOverlay,
  MeetingConflictWarning,
  ErrorBoundary,
};
