import React, { useState } from 'react';
import { ProjectMaterialUsageOverview, MaterialUsageStats } from '../types/materialUsage';
import { MaterialUsageStatsCard, MaterialUsageProgress } from './MaterialUsageStatus';
import { useResetUsageDialog, createResetDialog } from './ResetUsageDialog';

interface ProjectMaterialUsageOverviewProps {
  overview: ProjectMaterialUsageOverview;
  onRefresh?: () => void;
  onResetAll?: () => void;
  isLoading?: boolean;
}

/**
 * 项目素材使用概览组件
 * 显示项目级别的素材使用统计和详细信息
 */
export const ProjectMaterialUsageOverviewComponent: React.FC<ProjectMaterialUsageOverviewProps> = ({
  overview,
  onRefresh,
  onResetAll,
  isLoading = false
}) => {
  const [showDetails, setShowDetails] = useState(false);
  const { openDialog, ResetDialog } = useResetUsageDialog();

  // 处理重置确认
  const handleResetClick = () => {
    if (!onResetAll) return;

    openDialog(createResetDialog.project(
      '当前项目',
      overview.total_materials,
      async () => {
        await onResetAll();
      }
    ));
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
      {/* 标题栏 */}
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-semibold text-gray-900">素材使用概览</h3>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowDetails(!showDetails)}
            className="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors"
          >
            {showDetails ? '隐藏详情' : '显示详情'}
          </button>
          {onRefresh && (
            <button
              onClick={onRefresh}
              disabled={isLoading}
              className="px-3 py-1.5 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-md transition-colors disabled:opacity-50"
            >
              {isLoading ? '刷新中...' : '刷新'}
            </button>
          )}
          {onResetAll && (
            <button
              onClick={handleResetClick}
              className="px-3 py-1.5 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 rounded-md transition-colors"
            >
              重置全部
            </button>
          )}
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <MaterialUsageStatsCard
          title="总素材数"
          value={overview.total_materials}
          color="blue"
          icon={
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
              <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6zM14 9a1 1 0 00-1 1v6a1 1 0 001 1h2a1 1 0 001-1v-6a1 1 0 00-1-1h-2z" />
            </svg>
          }
        />
        
        <MaterialUsageStatsCard
          title="总片段数"
          value={overview.total_segments}
          color="gray"
          icon={
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M3 4a1 1 0 011-1h4a1 1 0 010 2H6.414l2.293 2.293a1 1 0 01-1.414 1.414L5 6.414V8a1 1 0 01-2 0V4zm9 1a1 1 0 010-2h4a1 1 0 011 1v4a1 1 0 01-2 0V6.414l-2.293 2.293a1 1 0 11-1.414-1.414L13.586 5H12zm-9 7a1 1 0 012 0v1.586l2.293-2.293a1 1 0 111.414 1.414L6.414 15H8a1 1 0 010 2H4a1 1 0 01-1-1v-4zm13-1a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 010-2h1.586l-2.293-2.293a1 1 0 111.414-1.414L15.586 13H14a1 1 0 01-1-1z" clipRule="evenodd" />
            </svg>
          }
        />
        
        <MaterialUsageStatsCard
          title="已使用"
          value={overview.used_segments}
          total={overview.total_segments}
          color="green"
          icon={
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
            </svg>
          }
        />
        
        <MaterialUsageStatsCard
          title="使用次数"
          value={overview.total_usage_count}
          color="orange"
          icon={
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
              <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          }
        />
      </div>

      {/* 使用进度条 */}
      <MaterialUsageProgress
        totalSegments={overview.total_segments}
        usedSegments={overview.used_segments}
        className="mb-6"
      />

      {/* 详细信息 */}
      {showDetails && (
        <div className="border-t border-gray-200 pt-6">
          <h4 className="text-md font-medium text-gray-900 mb-4">素材详细统计</h4>
          
          {overview.materials_stats.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              暂无素材数据
            </div>
          ) : (
            <div className="space-y-3">
              {overview.materials_stats.map((stats) => (
                <MaterialStatsRow key={stats.material_id} stats={stats} />
              ))}
            </div>
          )}
        </div>
      )}

      {/* 重置确认对话框 */}
      {ResetDialog}
    </div>
  );
};

/**
 * 单个素材统计行组件
 */
const MaterialStatsRow: React.FC<{ stats: MaterialUsageStats }> = ({ stats }) => {
  const usageRate = stats.usage_rate * 100;
  
  // 格式化最后使用时间
  const formatLastUsedTime = (timestamp?: string) => {
    if (!timestamp) return '从未使用';
    
    try {
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch {
      return '时间格式错误';
    }
  };

  return (
    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
      <div className="flex-1">
        <div className="flex items-center justify-between mb-1">
          <h5 className="font-medium text-gray-900 truncate">{stats.material_name}</h5>
          <span className="text-sm text-gray-500">
            {stats.used_segments}/{stats.total_segments} ({usageRate.toFixed(1)}%)
          </span>
        </div>
        
        <div className="flex items-center justify-between text-sm text-gray-600">
          <span>使用次数: {stats.total_usage_count}</span>
          <span>最后使用: {formatLastUsedTime(stats.last_used_at)}</span>
        </div>
        
        {/* 小型进度条 */}
        <div className="w-full bg-gray-200 rounded-full h-1.5 mt-2">
          <div 
            className="bg-blue-600 h-1.5 rounded-full transition-all duration-300"
            style={{ width: `${usageRate}%` }}
          />
        </div>
      </div>
    </div>
  );
};
