/**
 * Save Status Indicator Component
 * 
 * This component displays the current save status of the canvas.
 * It shows:
 * - Save status: "Saved" / "Saving..." / "Save Failed"
 * - Last saved time (relative, e.g., "2 minutes ago")
 * - Error message when save fails
 * - Manual "Save Now" button
 * 
 * Requirements: REQ-5.7.4
 */

'use client';

import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { 
  Save, 
  CheckCircle2, 
  AlertCircle,
  Loader2,
  Clock
} from 'lucide-react';
import { cn } from '@/utils';

interface SaveStatusIndicatorProps {
  /** Whether the canvas is currently saving */
  isSaving: boolean;
  
  /** Whether there are unsaved changes */
  isDirty?: boolean;
  
  /** Last save timestamp (Unix timestamp in milliseconds) */
  lastSavedAt?: number;
  
  /** Error message if save failed */
  error?: string | null;
  
  /** Callback to trigger manual save */
  onSaveNow?: () => void;
  
  /** Additional CSS classes */
  className?: string;
  
  /** Whether to show the "Save Now" button (default: true) */
  showSaveButton?: boolean;
  
  /** Compact mode - shows only icon and minimal text (default: false) */
  compact?: boolean;
}

/**
 * Format relative time from timestamp
 * @param timestamp Unix timestamp in milliseconds
 * @returns Relative time string (e.g., "2分钟前")
 */
function formatRelativeTime(timestamp: number): string {
  const now = Date.now();
  const diff = now - timestamp;
  
  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  
  if (seconds < 10) return '刚刚';
  if (seconds < 60) return `${seconds}秒前`;
  if (minutes === 1) return '1分钟前';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours === 1) return '1小时前';
  if (hours < 24) return `${hours}小时前`;
  if (days === 1) return '1天前';
  return `${days}天前`;
}

/**
 * Save Status Indicator Component
 * 
 * Displays the current save status of the canvas with visual feedback.
 * 
 * @example
 * ```tsx
 * // Basic usage
 * <SaveStatusIndicator 
 *   isSaving={isSaving}
 *   lastSavedAt={lastSavedAt}
 *   onSaveNow={saveImmediately}
 * />
 * 
 * // With error
 * <SaveStatusIndicator 
 *   isSaving={false}
 *   error="Failed to save canvas"
 *   onSaveNow={saveImmediately}
 * />
 * 
 * // Compact mode
 * <SaveStatusIndicator 
 *   isSaving={isSaving}
 *   lastSavedAt={lastSavedAt}
 *   compact
 * />
 * ```
 */
export function SaveStatusIndicator({
  isSaving,
  isDirty,
  lastSavedAt,
  error,
  onSaveNow,
  className,
  compact = false,
  showSaveButton = true,
}: SaveStatusIndicatorProps) {
  // Determine status
  const status = error ? 'error' : isSaving ? 'saving' : isDirty ? 'unsaved' : 'saved';

  // Only render a simple button as requested
  if (!onSaveNow) return null;

  return (
    <Button
      variant="ghost"
      size="sm"
      className={cn(
        "h-8 px-2 text-xs gap-1.5 transition-colors",
        status === 'unsaved' && "text-amber-500 hover:text-amber-600 hover:bg-amber-500/10",
        status === 'error' && "text-destructive hover:text-destructive hover:bg-destructive/10",
        status === 'saved' && "text-muted-foreground hover:text-foreground",
        className
      )}
      onClick={onSaveNow}
      disabled={isSaving}
    >
      {status === 'saving' ? (
        <Loader2 className="h-3.5 w-3.5 animate-spin" />
      ) : status === 'error' ? (
        <AlertCircle className="h-3.5 w-3.5" />
      ) : (
        <Save className="h-3.5 w-3.5" />
      )}
      
      <span>
        {status === 'saving' ? '保存中' : status === 'error' ? '重试' : '保存'}
      </span>
    </Button>
  );
}

/**
 * Toolbar Save Status Indicator
 * 
 * A minimal version designed for canvas toolbars.
 * Shows only the status icon with a tooltip.
 * 
 * @example
 * ```tsx
 * <ToolbarSaveStatus 
 *   isSaving={isSaving}
 *   lastSavedAt={lastSavedAt}
 *   onSaveNow={saveImmediately}
 * />
 * ```
 */
export function ToolbarSaveStatus({
  isSaving,
  isDirty,
  lastSavedAt,
  error,
  onSaveNow,
  className
}: Omit<SaveStatusIndicatorProps, 'compact' | 'showSaveButton'>) {
  const [relativeTime, setRelativeTime] = useState<string>('');
  
  useEffect(() => {
    if (!lastSavedAt) {
      setRelativeTime('');
      return;
    }
    
    const updateTime = () => {
      setRelativeTime(formatRelativeTime(lastSavedAt));
    };
    
    updateTime();
    const interval = setInterval(updateTime, 10000);
    
    return () => clearInterval(interval);
  }, [lastSavedAt]);
  
  const status = error ? 'error' : isSaving ? 'saving' : isDirty ? 'unsaved' : 'saved';
  
  // Build tooltip text
  let tooltipText = '';
  if (status === 'saving') {
    tooltipText = '正在保存更改...';
  } else if (status === 'unsaved') {
    tooltipText = '有未保存的更改';
  } else if (status === 'saved') {
    tooltipText = relativeTime ? `已保存 ${relativeTime}` : '所有更改已保存';
  } else if (status === 'error') {
    tooltipText = error || '保存更改失败';
  }
  
  return (
    <div className={cn('flex items-center gap-1', className)}>
      <button
        className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 hover:bg-accent transition-colors"
        title={tooltipText}
        onClick={onSaveNow}
        disabled={isSaving}
      >
        {status === 'saving' && (
          <Loader2 className="h-4 w-4 animate-spin text-blue-500" />
        )}

        {status === 'unsaved' && (
          <div className="h-2.5 w-2.5 rounded-full bg-amber-500 animate-pulse" />
        )}
        
        {status === 'saved' && (
          <CheckCircle2 className="h-4 w-4 text-green-500" />
        )}
        
        {status === 'error' && (
          <AlertCircle className="h-4 w-4 text-destructive" />
        )}
        
        <span className="text-xs font-medium">
          {status === 'saving' && '保存中...'}
          {status === 'unsaved' && '未保存'}
          {status === 'saved' && '已保存'}
          {status === 'error' && '保存失败'}
        </span>
      </button>
      
      {/* Save Now button for error or unsaved state */}
      {(status === 'error' || status === 'unsaved') && onSaveNow && (
        <Button
          variant="ghost"
          size="sm"
          className="h-7 px-2"
          onClick={onSaveNow}
        >
          <Save className="h-3 w-3 mr-1" />
          {status === 'error' ? '重试' : '保存'}
        </Button>
      )}
    </div>
  );
}

/**
 * Floating Save Status Badge
 * 
 * A floating badge that appears in the corner of the canvas.
 * Useful for non-intrusive save status indication.
 * 
 * @example
 * ```tsx
 * <FloatingSaveStatus 
 *   isSaving={isSaving}
 *   lastSavedAt={lastSavedAt}
 *   position="bottom-right"
 * />
 * ```
 */
export function FloatingSaveStatus({
  isSaving,
  lastSavedAt,
  error,
  onSaveNow,
  className,
  position = 'bottom-right'
}: SaveStatusIndicatorProps & {
  position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
}) {
  const [relativeTime, setRelativeTime] = useState<string>('');
  const [isExpanded, setIsExpanded] = useState(false);
  
  useEffect(() => {
    if (!lastSavedAt) {
      setRelativeTime('');
      return;
    }
    
    const updateTime = () => {
      setRelativeTime(formatRelativeTime(lastSavedAt));
    };
    
    updateTime();
    const interval = setInterval(updateTime, 10000);
    
    return () => clearInterval(interval);
  }, [lastSavedAt]);
  
  const status = error ? 'error' : isSaving ? 'saving' : 'saved';
  
  // Auto-expand on error
  useEffect(() => {
    if (status === 'error') {
      setIsExpanded(true);
    }
  }, [status]);
  
  // Position classes
  const positionClasses = {
    'top-left': 'top-4 left-4',
    'top-right': 'top-4 right-4',
    'bottom-left': 'bottom-4 left-4',
    'bottom-right': 'bottom-4 right-4'
  };
  
  return (
    <div
      className={cn(
        'fixed z-40 transition-all',
        positionClasses[position],
        className
      )}
      onMouseEnter={() => setIsExpanded(true)}
      onMouseLeave={() => status !== 'error' && setIsExpanded(false)}
    >
      <div
        className={cn(
          'flex items-center gap-2 rounded-full border bg-background/95 backdrop-blur-sm shadow-lg transition-all',
          isExpanded ? 'px-3 py-2' : 'p-2'
        )}
      >
        {/* Status Icon */}
        {status === 'saving' && (
          <Loader2 className="h-4 w-4 animate-spin text-blue-500" />
        )}
        
        {status === 'saved' && (
          <CheckCircle2 className="h-4 w-4 text-green-500" />
        )}
        
        {status === 'error' && (
          <AlertCircle className="h-4 w-4 text-destructive" />
        )}
        
        {/* Expanded Content */}
        {isExpanded && (
          <>
            <span className="text-sm font-medium whitespace-nowrap">
              {status === 'saving' && '保存中...'}
              {status === 'saved' && `已保存 ${relativeTime || ''}`}
              {status === 'error' && '保存失败'}
            </span>
            
            {status === 'error' && onSaveNow && (
              <Button
                variant="ghost"
                size="sm"
                className="h-6 px-2"
                onClick={onSaveNow}
              >
                <Save className="h-3 w-3" />
              </Button>
            )}
          </>
        )}
      </div>
    </div>
  );
}
