import { Template } from '@/sdk/sdk-server';
import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useServerSdk } from '../../hooks/index';
import { useI18n } from '../../hooks/useI18n';
import { i18nManager } from '../../i18n/manager';

// 导入组件
import UploadCard from './components/UploadCard';


import './index.css';

export default function FriendsPhoto() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const templateCode = searchParams.get('templateCode');
  const [template, setTemplate] = useState<Template | null>(null);

  console.log(template);

  const { t } = useI18n();
  const serverSdk = useServerSdk();

  const [loading, setLoading] = useState(false);
  const [image1, setImage1] = useState<string>('');
  const [image2, setImage2] = useState<string>('');

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

  useEffect(() => {
    const fetchTemplate = async () => {
      if (!templateCode) return;
      const template = await serverSdk.getTemplate(templateCode);
      setTemplate(template);
    };
    fetchTemplate();
  }, [templateCode]);

  // 提交处理
  const handleSubmit = async () => {
    if (!templateCode) {
      alert(t('friendsPhoto.templateCodeNotSet'));
      return;
    }
    if (!image1 || !image2) {
      alert(t('friendsPhoto.uploadTwoImages'));
      return;
    }

    setLoading(true);

    try {
      // 将两个图片URL用逗号分隔
      const combinedImageUrl = `${image1},${image2}`;

      const taskId = await serverSdk.executeTemplate({
        imageUrl: combinedImageUrl,
        templateCode: templateCode,
      });

      // 跳转到结果页面
      navigate(`/result?taskId=${taskId}&templateCode=${templateCode}`);
    } catch (error) {
      console.error('提交失败:', error);
      alert(t('friendsPhoto.waitForTaskCompletion'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="friends-photo">
      {/* 上传区域 */}
      <div className="upload-section">
        <UploadCard imageUrl={image1} title={t('friendsPhoto.selectYourPhoto')} onUploadSuccess={setImage1} />
        <UploadCard imageUrl={image2} title={t('friendsPhoto.selectFriendPhoto')} onUploadSuccess={setImage2} />
      </div>

      {/* 固定底部按钮 */}
      <div className="submit-section">
        <button
          className={`submit-button ${!image1 || !image2 || loading ? 'disabled' : ''}`}
          disabled={!image1 || !image2 || loading}
          onClick={handleSubmit}
        >
          {loading ? (
            <>
              <div className="loading-spinner" />
              <div className="submit-text">{t('friendsPhoto.generating')}</div>
            </>
          ) : (
            <div className="submit-text">
              ${template?.creditCost} {t('friendsPhoto.startGenerating')}
            </div>
          )}
        </button>
      </div>
    </div>
  );
}
