import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  ExportRecord,
  ExportRecordQueryOptions,
  ExportRecordStatistics,
  ExportType,
  ExportStatus
} from '../types/exportRecord';
import { DataTable, Column, TableAction } from './DataTable';
import { InteractiveButton } from './InteractiveButton';
import { SearchInput } from './InteractiveInput';
import { CustomSelect } from './CustomSelect';
import { DeleteConfirmDialog } from './DeleteConfirmDialog';
import {
  FileText,
  Download,
  RefreshCw,
  Trash2,
  Search,
  CheckCircle,
  XCircle,
  Clock,
  AlertCircle,
  BarChart3,
  FileSpreadsheet,
  FileJson,
  Film
} from 'lucide-react';
import DirectorySettingsButton from './DirectorySettingsButton';

interface ExportRecordManagerProps {
  projectId?: string;
  matchingResultId?: string;
  showHeader?: boolean; // 是否显示标题和描述
  compact?: boolean; // 紧凑模式，适用于tab显示
}

const ExportRecordManager: React.FC<ExportRecordManagerProps> = ({
  projectId,
  matchingResultId,
  showHeader = true,
  compact = false
}) => {
  const [records, setRecords] = useState<ExportRecord[]>([]);
  const [statistics, setStatistics] = useState<ExportRecordStatistics | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedRecords, setSelectedRecords] = useState<ExportRecord[]>([]);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [recordToDelete, setRecordToDelete] = useState<string | null>(null);

  // 过滤和分页状态
  const [filters, setFilters] = useState({
    export_type: '' as ExportType | '',
    export_status: '' as ExportStatus | '',
    search_keyword: '',
  });
  const [pagination, setPagination] = useState({
    page: 1,
    page_size: 20,
    total: 0,
  });

  // 加载导出记录列表
  const loadExportRecords = async () => {
    setLoading(true);
    setError(null);

    try {
      const options: ExportRecordQueryOptions = {
        project_id: projectId,
        matching_result_id: matchingResultId,
        export_type: filters.export_type || undefined,
        export_status: filters.export_status || undefined,
        search_keyword: filters.search_keyword || undefined,
        limit: pagination.page_size,
        offset: (pagination.page - 1) * pagination.page_size,
        sort_by: 'created_at',
        sort_order: 'desc',
      };

      const result = await invoke<ExportRecord[]>('list_export_records', { options });
      setRecords(result);

      // 更新总数（这里简化处理，实际应该从后端返回）
      setPagination(prev => ({ ...prev, total: result.length }));
    } catch (err) {
      setError(`加载导出记录失败: ${err}`);
    } finally {
      setLoading(false);
    }
  };

  // 加载统计信息
  const loadStatistics = async () => {
    try {
      let stats: ExportRecordStatistics;
      if (projectId) {
        stats = await invoke<ExportRecordStatistics>('get_project_export_statistics', {
          projectId
        });
      } else {
        stats = await invoke<ExportRecordStatistics>('get_global_export_statistics');
      }
      setStatistics(stats);
    } catch (err) {
      console.error('加载统计信息失败:', err);
    }
  };

  // 删除导出记录
  const handleDeleteRecord = async (recordId: string) => {
    setRecordToDelete(recordId);
    setDeleteDialogOpen(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    if (!recordToDelete) return;

    try {
      await invoke('delete_export_record', { recordId: recordToDelete });
      await loadExportRecords();
      await loadStatistics();
      setDeleteDialogOpen(false);
      setRecordToDelete(null);
    } catch (err) {
      setError(`删除导出记录失败: ${err}`);
    }
  };

  // 验证文件是否存在
  const handleValidateFile = async (recordId: string) => {
    try {
      const exists = await invoke<boolean>('validate_export_file', { recordId });
      // 这里应该使用项目的通知系统而不是alert
      console.log(exists ? '文件存在' : '文件不存在');
    } catch (err) {
      setError(`验证文件失败: ${err}`);
    }
  };

  // 重新导出
  const handleReExport = async (recordId: string) => {
    try {
      // 使用新的剪影导出路径选择命令
      const selected = await invoke<string | null>('select_jianying_export_path', {
        defaultFilename: 'draft_content_reexport.json'
      });

      if (selected) {
        await invoke('re_export_record', {
          recordId,
          newFilePath: selected
        });

        // 重新导出成功后刷新导出记录列表
        await loadExportRecords();
        console.log('重新导出成功，已刷新导出记录列表');
      }
    } catch (err) {
      setError(`重新导出失败: ${err}`);
    }
  };

  // 清理过期记录
  const handleCleanupExpired = async () => {
    // 这里应该使用自定义对话框而不是prompt
    const days = 30; // 默认30天，后续可以改为对话框输入

    try {
      const count = await invoke<number>('cleanup_expired_export_records', {
        days
      });
      console.log(`已清理 ${count} 条过期记录`);
      await loadExportRecords();
      await loadStatistics();
    } catch (err) {
      setError(`清理过期记录失败: ${err}`);
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes?: number): string => {
    if (!bytes) return '-';
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
  };

  // 格式化持续时间
  const formatDuration = (ms: number): string => {
    if (ms < 1000) return `${ms}ms`;
    const seconds = Math.floor(ms / 1000);
    if (seconds < 60) return `${seconds}s`;
    const minutes = Math.floor(seconds / 60);
    return `${minutes}m ${seconds % 60}s`;
  };

  // 获取状态颜色和图标
  const getStatusInfo = (status: ExportStatus) => {
    switch (status) {
      case ExportStatus.Success:
        return {
          color: 'text-green-600',
          bgColor: 'bg-green-50',
          icon: <CheckCircle className="w-4 h-4" />,
          text: '成功'
        };
      case ExportStatus.Failed:
        return {
          color: 'text-red-600',
          bgColor: 'bg-red-50',
          icon: <XCircle className="w-4 h-4" />,
          text: '失败'
        };
      case ExportStatus.InProgress:
        return {
          color: 'text-blue-600',
          bgColor: 'bg-blue-50',
          icon: <Clock className="w-4 h-4" />,
          text: '进行中'
        };
      case ExportStatus.Cancelled:
        return {
          color: 'text-gray-600',
          bgColor: 'bg-gray-50',
          icon: <AlertCircle className="w-4 h-4" />,
          text: '已取消'
        };
      default:
        return {
          color: 'text-gray-600',
          bgColor: 'bg-gray-50',
          icon: <AlertCircle className="w-4 h-4" />,
          text: '未知'
        };
    }
  };

  // 获取类型图标和名称
  const getTypeInfo = (type: ExportType) => {
    switch (type) {
      case ExportType.JianYingV1:
        return { icon: <Film className="w-4 h-4" />, name: '剪映 V1' };
      case ExportType.JianYingV2:
        return { icon: <Film className="w-4 h-4" />, name: '剪映 V2' };
      case ExportType.Json:
        return { icon: <FileJson className="w-4 h-4" />, name: 'JSON' };
      case ExportType.Csv:
        return { icon: <FileSpreadsheet className="w-4 h-4" />, name: 'CSV' };
      case ExportType.Excel:
        return { icon: <BarChart3 className="w-4 h-4" />, name: 'Excel' };
      default:
        return { icon: <FileText className="w-4 h-4" />, name: '其他' };
    }
  };

  // 定义表格列
  const columns: Column<ExportRecord>[] = [
    {
      key: 'export_type',
      title: '类型',
      width: '120px',
      render: (_, record) => {
        const typeInfo = getTypeInfo(record.export_type);
        return (
          <div className="flex items-center gap-2">
            <span className="text-primary-600">{typeInfo.icon}</span>
            <span className="text-sm font-medium text-gray-900">{typeInfo.name}</span>
          </div>
        );
      }
    },
    {
      key: 'file_path',
      title: '文件路径',
      render: (_, record) => (
        <div className="max-w-xs">
          <div className="text-sm text-gray-900 truncate" title={record.file_path}>
            {record.file_path}
          </div>
        </div>
      )
    },
    {
      key: 'export_status',
      title: '状态',
      width: '120px',
      render: (_, record) => {
        const statusInfo = getStatusInfo(record.export_status);
        return (
          <div className="flex items-center gap-2">
            <div className={`flex items-center gap-1 px-2 py-1 rounded-full ${statusInfo.bgColor}`}>
              <span className={statusInfo.color}>{statusInfo.icon}</span>
              <span className={`text-xs font-medium ${statusInfo.color}`}>
                {statusInfo.text}
              </span>
            </div>
          </div>
        );
      }
    },
    {
      key: 'file_size',
      title: '文件大小',
      width: '100px',
      align: 'right' as const,
      render: (_, record) => (
        <span className="text-sm text-gray-900">
          {formatFileSize(record.file_size)}
        </span>
      )
    },
    {
      key: 'export_duration_ms',
      title: '耗时',
      width: '80px',
      align: 'right' as const,
      render: (_, record) => (
        <span className="text-sm text-gray-900">
          {formatDuration(record.export_duration_ms)}
        </span>
      )
    },
    {
      key: 'created_at',
      title: '创建时间',
      width: '160px',
      render: (_, record) => (
        <span className="text-sm text-gray-900">
          {new Date(record.created_at).toLocaleString()}
        </span>
      )
    }
  ];

  // 定义表格操作
  const tableActions: TableAction<ExportRecord>[] = [
    {
      key: 'validate',
      label: '验证文件',
      icon: <Search className="w-4 h-4" />,
      onClick: (record) => handleValidateFile(record.id),
      variant: 'ghost'
    },
    {
      key: 'reexport',
      label: '重新导出',
      icon: <RefreshCw className="w-4 h-4" />,
      onClick: (record) => handleReExport(record.id),
      variant: 'ghost'
    },
    {
      key: 'delete',
      label: '删除',
      icon: <Trash2 className="w-4 h-4" />,
      onClick: (record) => handleDeleteRecord(record.id),
      variant: 'danger'
    }
  ];

  useEffect(() => {
    loadExportRecords();
    loadStatistics();
  }, [projectId, matchingResultId, filters, pagination.page]);

  return (
    <div className={`export-record-manager ${compact ? 'p-0' : 'p-6'} animate-fade-in`}>
      {showHeader && (
        <div className="page-header mb-6">
          <h2 className="text-2xl font-bold text-gradient-primary mb-2">
            导出记录管理
          </h2>
          <p className="text-gray-600 text-sm">
            管理和查看所有导出记录
            {projectId && <span className="ml-2 px-2 py-1 bg-blue-50 text-blue-600 rounded-full text-xs">(项目范围)</span>}
            {matchingResultId && <span className="ml-2 px-2 py-1 bg-purple-50 text-purple-600 rounded-full text-xs">(匹配结果范围)</span>}
          </p>
        </div>
      )}

      <div className="content space-y-6">
        {/* 统计信息 */}
        {statistics && (
          <div className={`grid ${compact ? 'grid-cols-2 md:grid-cols-4 gap-3' : 'grid-cols-2 md:grid-cols-4 gap-4'}`}>
            {/* 总导出次数 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-500">总导出次数</p>
                  <p className={`${compact ? 'text-xl' : 'text-2xl'} font-bold text-gray-900`}>
                    {statistics.total_exports}
                  </p>
                </div>
                <div className="text-2xl opacity-60">
                  <BarChart3 className="w-8 h-8 text-primary-600" />
                </div>
              </div>
            </div>

            {/* 成功导出 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-500">成功导出</p>
                  <p className={`${compact ? 'text-xl' : 'text-2xl'} font-bold text-green-600`}>
                    {statistics.successful_exports}
                  </p>
                  {statistics.total_exports > 0 && (
                    <p className="text-xs text-gray-400 mt-1">
                      {((statistics.successful_exports / statistics.total_exports) * 100).toFixed(1)}% 成功率
                    </p>
                  )}
                </div>
                <div className="text-2xl opacity-60">
                  <CheckCircle className="w-8 h-8 text-green-600" />
                </div>
              </div>
            </div>

            {/* 失败导出 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-500">失败导出</p>
                  <p className={`${compact ? 'text-xl' : 'text-2xl'} font-bold text-red-600`}>
                    {statistics.failed_exports}
                  </p>
                  {statistics.total_exports > 0 && (
                    <p className="text-xs text-gray-400 mt-1">
                      {((statistics.failed_exports / statistics.total_exports) * 100).toFixed(1)}% 失败率
                    </p>
                  )}
                </div>
                <div className="text-2xl opacity-60">
                  <XCircle className="w-8 h-8 text-red-600" />
                </div>
              </div>
            </div>

            {/* 总文件大小 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-500">总文件大小</p>
                  <p className={`${compact ? 'text-xl' : 'text-2xl'} font-bold text-purple-600`}>
                    {formatFileSize(statistics.total_file_size)}
                  </p>
                  {statistics.total_exports > 0 && (
                    <p className="text-xs text-gray-400 mt-1">
                      平均 {formatFileSize(statistics.total_file_size / statistics.total_exports)}
                    </p>
                  )}
                </div>
                <div className="text-2xl opacity-60">
                  <Download className="w-8 h-8 text-purple-600" />
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 过滤器 */}
        <div className={`card ${compact ? 'mb-4' : 'mb-6'}`}>
          <div className="card-body">
            <div className="flex flex-wrap gap-4 items-end">
              {/* 搜索框 */}
              <div className="flex-1 min-w-64">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  搜索文件路径
                </label>
                <SearchInput
                  value={filters.search_keyword}
                  onChange={(value) => setFilters(prev => ({ ...prev, search_keyword: value }))}
                  placeholder="搜索文件路径..."
                  className="w-full"
                />
              </div>

              {/* 导出类型过滤 */}
              <div className="min-w-40">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  导出类型
                </label>
                <CustomSelect
                  value={filters.export_type}
                  onChange={(value) => setFilters(prev => ({ ...prev, export_type: value as ExportType | '' }))}
                  options={[
                    { value: '', label: '所有类型' },
                    { value: ExportType.JianYingV1, label: '剪映 V1' },
                    { value: ExportType.JianYingV2, label: '剪映 V2' },
                    { value: ExportType.Json, label: 'JSON' },
                    { value: ExportType.Csv, label: 'CSV' },
                    { value: ExportType.Excel, label: 'Excel' }
                  ]}
                />
              </div>

              {/* 状态过滤 */}
              <div className="min-w-32">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  状态
                </label>
                <CustomSelect
                  value={filters.export_status}
                  onChange={(value) => setFilters(prev => ({ ...prev, export_status: value as ExportStatus | '' }))}
                  options={[
                    { value: '', label: '所有状态' },
                    { value: ExportStatus.Success, label: '成功' },
                    { value: ExportStatus.Failed, label: '失败' },
                    { value: ExportStatus.InProgress, label: '进行中' },
                    { value: ExportStatus.Cancelled, label: '已取消' }
                  ]}
                />
              </div>

              {/* 操作按钮 */}
              <div className="flex gap-2">
                <InteractiveButton
                  onClick={loadExportRecords}
                  variant="secondary"
                  icon={<RefreshCw className="w-4 h-4" />}
                  loading={loading}
                >
                  刷新
                </InteractiveButton>
                <InteractiveButton
                  onClick={handleCleanupExpired}
                  variant="danger"
                  icon={<Trash2 className="w-4 h-4" />}
                >
                  清理过期
                </InteractiveButton>
                <DirectorySettingsButton size="sm" variant="secondary" />
              </div>
            </div>
          </div>
        </div>
        {/* 错误信息 */}
        {error && (
          <div className="card bg-red-50 border-red-200 mb-6">
            <div className="card-body">
              <div className="flex items-center gap-3">
                <XCircle className="w-5 h-5 text-red-600 flex-shrink-0" />
                <div>
                  <h4 className="text-red-800 font-medium">操作失败</h4>
                  <p className="text-red-700 text-sm mt-1">{error}</p>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 数据表格 */}
        <div className="card">
          <DataTable
            data={records}
            columns={columns}
            actions={tableActions}
            loading={loading}
            searchable={false} // 我们已经有自定义搜索
            sortable={true}
            pagination={true}
            pageSize={pagination.page_size}
            emptyText="暂无导出记录"
            selectedRows={selectedRecords}
            onSelectionChange={setSelectedRecords}
            rowKey="id"
          />
        </div>
      </div>

      {/* 删除确认对话框 */}
      <DeleteConfirmDialog
        isOpen={deleteDialogOpen}
        onCancel={() => {
          setDeleteDialogOpen(false);
          setRecordToDelete(null);
        }}
        onConfirm={confirmDelete}
        title="删除导出记录"
        message="确定要删除这条导出记录吗？此操作无法撤销。"
      />

    </div>
  );
};

export default ExportRecordManager;
