import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useServerSdk } from '../../hooks/index';
import { useI18n } from '../../hooks/useI18n';
import { i18nManager } from '../../i18n/manager';
// import LanguageSwitcher from '../../components/LanguageSwitcher'; // 已隐藏 - 只支持英语
import './index.css';
export default function History() {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [records, setRecords] = useState<any[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(true);
  const serverSdk = useServerSdk();

  // 计算生成中任务的进度（暂时未使用，但保留以备后用）
  // const calculateProgress = (record: any) => {
  //   if (!record?.createdAt || record.status !== 'processing') return 0;

  //   const createdAt = new Date(record.createdAt).getTime();
  //   const now = Date.now();
  //   const elapsedMinutes = (now - createdAt) / (1000 * 60);

  //   // 根据任务类型确定预计时间
  //   const isVideo = record.taskType === 'video' || record.outputType === 'video' || record.type === 'video';
  //   const estimatedTime = isVideo ? 2.5 : 1; // 视频2.5分钟，图片1分钟

  //   // 计算进度百分比，最大95%
  //   const calculatedProgress = Math.min((elapsedMinutes / estimatedTime) * 100, 95);
  //   return Math.max(calculatedProgress, 0);
  // };

  const loadRecords = async () => {
    try {
      const logs = await serverSdk.getMineLogs();
      setRecords(logs || []);
    } catch (error) {
      console.error('加载记录失败:', error);
      alert(t('common.operationFailed'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRecords();
    // 设置页面标题
    i18nManager.updateNavigationBarTitle('history');
  }, []);

  // 定时更新生成中任务的进度
  useEffect(() => {
    const hasGeneratingTasks = records.some(record => record.status === 'processing');
    if (!hasGeneratingTasks) return;

    const interval = setInterval(() => {
      // 触发重新渲染以更新进度
      setRecords(prevRecords => [...prevRecords]);
    }, 1000);

    return () => clearInterval(interval);
  }, [records]);

  // 下拉刷新
  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await loadRecords();
      alert(t('home.refreshSuccess'));
    } catch (error) {
      console.error('刷新失败:', error);
      alert(t('home.refreshFailed'));
    } finally {
      setRefreshing(false);
    }
  };

  // 点击历史记录项
  const handleItemClick = (record: any) => {
    if (record.status === 'completed' && record.outputUrl) {
      // 跳转到结果页面查看
      navigate(`/result?taskId=${record.executionId}`);
    } else if (record.status === 'failed') {
      // 显示错误信息
      alert(`${t('common.operationFailed')}\n${record.errorMessage || t('common.operationFailed')}`);
    } else if (record.status === 'processing') {
      // 跳转到生成页面查看进度
      navigate(`/result?taskId=${record.executionId}`);
    }
  };

  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  return (
    <div className="history">
      {/* 设置区域 */}
      <div className="history-header">
        <div className="header-content">
          <span className="history-title">{t('navigation.mine')}</span>
          {/* 语言切换器已隐藏 - 只支持英语 */}
        </div>
      </div>

      <div className="history-list">
        <div className="refresh-area" onClick={handleRefresh}>
          {refreshing && <div className="refresh-indicator">刷新中...</div>}
        </div>
        <div className="history-grid">
          {loading ? (
            <div className="loading-state">
              <span className="loading-text">{t('common.loading')}</span>
            </div>
          ) : records.length === 0 ? (
            <div className="empty-state">
              <img className="empty-icon-image" src="/assets/icons/cloud.png" alt="empty" />
              <span className="empty-text">{t('history.noRecords')}</span>
            </div>
          ) : (
            records.map(record => {
              // const progress = calculateProgress(record); // 暂时未使用
              const isGenerating = record.status === 'processing';
              return (
                <div key={record.id} className="history-item" onClick={() => handleItemClick(record)}>
                  <div className="item-thumbnail">
                    {record.status === 'completed' && record.outputResult ? (
                      <img className="thumbnail-image" src={record.inputImageUrl.split(',')[0]} alt="thumbnail" />
                    ) : (
                      <div className={`thumbnail-placeholder ${record.status}`}>
                        <img className="thumbnail-image" src={record.inputImageUrl.split(',')[0]} alt="thumbnail" />
                        {/* 生成中状态的扫描效果 */}
                        {isGenerating && (
                          <div className="thumbnail-overlay">
                            <div className="thumbnail-progress-overlay" />
                            <div className="thumbnail-scan-light" />
                            {/* 加载loading 转圈 */}
                            <div className="thumbnail-loader" />
                          </div>
                        )}
                      </div>
                    )}
                  </div>

                  <div className="item-content">
                    <div className="item-header">
                      <span className="item-title">{record.templateName}</span>
                    </div>
                    <div className="item-info">
                      <span className="item-time">{formatTime(record.createdAt)}</span>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}
