import React, { useState, useEffect } from 'react';
import { Typography, Spin, Button, App } from 'antd';
import { ClockCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { juliang_callback, getOAuthList } from '../api';

const AuthorizationWaitingPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { message } = App.useApp();
  const [countdown, setCountdown] = useState(0);
  const [isChecking, setIsChecking] = useState(true);
  const [authSuccess, setAuthSuccess] = useState(false);
  const [authError, setAuthError] = useState('');

  useEffect(() => {
    const authCode = searchParams.get('auth_code');
    const state = searchParams.get('state');

    if (!authCode || !state) {
      setIsChecking(false);
      setCountdown(10);
      return;
    }

    const params = {
      auth_code: authCode,
      state: state,
      app_id: searchParams.get('app_id') || undefined,
      material_auth_status: searchParams.get('material_auth_status') || undefined,
      scope: searchParams.get('scope') || undefined,
      uid: searchParams.get('uid') || undefined,
    };

    const handleCallback = async () => {
      try {
        const res = await juliang_callback(params);
        setAuthSuccess(true);
        setIsChecking(false);
        message.success(res?.message || '授权成功');
        setTimeout(() => {
          navigate('/authorization');
        }, 1500);
      } catch (error: any) {
        const errorMsg = error?.message || '授权失败';
        setAuthError(errorMsg);
        setIsChecking(false);
        message.error(errorMsg);
      }
    };

    handleCallback();

    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev >= 11) {
          setIsChecking(false);
          return prev;
        }
        return prev + 1;
      });
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, [navigate, searchParams, message]);

  const handleRetry = () => {
    setCountdown(0);
    setIsChecking(true);
    setAuthSuccess(false);
    setAuthError('');
    window.location.href = '/authorization';
  };

  if (authSuccess) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)' }}>
        <div style={{ textAlign: 'center', padding: '60px 80px', background: '#fff', borderRadius: 16, boxShadow: '0 10px 40px rgba(0,0,0,0.1)' }}>
          <div style={{ width: 80, height: 80, background: '#dcfce7', borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center', margin: '0 auto 24px' }}>
            <Typography.Text style={{ fontSize: 40, color: '#22c55e' }}>✓</Typography.Text>
          </div>
          <Typography.Title level={3} style={{ marginBottom: 16, color: '#1e293b' }}>授权成功</Typography.Title>
          <Typography.Text style={{ color: '#64748b' }}>正在跳转至授权管理页面...</Typography.Text>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)' }}>
      <div style={{ textAlign: 'center', padding: '60px 80px', background: '#fff', borderRadius: 16, boxShadow: '0 10px 40px rgba(0,0,0,0.1)' }}>
        <div style={{ width: 80, height: 80, background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center', margin: '0 auto 24px' }}>
          {isChecking && countdown < 10 ? (
            <Spin size="large" tip="加载中" style={{ color: '#fff' }} />
          ) : (
            <ClockCircleOutlined style={{ fontSize: 40, color: '#fff' }} />
          )}
        </div>
        
        {authError ? (
          <>
            <Typography.Title level={3} style={{ marginBottom: 16, color: '#ef4444' }}>授权失败</Typography.Title>
            <Typography.Text style={{ color: '#64748b', marginBottom: 24, display: 'block' }}>{authError}</Typography.Text>
            <Button
              type="primary"
              size="large"
              icon={<ReloadOutlined />}
              onClick={handleRetry}
              style={{
                borderRadius: 8,
                background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                border: 'none',
                fontWeight: 600,
                padding: '12px 32px',
              }}
            >
              重新授权
            </Button>
          </>
        ) : countdown >= 10 ? (
          <>
            <Typography.Title level={3} style={{ marginBottom: 16, color: '#ef4444' }}>授权无响应</Typography.Title>
            <Typography.Text style={{ color: '#64748b', marginBottom: 24, display: 'block' }}>请重新授权</Typography.Text>
            <Button
              type="primary"
              size="large"
              icon={<ReloadOutlined />}
              onClick={handleRetry}
              style={{
                borderRadius: 8,
                background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                border: 'none',
                fontWeight: 600,
                padding: '12px 32px',
              }}
            >
              重新授权
            </Button>
          </>
        ) : (
          <>
            <Typography.Title level={3} style={{ marginBottom: 16, color: '#1e293b' }}>授权中，请等待</Typography.Title>
            <Typography.Text style={{ color: '#64748b', marginBottom: 24, display: 'block' }}>
              正在等待平台完成授权操作
            </Typography.Text>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              <ClockCircleOutlined style={{ color: '#6366f1' }} />
              <Typography.Text style={{ color: '#6366f1', fontWeight: 500, fontSize: 16 }}>
                {countdown}s
              </Typography.Text>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default AuthorizationWaitingPage;