import React, { useEffect, useState } from 'react';
import { Project } from '../types/project';
import { MaterialStats } from '../types/material';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { invoke } from '@tauri-apps/api/core';
import {
  Folder,
  MoreVertical,
  Edit3,
  Trash2,
  ExternalLink,
  Calendar,
  MapPin,
  FolderOpen,
  FileVideo,
  FileAudio,
  FileImage,
  File,
  BarChart3
} from 'lucide-react';

interface ProjectCardProps {
  project: Project;
  onOpen: (project: Project) => void;
  onEdit: (project: Project) => void;
  onDelete: (id: string) => void;
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/**
 * 项目卡片组件
 * 遵循简洁大方的设计风格
 */
export const ProjectCard: React.FC<ProjectCardProps> = ({
  project,
  onOpen,
  onEdit,
  onDelete
}) => {
  const [showMenu, setShowMenu] = React.useState(false);
  const [stats, setStats] = useState<MaterialStats | null>(null);
  const [isLoadingStats, setIsLoadingStats] = useState(false);
  const menuRef = React.useRef<HTMLDivElement>(null);

  // 加载项目统计信息
  useEffect(() => {
    const loadStats = async () => {
      setIsLoadingStats(true);
      try {
        const projectStats = await invoke<MaterialStats>('get_project_material_stats', {
          projectId: project.id
        });
        setStats(projectStats);
      } catch (error) {
        console.error('加载项目统计失败:', error);
        // 静默失败，不影响卡片显示
      } finally {
        setIsLoadingStats(false);
      }
    };

    loadStats();
  }, [project.id]);

  // 点击外部关闭菜单
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setShowMenu(false);
      }
    };

    if (showMenu) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showMenu]);

  // 格式化时间
  const formatTime = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return formatDistanceToNow(date, { 
        addSuffix: true, 
        locale: zhCN 
      });
    } catch {
      return '未知时间';
    }
  };

  // 获取项目目录名
  const getDirectoryName = (path: string) => {
    const parts = path.split(/[/\\]/);
    return parts[parts.length - 1] || path;
  };

  // 打开项目文件夹
  const handleOpenFolder = async (e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      const { openPath } = await import('@tauri-apps/plugin-opener');

      // 处理 Windows 路径格式，移除 \\?\ 前缀
      let normalizedPath = project.path;
      if (normalizedPath.startsWith('\\\\?\\')) {
        normalizedPath = normalizedPath.substring(4);
      }

      await openPath(normalizedPath);
    } catch (error) {
      console.error('打开文件夹失败:', error);

      // 如果 openPath 失败，尝试使用 revealItemInDir
      try {
        const { revealItemInDir } = await import('@tauri-apps/plugin-opener');
        let normalizedPath = project.path;
        if (normalizedPath.startsWith('\\\\?\\')) {
          normalizedPath = normalizedPath.substring(4);
        }
        await revealItemInDir(normalizedPath);
      } catch (fallbackError) {
        console.error('备用方法也失败:', fallbackError);
        alert('无法打开文件夹，请检查路径是否存在');
      }
    }
  };

  return (
    <div className="card card-interactive group cursor-pointer animate-fade-in-up relative overflow-hidden bg-gradient-to-br from-white to-gray-50/50 hover:from-white hover:to-primary-50/30 transition-all duration-500">
      {/* 增强的背景装饰 */}
      <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-primary-100 to-primary-200 rounded-full -translate-y-16 translate-x-16 opacity-40 group-hover:opacity-60 transition-all duration-500 group-hover:scale-110"></div>

      {/* 光晕效果 */}
      <div className="absolute inset-0 bg-gradient-to-br from-transparent via-transparent to-primary-50/20 opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>

      {/* 卡片头部 */}
      <div className="relative p-6 pb-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-gradient-to-br from-primary-100 to-primary-200 text-primary-600 rounded-xl group-hover:from-primary-200 group-hover:to-primary-300 group-hover:scale-110 group-hover:shadow-lg transition-all duration-300 relative overflow-hidden">
              <div className="absolute inset-0 bg-white opacity-0 group-hover:opacity-20 transition-opacity duration-300"></div>
              <Folder size={20} className="relative z-10" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 line-clamp-1 group-hover:text-primary-700 transition-colors duration-200">
                {project.name}
              </h3>
              <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                <Calendar size={12} />
                <span>{formatTime(project.updated_at)}</span>
              </div>
            </div>
          </div>

          {/* 菜单按钮 */}
          <div className="relative" ref={menuRef}>
            <button
              className="p-2 rounded-xl text-gray-400 hover:text-gray-600 hover:bg-white hover:shadow-md transition-all duration-200 opacity-0 group-hover:opacity-100"
              onClick={(e) => {
                e.stopPropagation();
                setShowMenu(!showMenu);
              }}
            >
              <MoreVertical size={16} />
            </button>
            {showMenu && (
              <div className="dropdown-menu animate-scale-in">
                <button
                  className="dropdown-item"
                  onClick={() => {
                    onOpen(project);
                    setShowMenu(false);
                  }}
                >
                  <ExternalLink size={14} />
                  打开项目
                </button>
                <button
                  className="dropdown-item"
                  onClick={(e) => {
                    handleOpenFolder(e);
                    setShowMenu(false);
                  }}
                >
                  <FolderOpen size={14} />
                  打开文件夹
                </button>
                <div className="dropdown-divider"></div>
                <button
                  className="dropdown-item"
                  onClick={() => {
                    onEdit(project);
                    setShowMenu(false);
                  }}
                >
                  <Edit3 size={14} />
                  编辑
                </button>
                <button
                  className="dropdown-item danger"
                  onClick={() => {
                    onDelete(project.id);
                    setShowMenu(false);
                  }}
                >
                  <Trash2 size={14} />
                  删除
                </button>
              </div>
            )}
          </div>
        </div>

        {/* 项目描述 */}
        {project.description && (
          <p className="text-sm text-gray-600 line-clamp-2 mb-4 leading-relaxed">
            {project.description}
          </p>
        )}
      </div>

      {/* 项目统计信息 */}
      <div className="relative px-6 pb-4" onClick={() => onOpen(project)}>
        {isLoadingStats ? (
          <div className="bg-gradient-to-r from-gray-50 to-gray-100 rounded-xl p-4 mb-4">
            <div className="flex items-center space-x-2 text-gray-500 text-sm">
              <BarChart3 className="w-4 h-4 animate-pulse" />
              <span>加载统计中...</span>
            </div>
          </div>
        ) : stats && (
          <div className="bg-gradient-to-r from-primary-50 via-blue-50 to-indigo-50 rounded-xl p-4 mb-4 border border-primary-200/50 shadow-sm hover:shadow-md transition-all duration-300 relative overflow-hidden">
            <div className="absolute inset-0 bg-gradient-to-r from-white/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
            <div className="flex items-center justify-between mb-3 relative z-10">
              <div className="flex items-center space-x-2 text-primary-700 font-semibold text-sm">
                <BarChart3 className="w-4 h-4 text-primary-600" />
                <span>项目统计</span>
              </div>
              {stats.total_materials > 0 && (
                <div className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-primary-100 text-primary-800 border border-primary-200">
                  {stats.total_materials} 个素材
                </div>
              )}
            </div>

            {/* 素材统计网格 */}
            <div className="grid grid-cols-2 gap-3 mb-3">
              <div className="text-center">
                <div className="text-lg font-bold text-gray-900">
                  {stats.total_materials}
                </div>
                <div className="text-xs text-gray-600">总素材</div>
              </div>
              <div className="text-center">
                <div className="text-lg font-bold text-gray-900">
                  {formatFileSize(stats.total_size)}
                </div>
                <div className="text-xs text-gray-600">总大小</div>
              </div>
            </div>

            {/* 文件类型分布 */}
            {(stats.video_count > 0 || stats.audio_count > 0 || stats.image_count > 0 || stats.other_count > 0) && (
              <div className="flex items-center justify-center gap-4 text-xs">
                {stats.video_count > 0 && (
                  <div className="flex items-center space-x-1 text-blue-600 bg-blue-50 px-2 py-1 rounded-lg">
                    <FileVideo className="w-3 h-3" />
                    <span className="font-medium">{stats.video_count}</span>
                  </div>
                )}
                {stats.audio_count > 0 && (
                  <div className="flex items-center space-x-1 text-green-600 bg-green-50 px-2 py-1 rounded-lg">
                    <FileAudio className="w-3 h-3" />
                    <span className="font-medium">{stats.audio_count}</span>
                  </div>
                )}
                {stats.image_count > 0 && (
                  <div className="flex items-center space-x-1 text-purple-600 bg-purple-50 px-2 py-1 rounded-lg">
                    <FileImage className="w-3 h-3" />
                    <span className="font-medium">{stats.image_count}</span>
                  </div>
                )}
                {stats.other_count > 0 && (
                  <div className="flex items-center space-x-1 text-gray-600 bg-gray-50 px-2 py-1 rounded-lg">
                    <File className="w-3 h-3" />
                    <span className="font-medium">{stats.other_count}</span>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* 项目路径信息 */}
        <div className="flex items-center gap-2 text-xs text-gray-500 mb-4">
          <MapPin size={12} />
          <span className="truncate bg-gray-100 px-2 py-1 rounded-lg font-mono" title={project.path}>
            {getDirectoryName(project.path)}
          </span>
        </div>
      </div>

      {/* 增强的底部操作区 */}
      <div className="relative px-6 pb-6">
        <div className="flex gap-2">
          <button
            className="p-2.5 rounded-lg text-gray-500 hover:text-primary-600 hover:bg-primary-50 transition-all duration-200 hover:scale-105"
            onClick={handleOpenFolder}
            title="打开项目文件夹"
          >
            <FolderOpen size={16} />
          </button>
          <button
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-all duration-200 hover:scale-105 font-medium text-sm"
            onClick={() => onEdit(project)}
          >
            <Edit3 size={14} />
            编辑
          </button>
          <button
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white rounded-lg transition-all duration-200 hover:scale-105 hover:shadow-lg font-medium text-sm"
            onClick={() => onOpen(project)}
          >
            <ExternalLink size={14} />
            打开
          </button>
        </div>
      </div>
    </div>
  );
};
