import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Plus, Video } from 'lucide-react'
import { ProjectService, Project } from '../services/projectService'
import ProjectCard from './ProjectCard'

const RecentProjects: React.FC = () => {
  const [recentProjects, setRecentProjects] = useState<Project[]>([])
  const [loading, setLoading] = useState(true)

  // 加载最近的项目
  useEffect(() => {
    const loadRecentProjects = async () => {
      try {
        const response = await ProjectService.getAllProjects()
        if (response.status && response.data) {
          // 按更新时间排序，取最近的3个项目
          const sortedProjects = response.data
            .sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
            .slice(0, 3)
          setRecentProjects(sortedProjects)
        }
      } catch (error) {
        console.error('Failed to load recent projects:', error)
      } finally {
        setLoading(false)
      }
    }

    loadRecentProjects()
  }, [])

  // 格式化时间显示
  const formatTimeAgo = (dateString: string): string => {
    const now = new Date()
    const date = new Date(dateString)
    const diffInMs = now.getTime() - date.getTime()
    const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60))
    const diffInDays = Math.floor(diffInHours / 24)

    if (diffInHours < 1) {
      return '刚刚'
    } else if (diffInHours < 24) {
      return `${diffInHours} 小时前`
    } else if (diffInDays < 7) {
      return `${diffInDays} 天前`
    } else {
      return date.toLocaleDateString('zh-CN')
    }
  }

  // 加载状态骨架屏
  const LoadingSkeleton = () => (
    <>
      {Array.from({ length: 3 }).map((_, index) => (
        <div key={index} className="card overflow-hidden">
          <div className="aspect-video bg-secondary-200 animate-pulse"></div>
          <div className="p-4">
            <div className="h-4 bg-secondary-200 rounded animate-pulse mb-2"></div>
            <div className="h-3 bg-secondary-200 rounded animate-pulse w-2/3"></div>
          </div>
        </div>
      ))}
    </>
  )

  // 空状态
  const EmptyState = () => (
    <div className="col-span-full text-center py-8">
      <Video className="mx-auto text-secondary-400 mb-4" size={48} />
      <p className="text-secondary-600 mb-4">还没有项目</p>
      <Link
        to="/projects"
        className="btn-primary inline-flex items-center px-2 py-1"
      >
        <Plus size={16} className="mr-2" />
        创建第一个项目
      </Link>
    </div>
  )

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-semibold text-secondary-900">最近项目</h2>
        <Link
          to="/projects"
          className="text-primary-600 hover:text-primary-700 text-sm font-medium"
        >
          查看全部
        </Link>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {loading ? (
          <LoadingSkeleton />
        ) : recentProjects.length > 0 ? (
          recentProjects.map((project) => (
            <ProjectCard
              key={project.id}
              project={project}
              formatTimeAgo={formatTimeAgo}
            />
          ))
        ) : (
          <EmptyState />
        )}
      </div>
    </div>
  )
}

export default RecentProjects
