import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { save } from '@tauri-apps/plugin-dialog';
import {
  TemplateMatchingResult,
  TemplateMatchingResultQueryOptions,
  MatchingResultStatus,
  MatchingStatistics
} from '../types/templateMatchingResult';
import { LoadingSpinner } from './LoadingSpinner';
import { ErrorMessage } from './ErrorMessage';
import { EmptyState } from './EmptyState';
import { DeleteConfirmDialog } from './DeleteConfirmDialog';
import { CustomSelect } from './CustomSelect';
import { TemplateMatchingResultCard } from './TemplateMatchingResultCard';
import { TemplateMatchingResultDetailModal } from './TemplateMatchingResultDetailModal';
import { TemplateMatchingResultStatsPanel } from './TemplateMatchingResultStatsPanel';
import { useNotifications } from './NotificationSystem';

interface TemplateMatchingResultManagerProps {
  projectId?: string;
  templateId?: string;
  bindingId?: string;
  showStats?: boolean;
  onResultSelect?: (result: TemplateMatchingResult) => void;
}

export const TemplateMatchingResultManager: React.FC<TemplateMatchingResultManagerProps> = ({
  projectId,
  templateId,
  bindingId,
  showStats = false,
  onResultSelect,
}) => {
  const [results, setResults] = useState<TemplateMatchingResult[]>([]);
  const [statistics, setStatistics] = useState<MatchingStatistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedResult, setSelectedResult] = useState<TemplateMatchingResult | null>(null);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    result: TemplateMatchingResult | null;
  }>({ show: false, result: null });

  // 批量操作状态
  const [selectedResults, setSelectedResults] = useState<Set<string>>(new Set());
  const [batchDeleteConfirm, setBatchDeleteConfirm] = useState<{
    show: boolean;
    resultIds: string[];
  }>({ show: false, resultIds: [] });
  const [batchOperationLoading, setBatchOperationLoading] = useState(false);

  // 过滤和排序状态
  const [filters, setFilters] = useState<{
    status?: MatchingResultStatus;
    searchKeyword?: string;
    sortBy: string;
    sortOrder: string;
  }>({
    sortBy: 'created_at',
    sortOrder: 'desc',
  });

  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 20,
    total: 0,
  });

  // 加载匹配结果列表
  const loadResults = async () => {
    try {
      setLoading(true);
      setError(null);

      const queryOptions: TemplateMatchingResultQueryOptions = {
        project_id: projectId,
        template_id: templateId,
        binding_id: bindingId,
        status: filters.status,
        search_keyword: filters.searchKeyword || undefined,
        sort_by: filters.sortBy,
        sort_order: filters.sortOrder,
        limit: pagination.pageSize,
        offset: (pagination.page - 1) * pagination.pageSize,
      };

      const resultList = await invoke<TemplateMatchingResult[]>('list_matching_results', {
        options: queryOptions,
      });

      setResults(resultList);
      setPagination(prev => ({ ...prev, total: resultList.length }));
    } catch (err) {
      setError(err as string);
    } finally {
      setLoading(false);
    }
  };

  // 加载统计信息
  const loadStatistics = async () => {
    if (!showStats) return;

    try {
      const stats = await invoke<MatchingStatistics>('get_matching_statistics', {
        projectId,
      });
      setStatistics(stats);
    } catch (err) {
      console.error('加载统计信息失败:', err);
    }
  };

  // 删除匹配结果
  const handleDelete = async (result: TemplateMatchingResult) => {
    try {
      await invoke<boolean>('soft_delete_matching_result', {
        resultId: result.id,
      });

      // 重新加载列表
      await loadResults();
      await loadStatistics();

      setDeleteConfirm({ show: false, result: null });
    } catch (err) {
      setError(`删除失败: ${err}`);
    }
  };

  // 批量删除匹配结果
  const handleBatchDelete = async (resultIds: string[]) => {
    console.log('开始批量删除，ID列表:', resultIds);
    setBatchOperationLoading(true);

    try {
      const [deletedResults, deletedUsageRecords] = await invoke<[number, number]>(
        'batch_soft_delete_matching_results_with_usage_reset',
        { resultIds }
      );

      console.log(`删除结果: ${deletedResults} 个匹配结果，${deletedUsageRecords} 条使用记录`);
      success(`成功删除 ${deletedResults} 个匹配结果，重置 ${deletedUsageRecords} 条使用记录`);

      // 重新加载列表
      console.log('重新加载列表...');
      await loadResults();
      await loadStatistics();
      console.log('列表重新加载完成');

      // 清空选择
      setSelectedResults(new Set());
    } catch (err) {
      console.error('批量删除失败:', err);
      setError(`批量删除失败: ${err}`);
    } finally {
      setBatchOperationLoading(false);
    }
  };

  // 确认批量删除
  const handleConfirmBatchDelete = async () => {
    const resultIds = [...batchDeleteConfirm.resultIds]; // 复制数组避免状态变化影响
    setBatchDeleteConfirm({ show: false, resultIds: [] }); // 立即关闭对话框
    await handleBatchDelete(resultIds);
  };

  // 切换选择状态
  const handleToggleSelect = (resultId: string) => {
    const newSelected = new Set(selectedResults);
    if (newSelected.has(resultId)) {
      newSelected.delete(resultId);
    } else {
      newSelected.add(resultId);
    }
    setSelectedResults(newSelected);
  };

  // 全选/取消全选
  const handleToggleSelectAll = () => {
    if (selectedResults.size === results.length) {
      setSelectedResults(new Set());
    } else {
      setSelectedResults(new Set(results.map(r => r.id)));
    }
  };

  // 查看详情
  const handleViewDetail = (result: TemplateMatchingResult) => {
    setSelectedResult(result);
    setShowDetailModal(true);
    onResultSelect?.(result);
  };
  const { success, warning } = useNotifications()
  // 导出到剪映 (V1版本)
  const handleExportToJianying = async (result: TemplateMatchingResult) => {
    try {
      // 选择保存路径
      const filePath = await save({
        title: '导出到剪映 (V1)',
        defaultPath: `draft_content_v1_${result.result_name}.json`,
        filters: [
          {
            name: 'JSON文件',
            extensions: ['json']
          }
        ]
      });

      if (!filePath) {
        return; // 用户取消了保存
      }

      // 调用后端导出API
      const exportedFilePath = await invoke<string>('export_matching_result_to_jianying', {
        resultId: result.id,
        outputPath: filePath,
      });

      // 显示成功消息
      success(`V1导出成功！文件已保存到：${exportedFilePath}`);

      // 导出成功后刷新数据
      await loadResults();
      await loadStatistics();
    } catch (err) {
      warning(`V1导出失败: ${err}`);
    }
  };
  // 导出到剪映 (V2版本)
  const handleExportToJianyingV2 = async (result: TemplateMatchingResult) => {
    try {
      // 选择保存路径
      const filePath = await save({
        title: '导出到剪映',
        defaultPath: 'draft_content.json',
        filters: [
          {
            name: 'JSON文件',
            extensions: ['json']
          }
        ]
      });

      if (!filePath) {
        return; // 用户取消了保存
      }

      // 调用后端V2导出API
      const exportedFilePath = await invoke<string>('export_matching_result_to_jianying_v2', {
        resultId: result.id,
        outputPath: filePath,
      });

      // 显示成功消息
      success(`导出成功！文件已保存到：${exportedFilePath}`);

      // 导出成功后刷新数据
      await loadResults();
      await loadStatistics();
    } catch (err) {
      warning(`导出失败: ${err}`);
    }
  };

  // 处理过滤器变化
  const handleFilterChange = (newFilters: Partial<typeof filters>) => {
    setFilters(prev => ({ ...prev, ...newFilters }));
    setPagination(prev => ({ ...prev, page: 1 })); // 重置到第一页
  };

  // 处理分页变化
  const handlePageChange = (page: number) => {
    setPagination(prev => ({ ...prev, page }));
  };

  // 初始加载
  useEffect(() => {
    loadResults();
    loadStatistics();
  }, [projectId, templateId, bindingId, filters, pagination.page]);

  // 状态选项
  const statusOptions = [
    { value: '', label: '全部状态' },
    { value: 'Success', label: '匹配成功' },
    { value: 'PartialSuccess', label: '部分成功' },
    { value: 'Failed', label: '匹配失败' },
    { value: 'Cancelled', label: '已取消' },
  ];

  // 排序选项
  const sortOptions = [
    { value: 'created_at', label: '创建时间' },
    { value: 'updated_at', label: '更新时间' },
    { value: 'success_rate', label: '成功率' },
    { value: 'result_name', label: '结果名称' },
    { value: 'total_segments', label: '片段数量' },
    { value: 'matching_duration_ms', label: '匹配耗时' },
  ];

  const sortOrderOptions = [
    { value: 'desc', label: '降序' },
    { value: 'asc', label: '升序' },
  ];

  if (loading && results.length === 0) {
    return <LoadingSpinner text="加载匹配结果..." />;
  }

  return (
    <div className="template-matching-result-manager space-y-6 relative">
      {/* 统计面板 */}
      {showStats && statistics && (
        <TemplateMatchingResultStatsPanel statistics={statistics} />
      )}

      {/* 过滤器和搜索 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200/50 p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {/* 搜索框 */}
          <div className="form-group">
            <label className="form-label">
              搜索
            </label>
            <div className="relative">
              <input
                type="text"
                placeholder="搜索结果名称或描述..."
                value={filters.searchKeyword || ''}
                onChange={(e) => handleFilterChange({ searchKeyword: e.target.value })}
                className="form-input h-10"
              />
            </div>
          </div>

          {/* 状态过滤 */}
          <div className="form-group">
            <label className="form-label">
              状态
            </label>
            <CustomSelect
              options={statusOptions}
              value={filters.status || ''}
              onChange={(value) => handleFilterChange({
                status: value === '' ? undefined : value as MatchingResultStatus
              })}
              placeholder="选择状态"
            />
          </div>

          {/* 排序字段 */}
          <div className="form-group">
            <label className="form-label">
              排序字段
            </label>
            <CustomSelect
              options={sortOptions}
              value={filters.sortBy}
              onChange={(value) => handleFilterChange({ sortBy: value })}
            />
          </div>

          {/* 排序顺序 */}
          <div className="form-group">
            <label className="form-label">
              排序顺序
            </label>
            <CustomSelect
              options={sortOrderOptions}
              value={filters.sortOrder}
              onChange={(value) => handleFilterChange({ sortOrder: value })}
            />
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex justify-between items-center mt-6 pt-4 border-t border-gray-100">
          <div className="flex items-center space-x-4">
            <div className="text-sm text-gray-600 font-medium">
              共 {pagination.total} 个匹配结果
            </div>
            {selectedResults.size > 0 && (
              <div className="text-sm text-blue-600 font-medium">
                已选择 {selectedResults.size} 个
              </div>
            )}
          </div>
          <div className="flex items-center space-x-3">
            {/* 批量操作按钮 */}
            {selectedResults.size > 0 && (
              <>
                <button
                  onClick={() => setBatchDeleteConfirm({
                    show: true,
                    resultIds: Array.from(selectedResults)
                  })}
                  disabled={batchOperationLoading}
                  className={`btn btn-danger btn-sm ${batchOperationLoading ? 'opacity-75 cursor-not-allowed' : ''}`}
                >
                  {batchOperationLoading && (
                    <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                  )}
                  {batchOperationLoading ? '删除中...' : `批量删除 (${selectedResults.size})`}
                </button>
                <button
                  onClick={() => setSelectedResults(new Set())}
                  disabled={batchOperationLoading}
                  className={`btn btn-secondary btn-sm ${batchOperationLoading ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                  取消选择
                </button>
              </>
            )}
            <button
              onClick={() => {
                loadResults();
                loadStatistics();
              }}
              className="btn btn-secondary btn-sm"
            >
              刷新
            </button>
          </div>
        </div>
      </div>

      {/* 错误信息 */}
      {error && (
        <ErrorMessage
          message={error}
          onDismiss={() => setError(null)}
        />
      )}

      {/* 结果列表 */}
      {results.length === 0 ? (
        <EmptyState
          title="暂无匹配结果"
          description="还没有任何模板匹配结果，请先执行模板匹配操作。"
          icon="📊"
        />
      ) : (
        <div className="space-y-4">
          {/* 列表控制栏 */}
          <div className="flex items-center justify-between bg-white rounded-lg shadow-sm border border-gray-200/50 p-4">
            <div className="flex items-center space-x-3">
              <label className={`flex items-center space-x-2 ${batchOperationLoading ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}>
                <input
                  type="checkbox"
                  checked={selectedResults.size === results.length && results.length > 0}
                  onChange={handleToggleSelectAll}
                  disabled={batchOperationLoading}
                  className="form-checkbox h-4 w-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500 disabled:opacity-50"
                />
                <span className="text-sm font-medium text-gray-700">
                  {selectedResults.size === results.length && results.length > 0 ? '取消全选' : '全选'}
                </span>
              </label>
              {selectedResults.size > 0 && (
                <span className="text-sm text-gray-500">
                  已选择 {selectedResults.size} / {results.length} 个结果
                </span>
              )}
            </div>
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-500">
                显示导出状态
              </span>
              <div className="flex items-center space-x-1">
                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                  ✓ 已导出
                </span>
                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                  ○ 未导出
                </span>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {results.map((result) => (
              <TemplateMatchingResultCard
                key={result.id}
                result={result}
                onViewDetail={() => handleViewDetail(result)}
                onDelete={() => setDeleteConfirm({ show: true, result })}
                onExportToJianying={() => handleExportToJianying(result)}
                onExportToJianyingV2={() => handleExportToJianyingV2(result)}
                isSelected={selectedResults.has(result.id)}
                onToggleSelect={() => !batchOperationLoading && handleToggleSelect(result.id)}
                showExportStatus={true}
                disabled={batchOperationLoading}
              />
            ))}
          </div>
        </div>
      )}

      {/* 分页 */}
      {pagination.total > pagination.pageSize && (
        <div className="pagination-section mt-6 flex justify-center">
          <div className="flex items-center space-x-2">
            <button
              onClick={() => handlePageChange(pagination.page - 1)}
              disabled={pagination.page <= 1}
              className="px-3 py-2 border border-gray-300 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
            >
              上一页
            </button>
            <span className="px-3 py-2 text-sm text-gray-700">
              第 {pagination.page} 页，共 {Math.ceil(pagination.total / pagination.pageSize)} 页
            </span>
            <button
              onClick={() => handlePageChange(pagination.page + 1)}
              disabled={pagination.page >= Math.ceil(pagination.total / pagination.pageSize)}
              className="px-3 py-2 border border-gray-300 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* 详情模态框 */}
      {showDetailModal && selectedResult && (
        <TemplateMatchingResultDetailModal
          resultId={selectedResult.id}
          onClose={() => {
            setShowDetailModal(false);
            setSelectedResult(null);
          }}
          onUpdate={() => {
            loadResults();
            loadStatistics();
          }}
        />
      )}

      {/* 删除确认对话框 */}
      <DeleteConfirmDialog
        isOpen={deleteConfirm.show}
        title="删除匹配结果"
        message={`确定要删除匹配结果 "${deleteConfirm.result?.result_name}" 吗？此操作不可撤销。`}
        onConfirm={() => deleteConfirm.result && handleDelete(deleteConfirm.result)}
        onCancel={() => setDeleteConfirm({ show: false, result: null })}
      />

      {/* 批量删除确认对话框 */}
      <DeleteConfirmDialog
        isOpen={batchDeleteConfirm.show}
        title="批量删除匹配结果"
        message={`确定要删除选中的 ${batchDeleteConfirm.resultIds.length} 个匹配结果吗？此操作将同时重置相关资源的使用状态，且不可撤销。`}
        deleting={batchOperationLoading}
        onConfirm={handleConfirmBatchDelete}
        onCancel={() => !batchOperationLoading && setBatchDeleteConfirm({ show: false, resultIds: [] })}
      />

      {/* 批量操作Loading遮罩 */}
      {batchOperationLoading && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 shadow-xl max-w-sm w-full mx-4">
            <div className="flex items-center space-x-3">
              <svg className="animate-spin h-6 w-6 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <div>
                <h3 className="text-lg font-medium text-gray-900">正在删除匹配结果</h3>
                <p className="text-sm text-gray-500">正在删除 {selectedResults.size} 个匹配结果并重置资源状态...</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
