import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  TemplateMatchingResultDetail,
  MatchingResultStatus
} from '../types/templateMatchingResult';
import { Modal } from './Modal';
import { LoadingSpinner } from './LoadingSpinner';
import { ErrorMessage } from './ErrorMessage';
import { TabNavigation } from './TabNavigation';
import { SegmentThumbnail } from './SegmentThumbnail';

interface TemplateMatchingResultDetailModalProps {
  resultId: string;
  onClose: () => void;
  onUpdate?: () => void;
}

export const TemplateMatchingResultDetailModal: React.FC<TemplateMatchingResultDetailModalProps> = ({
  resultId,
  onClose,
  onUpdate,
}) => {
  const [detail, setDetail] = useState<TemplateMatchingResultDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState('overview');
  const [thumbnailCache, setThumbnailCache] = useState<Map<string, string>>(new Map());
  const [segmentDetails, setSegmentDetails] = useState<Map<string, any>>(new Map());
  const [editMode, setEditMode] = useState(false);
  const [editForm, setEditForm] = useState({
    result_name: '',
    description: '',
    quality_score: '',
  });

  // 加载详情数据
  const loadDetail = async () => {
    try {
      setLoading(true);
      setError(null);

      const resultDetail = await invoke<TemplateMatchingResultDetail>('get_matching_result_detail', {
        resultId,
      });

      if (resultDetail) {
        setDetail(resultDetail);
        setEditForm({
          result_name: resultDetail.matching_result.result_name,
          description: resultDetail.matching_result.description || '',
          quality_score: resultDetail.matching_result.quality_score?.toString() || '',
        });
      } else {
        setError('匹配结果不存在');
      }
    } catch (err) {
      setError(err as string);
    } finally {
      setLoading(false);
    }
  };

  // 保存编辑
  const handleSave = async () => {
    if (!detail) return;

    try {
      // 更新基本信息
      await invoke('update_matching_result_info', {
        resultId: detail.matching_result.id,
        resultName: editForm.result_name || undefined,
        description: editForm.description || undefined,
      });

      // 更新质量评分
      if (editForm.quality_score) {
        const score = parseFloat(editForm.quality_score);
        if (!isNaN(score) && score >= 0 && score <= 5) {
          await invoke('set_matching_result_quality_score', {
            resultId: detail.matching_result.id,
            qualityScore: score,
          });
        }
      }

      setEditMode(false);
      await loadDetail();
      onUpdate?.();
    } catch (err) {
      setError(`保存失败: ${err}`);
    }
  };

  // 格式化时长
  const formatDuration = (ms: number): string => {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}min`;
  };

  // 格式化时间
  const formatTime = (microseconds: number): string => {
    const seconds = microseconds / 1000000;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = (seconds % 60).toFixed(1);
    return minutes > 0 ? `${minutes}:${remainingSeconds.padStart(4, '0')}` : `${remainingSeconds}s`;
  };

  // 从文件路径提取文件名
  const extractFileName = (filePath: string): string => {
    if (!filePath) return '';
    return filePath.split(/[/\\]/).pop() || filePath;
  };

  // 获取片段详细信息
  const getSegmentDetails = async (segmentId: string) => {
    if (segmentDetails.has(segmentId)) {
      return segmentDetails.get(segmentId);
    }

    try {
      const segmentInfo = await invoke('get_material_segment_by_id', { segmentId });
      setSegmentDetails(prev => new Map(prev.set(segmentId, segmentInfo)));
      return segmentInfo;
    } catch (error) {
      console.error('获取片段详情失败:', error);
      return null;
    }
  };

  // 渲染片段信息组件
  const SegmentInfo: React.FC<{ segment: any }> = ({ segment }) => {
    const [segmentDetail, setSegmentDetail] = useState<any>(null);

    useEffect(() => {
      const loadSegmentDetail = async () => {
        const detail = await getSegmentDetails(segment.material_segment_id);
        setSegmentDetail(detail);
      };
      loadSegmentDetail();
    }, [segment.material_segment_id]);

    return (
      <div className="text-sm text-gray-600">
        <div>
          <span className="font-medium">素材:</span> {segmentDetail ? extractFileName(segmentDetail.file_path) : segment.material_segment_id}
        </div>
      </div>
    );
  };

  // 获取状态样式
  const getStatusStyle = (status: MatchingResultStatus) => {
    switch (status) {
      case MatchingResultStatus.Success:
        return 'bg-green-100 text-green-800';
      case MatchingResultStatus.PartialSuccess:
        return 'bg-yellow-100 text-yellow-800';
      case MatchingResultStatus.Failed:
        return 'bg-red-100 text-red-800';
      case MatchingResultStatus.Cancelled:
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  useEffect(() => {
    loadDetail();
  }, [resultId]);

  const tabs = [
    { id: 'overview', label: '概览', count: undefined },
    { id: 'segments', label: '成功片段', count: detail?.segment_results.length },
    { id: 'failed', label: '失败片段', count: detail?.failed_segment_results.length },
  ];

  if (loading) {
    return (
      <Modal isOpen onClose={onClose} title="匹配结果详情">
        <div className="flex justify-center items-center h-64">
          <LoadingSpinner text="加载详情..." />
        </div>
      </Modal>
    );
  }

  if (error || !detail) {
    return (
      <Modal isOpen onClose={onClose} title="匹配结果详情">
        <div className="p-4">
          <ErrorMessage message={error || '数据加载失败'} />
        </div>
      </Modal>
    );
  }

  const { matching_result, segment_results, failed_segment_results } = detail;

  return (
    <Modal
      isOpen
      onClose={onClose}
      title="匹配结果详情"
      size="xl"
    >
      <div className="max-h-[85vh] overflow-y-auto custom-scrollbar">
        {/* 头部信息 */}
        <div className="modal-header">
          {editMode ? (
            <div className="space-y-4">
              <div className="form-group">
                <label className="form-label">
                  结果名称
                </label>
                <input
                  type="text"
                  value={editForm.result_name}
                  onChange={(e) => setEditForm(prev => ({ ...prev, result_name: e.target.value }))}
                  className="form-input"
                />
              </div>
              <div className="form-group">
                <label className="form-label">
                  描述
                </label>
                <textarea
                  value={editForm.description}
                  onChange={(e) => setEditForm(prev => ({ ...prev, description: e.target.value }))}
                  rows={3}
                  className="form-textarea"
                />
              </div>
              <div className="form-group">
                <label className="form-label">
                  质量评分 (0-5)
                </label>
                <input
                  type="number"
                  min="0"
                  max="5"
                  step="0.1"
                  value={editForm.quality_score}
                  onChange={(e) => setEditForm(prev => ({ ...prev, quality_score: e.target.value }))}
                  className="form-input"
                />
              </div>
              <div className="flex space-x-3">
                <button
                  onClick={handleSave}
                  className="btn btn-primary"
                >
                  保存
                </button>
                <button
                  onClick={() => setEditMode(false)}
                  className="btn btn-secondary"
                >
                  取消
                </button>
              </div>
            </div>
          ) : (
            <div>
              <div className="flex items-start justify-between">
                <div>
                  <h2 className="text-xl font-semibold text-gray-900">
                    {matching_result.result_name}
                  </h2>
                  {matching_result.description && (
                    <p className="text-gray-600 mt-1">{matching_result.description}</p>
                  )}
                </div>
                <div className="flex items-center space-x-3">
                  <span className={`status-indicator ${getStatusStyle(matching_result.status)}`}>
                    {matching_result.status === MatchingResultStatus.Success ? '匹配成功' :
                     matching_result.status === MatchingResultStatus.PartialSuccess ? '部分成功' :
                     matching_result.status === MatchingResultStatus.Failed ? '匹配失败' : '已取消'}
                  </span>
                  <button
                    onClick={() => setEditMode(true)}
                    className="btn btn-secondary btn-sm"
                  >
                    编辑
                  </button>
                </div>
              </div>

              {/* 统计信息 */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
                <div className="text-center p-4 bg-gradient-to-br from-primary-50 to-primary-100 rounded-xl">
                  <div className="text-2xl font-bold text-primary-700">
                    {Math.min(matching_result.success_rate * 100, 100).toFixed(1)}%
                  </div>
                  <div className="text-sm text-primary-600 font-medium">成功率</div>
                </div>
                <div className="text-center p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl">
                  <div className="text-2xl font-bold text-gray-900">
                    {matching_result.matched_segments}/{matching_result.total_segments}
                  </div>
                  <div className="text-sm text-gray-600 font-medium">匹配片段</div>
                </div>
                <div className="text-center p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-xl">
                  <div className="text-2xl font-bold text-green-700">
                    {matching_result.used_materials}
                  </div>
                  <div className="text-sm text-gray-500">使用素材</div>
                </div>
                <div className="text-center p-3 bg-gray-50 rounded-lg">
                  <div className="text-2xl font-bold text-gray-900">
                    {formatDuration(matching_result.matching_duration_ms)}
                  </div>
                  <div className="text-sm text-gray-500">匹配耗时</div>
                </div>
              </div>

              {/* 质量评分 */}
              {matching_result.quality_score && (
                <div className="mt-4 p-3 bg-yellow-50 rounded-lg">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-700">质量评分:</span>
                    <div className="flex items-center">
                      <div className="flex text-yellow-400 mr-2">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <svg
                            key={star}
                            className={`w-5 h-5 ${
                              star <= matching_result.quality_score! ? 'fill-current' : 'text-gray-300'
                            }`}
                            viewBox="0 0 20 20"
                          >
                            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                          </svg>
                        ))}
                      </div>
                      <span className="text-sm font-medium text-gray-900">
                        {matching_result.quality_score.toFixed(1)}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 标签页导航 */}
        <TabNavigation
          tabs={tabs}
          activeTab={activeTab}
          onTabChange={setActiveTab}
          variant="underline"
          className='px-4'
        />

        {/* 标签页内容 */}
        <div className="p-6">
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <h3 className="text-lg font-medium text-gray-900 mb-3">基本信息</h3>
                  <dl className="space-y-2">
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">项目ID:</dt>
                      <dd className="text-sm text-gray-900">{matching_result.project_id}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">模板ID:</dt>
                      <dd className="text-sm text-gray-900">{matching_result.template_id}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">绑定ID:</dt>
                      <dd className="text-sm text-gray-900">{matching_result.binding_id}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">创建时间:</dt>
                      <dd className="text-sm text-gray-900">
                        {new Date(matching_result.created_at).toLocaleString('zh-CN')}
                      </dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">更新时间:</dt>
                      <dd className="text-sm text-gray-900">
                        {new Date(matching_result.updated_at).toLocaleString('zh-CN')}
                      </dd>
                    </div>
                  </dl>
                </div>

                <div>
                  <h3 className="text-lg font-medium text-gray-900 mb-3">匹配统计</h3>
                  <dl className="space-y-2">
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">总片段数:</dt>
                      <dd className="text-sm text-gray-900">{matching_result.total_segments}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">成功匹配:</dt>
                      <dd className="text-sm text-green-600">{matching_result.matched_segments}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">匹配失败:</dt>
                      <dd className="text-sm text-red-600">{matching_result.failed_segments}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">使用素材:</dt>
                      <dd className="text-sm text-gray-900">{matching_result.used_materials}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-sm text-gray-500">使用模特:</dt>
                      <dd className="text-sm text-gray-900">{matching_result.used_models}</dd>
                    </div>
                  </dl>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'segments' && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">
                成功匹配的片段 ({segment_results.length})
              </h3>
              {segment_results.length === 0 ? (
                <p className="text-gray-500 text-center py-8">暂无成功匹配的片段</p>
              ) : (
                <div className="space-y-3">
                  {segment_results.map((segment) => (
                    <div key={segment.id} className="bg-green-50 border border-green-200 rounded-lg p-4">
                      <div className="flex items-start gap-4">
                        {/* 缩略图 */}
                        <SegmentThumbnail
                          segmentId={segment.material_segment_id}
                          size="large"
                          thumbnailCache={thumbnailCache}
                          setThumbnailCache={setThumbnailCache}
                        />

                        {/* 片段信息 */}
                        <div className="flex-1 min-w-0">
                          <h4 className="font-medium text-gray-900 mb-2">{segment.track_segment_name}</h4>

                          <SegmentInfo segment={segment} />

                          <div className="mt-2 text-sm text-gray-500">
                            <span className="font-medium">匹配原因:</span> {segment.match_reason}
                          </div>
                        </div>

                        {/* 匹配度 */}
                        <div className="text-right flex-shrink-0">
                          <div className="text-lg font-bold text-green-600">
                            {(segment.match_score * 100).toFixed(1)}%
                          </div>
                          <div className="text-xs text-gray-500">匹配度</div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {activeTab === 'failed' && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">
                匹配失败的片段 ({failed_segment_results.length})
              </h3>
              {failed_segment_results.length === 0 ? (
                <p className="text-gray-500 text-center py-8">暂无匹配失败的片段</p>
              ) : (
                <div className="space-y-3">
                  {failed_segment_results.map((segment) => (
                    <div key={segment.id} className="bg-red-50 border border-red-200 rounded-lg p-4">
                      <div>
                        <h4 className="font-medium text-gray-900">{segment.track_segment_name}</h4>
                        <p className="text-sm text-gray-600 mt-1">
                          匹配规则: {segment.matching_rule_type}
                        </p>
                        <p className="text-sm text-gray-500 mt-1">
                          时长: {formatTime(segment.segment_duration)} | 
                          时间: {formatTime(segment.start_time)} - {formatTime(segment.end_time)}
                        </p>
                        <p className="text-sm text-red-600 mt-2 font-medium">
                          失败原因: {segment.failure_reason}
                        </p>
                        {segment.failure_details && (
                          <p className="text-sm text-gray-500 mt-1">
                            详情: {segment.failure_details}
                          </p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
};
