'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import TwitterCallbackModal from '@/components/common/TwitterCallbackModal';

export default function TwitterAuthCallbackPage() {
  const router = useRouter();
  const [callbackParams, setCallbackParams] = useState<{ state: string; code: string } | null>(null);
  const [project, setProject] = useState<any>(null);

  useEffect(() => {
    // 解析回调参数
    const searchParams = new URLSearchParams(window.location.search);
    const state = searchParams.get('state');
    const code = searchParams.get('code');

    if (state && code) {
      setCallbackParams({ state, code });

      // 从 localStorage 获取项目信息
      const storedProject = localStorage.getItem('currentShareProject');
      if (storedProject) {
        try {
          const parsedProject = JSON.parse(storedProject);
          setProject(parsedProject);
        } catch (error) {
          console.error('解析项目信息失败:', error);
          setProject({ project_id: '', name: '未知项目', final_video_url: '' });
        }
      } else {
        setProject({ project_id: '', name: '未知项目', final_video_url: '' });
      }

      // 清理 URL 参数
      const cleanUrl = window.location.pathname;
      window.history.replaceState({}, document.title, cleanUrl);
    } else {
      // 如果没有参数，重定向到主页面
      router.push('/movies');
    }
  }, [router]);

  const handleCloseModal = () => {
    // 清理 localStorage 中的临时数据
    try {
      localStorage.removeItem('twitterAuthCallbackPayload');
      localStorage.removeItem('twitterAuthCallbackFlag');
    } catch (error) {
      console.error('清理 localStorage 失败:', error);
    }
    setCallbackParams(null);
    router.push('/movies');
  };

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-900 text-white">
      {callbackParams && project && (
        <TwitterCallbackModal
          visible={true}
          onClose={handleCloseModal}
          project={project}
          urlParams={callbackParams}
        />
      )}
      {!callbackParams && (
        <p>处理 Twitter 授权回调...</p>
      )}
    </div>
  );
}
