import React from 'react';
import { ModelDynamic, VideoGenerationStatus } from '../types/model';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import {
  ClockIcon,
  VideoCameraIcon,
  SparklesIcon,
  ExclamationCircleIcon,
  ArrowPathIcon
} from '@heroicons/react/24/outline';

interface ModelDynamicListProps {
  dynamics: ModelDynamic[];
  onRefresh: () => void;
  loading?: boolean;
  error?: string | null;
}

const ModelDynamicList: React.FC<ModelDynamicListProps> = ({
  dynamics,
  onRefresh,
  loading = false,
  error = null
}) => {
  const formatDate = (dateString: string) => {
    try {
      return formatDistanceToNow(new Date(dateString), {
        addSuffix: true,
        locale: zhCN
      });
    } catch (error) {
      return '未知时间';
    }
  };

  const getVideoStatusIcon = (status: VideoGenerationStatus) => {
    switch (status) {
      case VideoGenerationStatus.Pending:
        return <ClockIcon className="h-4 w-4 text-gray-500" />;
      case VideoGenerationStatus.Generating:
        return <SparklesIcon className="h-4 w-4 text-yellow-500 animate-pulse" />;
      case VideoGenerationStatus.Completed:
        return <VideoCameraIcon className="h-4 w-4 text-green-500" />;
      case VideoGenerationStatus.Failed:
        return <ExclamationCircleIcon className="h-4 w-4 text-red-500" />;
    }
  };

  // 错误状态
  if (error) {
    return (
      <div className="text-center py-16">
        <div className="max-w-md mx-auto">
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <ExclamationCircleIcon className="h-8 w-8 text-red-500" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
          <p className="text-gray-600 mb-6">{error}</p>
          <button
            onClick={onRefresh}
            className="px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  // 加载状态
  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="w-5 h-5 bg-gray-200 rounded animate-pulse"></div>
            <div className="w-20 h-5 bg-gray-200 rounded animate-pulse"></div>
          </div>
          <div className="w-16 h-8 bg-gray-200 rounded animate-pulse"></div>
        </div>
        <div className="grid gap-4">
          {[...Array(3)].map((_, index) => (
            <div key={index} className="bg-white rounded-xl border border-gray-200 p-5 animate-pulse">
              <div className="flex justify-between items-start mb-4">
                <div className="flex-1">
                  <div className="w-32 h-4 bg-gray-200 rounded mb-2"></div>
                  <div className="w-full h-3 bg-gray-200 rounded"></div>
                </div>
                <div className="w-16 h-3 bg-gray-200 rounded"></div>
              </div>
              <div className="w-full h-20 bg-gray-200 rounded mb-4"></div>
              <div className="w-full h-32 bg-gray-200 rounded"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // 空状态
  if (dynamics.length === 0) {
    return (
      <div className="text-center py-16 animate-fade-in">
        <div className="max-w-md mx-auto">
          <div className="w-20 h-20 bg-gradient-to-br from-primary-100 to-primary-200 rounded-2xl flex items-center justify-center mx-auto mb-6">
            <SparklesIcon className="h-10 w-10 text-primary-600" />
          </div>
          <h3 className="text-xl font-semibold text-gray-900 mb-2">暂无动态</h3>
          <p className="text-gray-600 mb-8">
            点击"生成视频"按钮，创建您的第一个AI视频动态
          </p>
          <div className="flex flex-col sm:flex-row gap-3 justify-center">
            <button
              onClick={onRefresh}
              className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              刷新列表
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 优化的头部操作区 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <SparklesIcon className="h-5 w-5 text-primary-600" />
          <h3 className="text-lg font-semibold text-gray-900">动态列表</h3>
          <span className="text-sm text-gray-500">({dynamics.length})</span>
        </div>
        <button
          onClick={onRefresh}
          disabled={loading}
          className="flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <ArrowPathIcon className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
          {loading ? '刷新中...' : '刷新'}
        </button>
      </div>

      {/* 优化的动态列表 - 采用更紧凑的卡片布局 */}
      <div className="grid gap-4">
        {dynamics.map((dynamic, index) => (
          <div
            key={dynamic.id}
            className="dynamic-card overflow-hidden animate-fade-in-up"
            style={{ animationDelay: `${index * 0.1}s` }}
          >
            {/* 优化的动态内容 - 更紧凑的布局 */}
            <div className="p-5">
              <div className="flex items-start gap-4 mb-4">
                {/* 优化的左侧缩略图 */}
                <div className="flex-shrink-0">
                  <div className="thumbnail-container w-16 h-16 border border-gray-200 shadow-sm">
                    <img
                      src={dynamic.source_image_path}
                      alt="源图片"
                      className="w-full h-full object-cover hover:scale-110 transition-transform duration-300"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent opacity-0 hover:opacity-100 transition-opacity duration-200"></div>
                  </div>
                </div>

                {/* 优化的右侧内容区 */}
                <div className="flex-1 min-w-0">
                  {/* 标题和状态 */}
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-primary-500 rounded-full"></div>
                      <h4 className="text-base font-semibold text-gray-900 truncate">
                        {dynamic.title || '动态'}
                      </h4>
                    </div>
                    <div className="flex items-center gap-1 text-xs text-gray-500 bg-gray-50 px-2 py-1 rounded-full">
                      <VideoCameraIcon className="h-3 w-3" />
                      <span>{dynamic.generated_videos.filter(v => v.status === VideoGenerationStatus.Completed).length}/{dynamic.video_count}</span>
                    </div>
                  </div>

                  {/* 描述文本 */}
                  <p className="text-sm text-gray-600 line-clamp-2 mb-2">{dynamic.description}</p>

                  {/* 提示词预览 */}
                  <div className="bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg p-2 mb-2">
                    <p className="text-xs text-gray-700 line-clamp-1">{dynamic.prompt}</p>
                  </div>

                  {/* 时间信息 */}
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-gray-500">
                      {formatDate(dynamic.created_at)}
                    </span>
                  </div>
                </div>
              </div>

              {/* 优化的视频网格 - 与左右布局保持一致 */}
              {dynamic.generated_videos.length > 0 && (
                <div className="border-t border-gray-100 pt-4">
                  <div className="text-sm font-medium text-gray-700 mb-3 flex items-center gap-2">
                    <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                    <span>生成视频</span>
                    <span className="text-xs text-gray-500 bg-green-50 px-2 py-0.5 rounded-full">
                      {dynamic.generated_videos.filter(v => v.status === VideoGenerationStatus.Completed).length}/{dynamic.video_count}
                    </span>
                  </div>
                  <div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
                    {dynamic.generated_videos.map((video) => (
                      <div
                        key={video.id}
                        className="relative aspect-video bg-gray-100 rounded-lg overflow-hidden border border-gray-200 group hover:border-primary-300 hover:shadow-lg transition-all duration-300 cursor-pointer transform hover:scale-[1.02]"
                      >
                        {/* 视频缩略图 */}
                        {video.thumbnail_path ? (
                          <img
                            src={video.thumbnail_path}
                            alt="视频缩略图"
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <VideoCameraIcon className="h-8 w-8 text-gray-400" />
                          </div>
                        )}

                        {/* 状态指示器 */}
                        <div className="absolute top-2 right-2">
                          {getVideoStatusIcon(video.status)}
                        </div>

                        {/* 进度指示器 */}
                        {video.status === VideoGenerationStatus.Generating && video.generation_progress !== undefined && (
                          <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-200">
                            <div
                              className="h-full bg-yellow-500"
                              style={{ width: `${video.generation_progress}%` }}
                            ></div>
                          </div>
                        )}

                        {/* 优化的悬停覆盖层 */}
                        {video.status === VideoGenerationStatus.Completed && (
                          <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-all duration-300 flex items-center justify-center">
                            <button className="text-white text-sm font-medium px-4 py-2 bg-white/20 hover:bg-white/30 rounded-lg backdrop-blur-sm border border-white/20 transition-all duration-200 transform hover:scale-105">
                              <div className="flex items-center gap-2">
                                <VideoCameraIcon className="h-4 w-4" />
                                播放
                              </div>
                            </button>
                          </div>
                        )}

                        {/* 错误信息 */}
                        {video.status === VideoGenerationStatus.Failed && video.error_message && (
                          <div className="absolute inset-0 bg-red-500/10 flex items-center justify-center">
                            <div className="text-xs text-red-600 text-center px-2">
                              {video.error_message}
                            </div>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ModelDynamicList;
