import React, { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { useUser } from '../contexts/UserContext';
import { PageWrapper } from '../styles/shared';

const AuthCallbackPage = () => {
  const navigate = useNavigate();
  const { handleSSOCallback, fetchMe, clearSession } = useUser();
  const processed = useRef(false);

  useEffect(() => {
    if (processed.current) return;
    processed.current = true;

    const hash = window.location.hash.substring(1);
    const params = new URLSearchParams(hash);

    const token = params.get('token');
    const expiresAt = params.get('expiresAt');
    const account = params.get('account');
    const username = params.get('username');

    if (!token) {
      navigate('/login', { replace: true });
      return;
    }

    handleSSOCallback(token, expiresAt, account, username);

    fetchMe()
      .then((ok) => {
        if (ok) {
          navigate('/', { replace: true });
          return;
        }
        toast.error('无法同步账户信息，请重新登录');
        clearSession();
        navigate('/login', { replace: true });
      })
      .catch(() => {
        toast.error('网络异常，请稍后重试');
        clearSession();
        navigate('/login', { replace: true });
      });
  }, [navigate, handleSSOCallback, fetchMe, clearSession]);

  return (
    <PageWrapper className="flex items-center justify-center text-center">
      <div>
        <div className="flex gap-2 justify-center mb-4">
          {[0, 0.2, 0.4].map((delay, i) => (
            <div
              key={i}
              className="w-2.5 h-2.5 rounded-full bg-[#81c784]"
              style={{
                animation: `dotBounce 1.4s ease-in-out infinite ${delay}s`,
              }}
            />
          ))}
        </div>
        <p className="text-gray-500 text-base">正在登录，请稍候...</p>
      </div>
      <style>{`
        @keyframes dotBounce {
          0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
          40% { transform: scale(1.2); opacity: 1; }
        }
      `}</style>
    </PageWrapper>
  );
};

export default AuthCallbackPage;
