/**
 * 增强的加载状态组件
 * 提供更丰富的加载体验，遵循UI/UX设计规范
 */

import React from 'react';
import { Loader2, RefreshCw, Download, Upload, Search, Zap, AlertCircle } from 'lucide-react';

export type LoadingType = 'default' | 'refresh' | 'download' | 'upload' | 'search' | 'processing';

interface EnhancedLoadingStateProps {
  type?: LoadingType;
  size?: 'small' | 'medium' | 'large';
  message?: string;
  progress?: number;
  showProgress?: boolean;
  className?: string;
  overlay?: boolean;
  children?: React.ReactNode;
}

export const EnhancedLoadingState: React.FC<EnhancedLoadingStateProps> = ({
  type = 'default',
  size = 'medium',
  message,
  progress,
  showProgress = false,
  className = '',
  overlay = false,
  children,
}) => {
  const getIcon = () => {
    switch (type) {
      case 'refresh':
        return <RefreshCw className="animate-spin" />;
      case 'download':
        return <Download className="animate-bounce" />;
      case 'upload':
        return <Upload className="animate-bounce" />;
      case 'search':
        return <Search className="animate-pulse" />;
      case 'processing':
        return <Zap className="animate-pulse" />;
      default:
        return <Loader2 className="animate-spin" />;
    }
  };

  const getSizeClasses = () => {
    switch (size) {
      case 'small':
        return 'w-4 h-4';
      case 'large':
        return 'w-8 h-8';
      default:
        return 'w-6 h-6';
    }
  };

  const getContainerClasses = () => {
    const baseClasses = 'flex flex-col items-center justify-center space-y-3';
    const sizeClasses = size === 'small' ? 'p-2' : size === 'large' ? 'p-8' : 'p-4';
    
    if (overlay) {
      return `${baseClasses} ${sizeClasses} absolute inset-0 bg-white bg-opacity-90 backdrop-blur-sm z-10`;
    }
    
    return `${baseClasses} ${sizeClasses} ${className}`;
  };

  const getMessageClasses = () => {
    switch (size) {
      case 'small':
        return 'text-xs text-gray-600';
      case 'large':
        return 'text-lg text-gray-700 font-medium';
      default:
        return 'text-sm text-gray-600';
    }
  };

  const getTypeMessage = () => {
    if (message) return message;
    
    switch (type) {
      case 'refresh':
        return '刷新中...';
      case 'download':
        return '下载中...';
      case 'upload':
        return '上传中...';
      case 'search':
        return '搜索中...';
      case 'processing':
        return '处理中...';
      default:
        return '加载中...';
    }
  };

  const content = (
    <div className={getContainerClasses()}>
      {/* 加载图标 */}
      <div className={`text-blue-500 ${getSizeClasses()}`}>
        {getIcon()}
      </div>

      {/* 加载消息 */}
      <div className={getMessageClasses()}>
        {getTypeMessage()}
      </div>

      {/* 进度条 */}
      {showProgress && typeof progress === 'number' && (
        <div className="w-full max-w-xs">
          <div className="flex justify-between text-xs text-gray-500 mb-1">
            <span>进度</span>
            <span>{Math.round(progress)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div
              className="bg-blue-500 h-2 rounded-full transition-all duration-300 ease-out progress-bar"
              style={{ width: `${Math.min(100, Math.max(0, progress))}%` }}
            />
          </div>
        </div>
      )}

      {/* 自定义内容 */}
      {children}
    </div>
  );

  if (overlay) {
    return (
      <div className="relative">
        {content}
      </div>
    );
  }

  return content;
};

// 骨架屏加载组件
interface SkeletonProps {
  className?: string;
  width?: string | number;
  height?: string | number;
  rounded?: boolean;
  animate?: boolean;
}

export const Skeleton: React.FC<SkeletonProps> = ({
  className = '',
  width = '100%',
  height = '1rem',
  rounded = false,
  animate = true,
}) => {
  const baseClasses = 'bg-gray-200';
  const animateClasses = animate ? 'loading-shimmer' : '';
  const roundedClasses = rounded ? 'rounded-full' : 'rounded';
  
  const style = {
    width: typeof width === 'number' ? `${width}px` : width,
    height: typeof height === 'number' ? `${height}px` : height,
  };

  return (
    <div
      className={`${baseClasses} ${animateClasses} ${roundedClasses} ${className}`}
      style={style}
    />
  );
};

// 卡片骨架屏
export const CardSkeleton: React.FC<{ className?: string }> = ({ className = '' }) => (
  <div className={`p-4 border border-gray-200 rounded-lg ${className}`}>
    <div className="space-y-3">
      <div className="flex items-center space-x-3">
        <Skeleton width={40} height={40} rounded />
        <div className="flex-1 space-y-2">
          <Skeleton height={16} width="60%" />
          <Skeleton height={12} width="40%" />
        </div>
      </div>
      <Skeleton height={12} />
      <Skeleton height={12} width="80%" />
      <div className="flex space-x-2">
        <Skeleton height={32} width={80} rounded />
        <Skeleton height={32} width={80} rounded />
      </div>
    </div>
  </div>
);

// 列表骨架屏
export const ListSkeleton: React.FC<{ 
  items?: number; 
  className?: string;
}> = ({ 
  items = 3, 
  className = '' 
}) => (
  <div className={`space-y-3 ${className}`}>
    {Array.from({ length: items }).map((_, index) => (
      <div key={index} className="flex items-center space-x-3 p-3 border border-gray-200 rounded-lg">
        <Skeleton width={48} height={48} rounded />
        <div className="flex-1 space-y-2">
          <Skeleton height={16} width="70%" />
          <Skeleton height={12} width="50%" />
        </div>
        <Skeleton width={80} height={32} rounded />
      </div>
    ))}
  </div>
);

// 表格骨架屏
export const TableSkeleton: React.FC<{ 
  rows?: number; 
  columns?: number;
  className?: string;
}> = ({ 
  rows = 5, 
  columns = 4,
  className = '' 
}) => (
  <div className={`space-y-2 ${className}`}>
    {/* 表头 */}
    <div className="grid gap-4 p-3 bg-gray-50 rounded-lg" style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}>
      {Array.from({ length: columns }).map((_, index) => (
        <Skeleton key={index} height={16} width="80%" />
      ))}
    </div>
    
    {/* 表格行 */}
    {Array.from({ length: rows }).map((_, rowIndex) => (
      <div key={rowIndex} className="grid gap-4 p-3 border border-gray-200 rounded-lg" style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}>
        {Array.from({ length: columns }).map((_, colIndex) => (
          <Skeleton key={colIndex} height={14} width={colIndex === 0 ? "90%" : "70%"} />
        ))}
      </div>
    ))}
  </div>
);

// 加载状态容器
interface LoadingContainerProps {
  loading: boolean;
  error?: string | null;
  empty?: boolean;
  emptyMessage?: string;
  loadingComponent?: React.ReactNode;
  errorComponent?: React.ReactNode;
  emptyComponent?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}

export const LoadingContainer: React.FC<LoadingContainerProps> = ({
  loading,
  error,
  empty = false,
  emptyMessage = '暂无数据',
  loadingComponent,
  errorComponent,
  emptyComponent,
  children,
  className = '',
}) => {
  if (loading) {
    return (
      <div className={className}>
        {loadingComponent || <EnhancedLoadingState />}
      </div>
    );
  }

  if (error) {
    return (
      <div className={className}>
        {errorComponent || (
          <div className="flex flex-col items-center justify-center p-8 text-center">
            <div className="text-red-500 mb-2">
              <AlertCircle className="w-8 h-8" />
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-1">加载失败</h3>
            <p className="text-sm text-gray-600">{error}</p>
          </div>
        )}
      </div>
    );
  }

  if (empty) {
    return (
      <div className={className}>
        {emptyComponent || (
          <div className="flex flex-col items-center justify-center p-8 text-center">
            <div className="text-gray-400 mb-2">
              <Search className="w-8 h-8" />
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-1">暂无内容</h3>
            <p className="text-sm text-gray-600">{emptyMessage}</p>
          </div>
        )}
      </div>
    );
  }

  return <div className={className}>{children}</div>;
};
