import { api, Template } from '@/services/api';
import { auth } from '@/services/auth';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useI18n } from '../../hooks/useI18n';
import { i18nManager } from '../../i18n/manager';
import UploadCard from './components/UploadCard';
import './index.css';

export default function Create() {
  const { templateCode } = useParams();
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
  const [loginRedirecting, setLoginRedirecting] = useState(false);

  const [template, setTemplate] = useState<Template | null>(null);

  useEffect(() => {
    const checkLogin = async () => {
      // Check login status, including OAuth 2.0 callback handling
      const isLoggedIn = await auth.checkLogin();
      setIsLoggedIn(isLoggedIn);
    };
    checkLogin();
  }, []);

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

  const { t } = useI18n();

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

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

  // 提交处理
  const handleSubmit = async () => {
    if (!isLoggedIn) {
      setLoginRedirecting(true);
      setLoading(true);
      await auth.login(window.location.pathname);
      return;
    }
    if (!templateCode) {
      alert('Template code not set');
      return;
    }
    if (!image1 || (template?.imageCount === 2 && !image2)) {
      alert('Upload two images');
      return;
    }

    setLoading(true);

    try {
      // 将两个图片URL用逗号分隔
      const { hostname, protocol, port } = window.location;
      let baseUrl = `${protocol}//${hostname}`;
      if (hostname === 'localhost') {
        baseUrl = `${protocol}//${hostname}:${port}`;
      }
      const cbUrl = `${baseUrl}/result`;
      const checkout = await api.createCheckoutSession({
        templateCode: templateCode,
        metadata: {
          cb_url: cbUrl,
          imageUrls: [image1, image2 || image1],
        },
      });
      if (checkout && checkout.url) {
        window.location.href = checkout.url;
      }
      // 跳转到结果页面
      // navigate(`/result?taskId=${taskId}&templateCode=${templateCode}`);
    } catch (error) {
      console.error('提交失败:', error);
      alert('Wait for task completion');
    } finally {
      setLoading(false);
    }
  };

  // // If not authenticated, show login prompt

  if (loginRedirecting) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <div>Redirecting to login...</div>
      </div>
    );
  }

  if (!template) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <div>Loading...</div>
      </div>
    );
  }

  return (
    <div className="friends-photo">
      {/* 上传区域 */}
      <div className="upload-section">
        <UploadCard
          disabled={!isLoggedIn}
          imageUrl={image1}
          title={t('friendsPhoto.selectYourPhoto')}
          onUploadSuccess={setImage1}
          onLogin={() => {
            setLoginRedirecting(true);
            auth.login(window.location.pathname);
          }}
        />
        {template?.imageCount === 2 && (
          <UploadCard
            disabled={!isLoggedIn}
            imageUrl={image2}
            title={t('friendsPhoto.selectFriendPhoto')}
            onUploadSuccess={setImage2}
            onLogin={() => {
              setLoginRedirecting(true);
              auth.login(window.location.pathname);
            }}
          />
        )}
      </div>

      {/* 固定底部按钮 */}
      <div className="submit-section">
        <button
          className={`submit-button ${(!image1 || (template?.imageCount === 2 && !image2) || loading) && isLoggedIn ? 'disabled' : ''}`}
          disabled={(!image1 || (template?.imageCount === 2 && !image2) || loading) && isLoggedIn}
          onClick={handleSubmit}
        >
          {isLoggedIn === false ? (
            <div className="submit-text">Login to Generate</div>
          ) : loading ? (
            <>
              <div className="loading-spinner" style={{ margin: 'auto' }} />
            </>
          ) : (
            <div className="submit-text">{t('friendsPhoto.startGenerating')}</div>
          )}
        </button>
      </div>
    </div>
  );
}
