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

const CenterWrap = styled(PageWrapper)`
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
`;

const Dots = styled.div`
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-bottom: 16px;
`;

const Dot = styled.div`
  width: 10px; height: 10px;
  border-radius: 50%;
  background: #81c784;
  animation: dotBounce 1.4s ease-in-out infinite;
  animation-delay: ${props => props.$delay || '0s'};

  @keyframes dotBounce {
    0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
    40% { transform: scale(1.2); opacity: 1; }
  }
`;

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 (
    <CenterWrap>
      <div>
        <Dots>
          <Dot $delay="0s" />
          <Dot $delay="0.2s" />
          <Dot $delay="0.4s" />
        </Dots>
        <p style={{ color: '#666', fontSize: '16px' }}>正在登录，请稍候...</p>
      </div>
    </CenterWrap>
  );
};

export default AuthCallbackPage;
