import React, { useState } from 'react';
import {
  Play,
  Clock,
  Tag,
  Users,
  Star,
  MoreVertical,
  Eye,
  Edit,
  Trash2,
  RefreshCw,
  FileVideo,
  Calendar,
  Hash,
  TrendingUp
} from 'lucide-react';
import {
  SegmentWithDetails,
  MaterialSegmentViewMode,
  SegmentActionType
} from '../types/materialSegmentView';
import { MaterialSegmentDetailModal } from './MaterialSegmentDetailModal';

interface MaterialSegmentCardProps {
  segmentWithDetails: SegmentWithDetails;
  isSelected: boolean;
  onSelect: () => void;
  viewMode: MaterialSegmentViewMode;
}

/**
 * MaterialSegment卡片组件
 * 遵循 Tauri 开发规范的组件设计模式
 */
export const MaterialSegmentCard: React.FC<MaterialSegmentCardProps> = ({
  segmentWithDetails,
  isSelected,
  onSelect,
}) => {
  const [showActions, setShowActions] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const { segment, material_name, classification, model } = segmentWithDetails;

  // 格式化时长
  const formatDuration = (seconds: number) => {
    if (seconds < 60) {
      return `${Math.round(seconds)}s`;
    } else {
      return `${Math.floor(seconds / 60)}:${Math.round(seconds % 60).toString().padStart(2, '0')}`;
    }
  };

  // 格式化时间戳
  const formatTimestamp = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.round(seconds % 60);
    return `${minutes}:${secs.toString().padStart(2, '0')}`;
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取置信度颜色
  const getConfidenceColor = (confidence: number) => {
    if (confidence >= 0.8) return 'text-green-600 bg-green-100';
    if (confidence >= 0.6) return 'text-yellow-600 bg-yellow-100';
    return 'text-red-600 bg-red-100';
  };

  // 获取质量评分颜色
  const getQualityColor = (score: number) => {
    if (score >= 0.8) return 'text-green-600';
    if (score >= 0.6) return 'text-yellow-600';
    return 'text-red-600';
  };

  // 处理操作点击
  const handleAction = (actionType: SegmentActionType, event: React.MouseEvent) => {
    event.stopPropagation();
    setShowActions(false);

    switch (actionType) {
      case SegmentActionType.ViewDetails:
        setShowDetailModal(true);
        break;
      case SegmentActionType.Reclassify:
        // TODO: 实现重新分类逻辑
        console.log(`重新分类片段: ${segment.id}`);
        break;
      case SegmentActionType.EditModel:
        // TODO: 实现编辑模特逻辑
        console.log(`编辑模特关联: ${segment.id}`);
        break;
      case SegmentActionType.Delete:
        // TODO: 实现删除逻辑
        console.log(`删除片段: ${segment.id}`);
        break;
      default:
        console.log(`执行操作: ${actionType} on segment ${segment.id}`);
    }
  };

  return (
    <div 
      className={`relative bg-white rounded-lg border-2 transition-all duration-200 hover:shadow-md cursor-pointer ${
        isSelected 
          ? 'border-blue-500 bg-blue-50' 
          : 'border-gray-200 hover:border-gray-300'
      }`}
      onClick={onSelect}
    >
      {/* 选择指示器 */}
      {isSelected && (
        <div className="absolute top-2 left-2 w-4 h-4 bg-blue-500 rounded-full flex items-center justify-center">
          <div className="w-2 h-2 bg-white rounded-full" />
        </div>
      )}

      {/* 操作菜单 */}
      <div className="absolute top-2 right-2">
        <button
          onClick={(e) => {
            e.stopPropagation();
            setShowActions(!showActions);
          }}
          className="p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
        >
          <MoreVertical className="w-4 h-4" />
        </button>

        {showActions && (
          <div className="absolute right-0 top-8 bg-white border border-gray-200 rounded-lg shadow-lg py-1 z-10 min-w-[120px]">
            <button
              onClick={(e) => handleAction(SegmentActionType.ViewDetails, e)}
              className="w-full px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 flex items-center"
            >
              <Eye className="w-4 h-4 mr-2" />
              查看详情
            </button>
            <button
              onClick={(e) => handleAction(SegmentActionType.Reclassify, e)}
              className="w-full px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 flex items-center"
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              重新分类
            </button>
            <button
              onClick={(e) => handleAction(SegmentActionType.EditModel, e)}
              className="w-full px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 flex items-center"
            >
              <Edit className="w-4 h-4 mr-2" />
              编辑模特
            </button>
            <div className="border-t border-gray-100 my-1" />
            <button
              onClick={(e) => handleAction(SegmentActionType.Delete, e)}
              className="w-full px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50 flex items-center"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              删除
            </button>
          </div>
        )}
      </div>

      <div className="p-4">
        {/* 片段基本信息 */}
        <div className="mb-3">
          <div className="flex items-center justify-between mb-2">
            <h4 className="font-medium text-gray-900 truncate flex-1 mr-2">
              {material_name}
            </h4>
            <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">
              #{segment.segment_index}
            </span>
          </div>

          {/* 时间信息 */}
          <div className="flex items-center justify-between text-sm text-gray-600 mb-2">
            <div className="flex items-center space-x-2">
              <Clock className="w-4 h-4" />
              <span>{formatTimestamp(segment.start_time)} - {formatTimestamp(segment.end_time)}</span>
            </div>
            <div className="flex items-center space-x-1">
              <span className="font-medium">{formatDuration(segment.duration)}</span>
            </div>
          </div>

          {/* 文件信息 */}
          <div className="flex items-center text-xs text-gray-500 mb-3">
            <FileVideo className="w-3 h-3 mr-1" />
            <span className="truncate">{segment.file_path.split('/').pop()}</span>
          </div>
        </div>

        {/* 分类信息 */}
        {classification && (
          <div className="mb-3 p-2 bg-gray-50 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-1">
                <Tag className="w-3 h-3 text-blue-500" />
                <span className="text-sm font-medium text-gray-900">{classification.category}</span>
              </div>
              <div className={`text-xs px-2 py-1 rounded-full ${getConfidenceColor(classification.confidence)}`}>
                {Math.round(classification.confidence * 100)}%
              </div>
            </div>

            {/* 质量评分 */}
            <div className="flex items-center justify-between text-xs">
              <div className="flex items-center space-x-1">
                <TrendingUp className="w-3 h-3 text-gray-400" />
                <span className="text-gray-600">质量评分</span>
              </div>
              <div className="flex items-center space-x-1">
                <Star className={`w-3 h-3 ${getQualityColor(classification.quality_score)}`} />
                <span className={getQualityColor(classification.quality_score)}>
                  {Math.round(classification.quality_score * 100)}%
                </span>
              </div>
            </div>

            {/* 商品匹配指示器 */}
            {classification.product_match && (
              <div className="mt-1 text-xs text-green-600 bg-green-100 px-2 py-1 rounded inline-block">
                商品匹配
              </div>
            )}
          </div>
        )}

        {/* 模特信息 */}
        {model && (
          <div className="mb-3 p-2 bg-green-50 rounded-lg">
            <div className="flex items-center space-x-2">
              <Users className="w-3 h-3 text-green-500" />
              <span className="text-sm font-medium text-gray-900">{model.name}</span>
              <span className="text-xs text-gray-500">({model.model_type})</span>
            </div>
          </div>
        )}

        {/* 关键特征 */}
        {classification && classification.features.length > 0 && (
          <div className="mb-3">
            <div className="text-xs text-gray-600 mb-1">关键特征</div>
            <div className="flex flex-wrap gap-1">
              {classification.features.slice(0, 3).map((feature, index) => (
                <span 
                  key={index}
                  className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded"
                >
                  {feature}
                </span>
              ))}
              {classification.features.length > 3 && (
                <span className="text-xs text-gray-500">
                  +{classification.features.length - 3}
                </span>
              )}
            </div>
          </div>
        )}

        {/* 底部信息 */}
        <div className="flex items-center justify-between text-xs text-gray-500 pt-2 border-t border-gray-100">
          <div className="flex items-center space-x-1">
            <Calendar className="w-3 h-3" />
            <span>{formatDate(segment.created_at)}</span>
          </div>
          <div className="flex items-center space-x-1">
            <Hash className="w-3 h-3" />
            <span className="font-mono">{segment.id.slice(-8)}</span>
          </div>
        </div>
      </div>

      {/* 播放按钮覆盖层 */}
      <div className="absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-20 transition-all duration-200 rounded-lg flex items-center justify-center opacity-0 hover:opacity-100">
        <button 
          onClick={(e) => {
            e.stopPropagation();
            // TODO: 实现视频播放逻辑
            console.log('播放片段:', segment.file_path);
          }}
          className="bg-white bg-opacity-90 hover:bg-opacity-100 rounded-full p-3 transition-all duration-200 transform hover:scale-110"
        >
          <Play className="w-6 h-6 text-gray-700" />
        </button>
      </div>

      {/* 详情模态框 */}
      <MaterialSegmentDetailModal
        segmentWithDetails={segmentWithDetails}
        isOpen={showDetailModal}
        onClose={() => setShowDetailModal(false)}
        onPlay={() => {
          // TODO: 实现视频播放逻辑
          console.log('播放片段:', segment.file_path);
        }}
      />
    </div>
  );
};
