import React, { useState, useEffect } from 'react';
import { View, Text, Button } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { saveStorageByLoginUser, SERVER_API_URL } from "@/utils/server";
import { checkAndHandleInviteRelation, hasPendingInvite, getStoredInviteParams } from "@/utils/invite";

/**
 * 扫码登录确认页面 - 科技风格授权页
 *
 * 用户扫描 PC 端二维码后，打开此小程序页面进行微信手机号授权登录
 */

// 微信获取手机号回调参数类型
interface GetPhoneNumberDetail {
  code?: string;
  encryptedData?: string;
  iv?: string;
  errMsg: string;
}

interface GetPhoneNumberEvent {
  detail: GetPhoneNumberDetail;
}

// 登录接口返回数据类型
interface LoginResponse {
  data: {
    access_token: string;
    user: any;
  };
  code: number;
  message: string;
}

// 协议类型
type AgreementType = 'service' | 'privacy';

const QRConfirmPage: React.FC = () => {
  const router = useRouter();
  const [authLoading, setAuthLoading] = useState(false); // 授权中状态
  const [agreementChecked, setAgreementChecked] = useState(false); // 协议勾选状态
  const [token, setToken] = useState<string>(''); // 登录 token

  useEffect(() => {
    // 从 URL 参数中获取 token
    const params = router.params;
    let loginToken = params.scene || params.token || params.qrCodeKey || '';

    // 兼容 q 参数（URL 编码的完整 URL）
    if (params.q && !loginToken) {
      try {
        const decodedUrl = decodeURIComponent(params.q);
        const url = new URL(decodedUrl);
        loginToken = url.searchParams.get('token') || url.searchParams.get('qrCodeKey') || '';
      } catch (e) {
        loginToken = decodeURIComponent(params.q);
      }
    }

    setToken(loginToken);
  }, [router.params]);

  /**
   * 处理微信手机号授权
   */
  const handleGetPhoneNumber = async ({ detail }: GetPhoneNumberEvent) => {
    const { code, encryptedData, iv, errMsg } = detail;

    // 检查协议是否勾选
    if (!agreementChecked) {
      Taro.showToast({ title: '请先同意服务协议和隐私政策', icon: 'none' });
      return;
    }

    // 用户拒绝授权
    if (errMsg && errMsg.includes('fail')) {
      Taro.showToast({ title: '需要授权手机号才能完成登录', icon: 'none' });
      return;
    }

    if (!code) {
      Taro.showToast({ title: '获取授权信息失败，请重试', icon: 'none' });
      return;
    }

    await handleAuthLogin(code, encryptedData, iv);
  };

  /**
   * 授权登录
   */
  const handleAuthLogin = async (phoneCode: string, encryptedData?: string, iv?: string) => {
    try {
      setAuthLoading(true);

      // 获取邀请参数
      const inviteParams = getStoredInviteParams();
      const refereeId = inviteParams?.inviter ? parseInt(inviteParams.inviter) : 0;

      const res = await Taro.request<LoginResponse>({
        url: `${SERVER_API_URL}/wx-login/loginByMpWxPhone`,
        method: 'POST',
        data: {
          code: phoneCode,
          encryptedData,
          iv,
          tenantId: 5,
          notVerifyPhone: true,
          refereeId,
          sceneType: 'save_referee'
        },
        header: { 'content-type': 'application/json', 'TenantId': 5 }
      });

      if (res.data.code !== 0) {
        throw new Error(res.data.message || '登录失败');
      }

      if (res.data.data?.user) {
        saveStorageByLoginUser(res.data.data.access_token, res.data.data.user);

        // 处理邀请关系
        if (hasPendingInvite()) {
          try {
            await checkAndHandleInviteRelation();
          } catch (e) {
            console.error('处理邀请关系失败:', e);
          }
        }

        Taro.showToast({ title: '授权成功，正在确认登录...', icon: 'none' });

        // 延迟确认扫码登录
        setTimeout(() => handleConfirmQRLogin(res.data.data.user), 1500);
      }
    } catch (error: any) {
      Taro.showToast({ title: error.message || '授权失败', icon: 'error' });
    } finally {
      setAuthLoading(false);
    }
  };

  /**
   * 确认扫码登录
   */
  const handleConfirmQRLogin = async (userInfo: any) => {
    if (!token) {
      Taro.showToast({ title: '缺少登录token', icon: 'none' });
      return;
    }

    try {
      const res = await Taro.request({
        url: `${SERVER_API_URL}/qr-login/confirm`,
        method: 'POST',
        data: {
          token,
          userId: userInfo.userId,
          platform: 'wechat',
          wechatInfo: {
            nickname: userInfo.nickname || userInfo.username,
            avatar: userInfo.avatar
          }
        },
        header: { 'content-type': 'application/json', 'TenantId': 5 }
      });

      if (res.data.success || res.data.status === 'confirmed') {
        Taro.showToast({ title: '登录确认成功', icon: 'success', duration: 1500 });
        setTimeout(() => {
          Taro.switchTab({ url: '/pages/user/user' });
        }, 1500);
      } else {
        Taro.showToast({ title: res.data.message || '登录确认失败', icon: 'none' });
      }
    } catch (err: any) {
      Taro.showToast({ title: err.message || '确认登录失败', icon: 'error' });
    }
  };

  /**
   * 取消登录
   */
  const handleCancel = () => {
    const pages = Taro.getCurrentPages();
    if (pages.length > 1) {
      Taro.navigateBack();
    } else {
      Taro.switchTab({ url: '/pages/user/user' });
    }
  };

  // 打开协议页面
  const openAgreement = (type: AgreementType) => {
    const urlMap = {
      service: 'https://websopy.websoft.top/agreement',
      privacy: 'https://websopy.websoft.top/privacy',
    };
    const targetUrl = encodeURIComponent(urlMap[type]);
    Taro.navigateTo({ url: `/passport/webview/index?url=${targetUrl}` });
  };

  // 科技风格授权页面 - 蓝色主题
  return (
    <View className="min-h-screen relative overflow-hidden" style={{ background: 'linear-gradient(135deg, #0a0a1a 0%, #0d1528 50%, #0a1520 100%)' }}>

      {/* 背景科技元素 */}
      {/* 网格背景 */}
      <View style={{
        position: 'absolute', top: 0, left: 0, right: 0, bottom: 0,
        backgroundImage: `linear-gradient(rgba(59, 130, 246, 0.08) 1px, transparent 1px), linear-gradient(90deg, rgba(59, 130, 246, 0.08) 1px, transparent 1px)`,
        backgroundSize: '50px 50px', opacity: 0.5,
      }} />

      {/* 渐变光晕 - 左上 */}
      <View style={{
        position: 'absolute', top: '-30%', left: '-20%', width: '60%', height: '60%',
        background: 'radial-gradient(circle, rgba(59, 130, 246, 0.25) 0%, transparent 70%)',
        filter: 'blur(40px)',
      }} />

      {/* 渐变光晕 - 右下 */}
      <View style={{
        position: 'absolute', bottom: '-20%', right: '-20%', width: '50%', height: '50%',
        background: 'radial-gradient(circle, rgba(99, 102, 241, 0.2) 0%, transparent 70%)',
        filter: 'blur(50px)',
      }} />

      {/* 动态粒子光点 */}
      {[
        { top: '15%', left: '20%', size: 4, delay: '0s' },
        { top: '25%', left: '80%', size: 3, delay: '0.5s' },
        { top: '40%', left: '15%', size: 5, delay: '1s' },
        { top: '35%', left: '85%', size: 3, delay: '1.5s' },
        { top: '55%', left: '10%', size: 4, delay: '2s' },
        { top: '60%', left: '90%', size: 3, delay: '0.3s' },
        { top: '75%', left: '25%', size: 4, delay: '1.2s' },
        { top: '80%', left: '75%', size: 5, delay: '0.8s' },
      ].map((particle, index) => (
        <View key={index} className="particle-blue" style={{
          position: 'absolute', top: particle.top, left: particle.left,
          width: particle.size, height: particle.size, borderRadius: '50%',
          background: index % 2 === 0 ? '#3b82f6' : '#6366f1',
          boxShadow: index % 2 === 0
            ? '0 0 10px rgba(59, 130, 246, 0.8), 0 0 20px rgba(59, 130, 246, 0.4)'
            : '0 0 10px rgba(99, 102, 241, 0.8), 0 0 20px rgba(99, 102, 241, 0.4)',
          animationDelay: particle.delay,
        }} />
      ))}

      {/* 扫描线效果 */}
      <View style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: '2px',
        background: 'linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.6), transparent)',
        animation: 'scanline-blue 3s ease-in-out infinite',
      }} />

      {/* 主内容区域 */}
      <View className="relative z-10 flex flex-col items-center justify-center min-h-screen px-8">

        {/* Logo 区域 */}
        <View className="flex flex-col items-center mb-12">
          <View style={{
            width: '100px', height: '100px', borderRadius: '24px',
            background: 'linear-gradient(135deg, rgba(59, 130, 246, 0.2), rgba(99, 102, 241, 0.2))',
            border: '1px solid rgba(59, 130, 246, 0.3)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: '20px', position: 'relative', overflow: 'hidden',
          }}>
            {/* Logo 内光效 */}
            <View style={{
              position: 'absolute', top: '-50%', left: '-50%', width: '200%', height: '200%',
              background: 'conic-gradient(from 0deg, transparent, rgba(59, 130, 246, 0.15), transparent, rgba(99, 102, 241, 0.15), transparent)',
              animation: 'rotate 4s linear infinite',
            }} />
            <Text style={{ fontSize: '48px', position: 'relative', zIndex: 1 }}>🔐</Text>
          </View>

          <Text style={{
            fontSize: '28px', fontWeight: '700',
            background: 'linear-gradient(90deg, #3b82f6, #6366f1, #8b5cf6)',
            WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
            backgroundClip: 'text', marginBottom: '8px',
          }}>websopy</Text>

          <View style={{
            width: '60px', height: '3px',
            background: 'linear-gradient(90deg, transparent, #3b82f6, transparent)',
            marginTop: '20px', borderRadius: '2px',
          }} />
        </View>

        {/* 主按钮 - 渐变发光按钮 */}
        <View style={{
          width: '100%', maxWidth: '320px',
          background: 'linear-gradient(135deg, #1d4ed8 0%, #3b82f6 50%, #6366f1 100%)',
          borderRadius: '30px', padding: '2px',
          boxShadow: '0 0 30px rgba(59, 130, 246, 0.4), 0 0 60px rgba(59, 130, 246, 0.2)',
        }}>
          <Button
            open-type="getPhoneNumber"
            onGetPhoneNumber={handleGetPhoneNumber}
            disabled={authLoading}
            style={{
              width: '100%', height: '52px', fontSize: '17px', fontWeight: '600',
              color: '#fff', background: 'transparent', borderRadius: '28px',
              border: 'none', padding: '0', boxSizing: 'border-box', lineHeight: '52px',
            }}
          >
            {authLoading ? '授权中...' : '微信手机号登录'}
          </Button>
        </View>

        {/* 取消按钮 */}
        <View style={{ width: '100%', maxWidth: '320px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: '16px' }} onClick={handleCancel}>
          <Text style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '14px' }}>取消</Text>
        </View>

        {/* 协议勾选 */}
        <View className="flex items-center justify-center mt-6">
          <View style={{ padding: '8px', marginRight: '4px' }} onClick={() => setAgreementChecked(!agreementChecked)}>
            <View style={{
              width: '18px', height: '18px', borderRadius: '4px',
              border: agreementChecked ? 'none' : '1px solid rgba(255, 255, 255, 0.3)',
              background: agreementChecked ? 'linear-gradient(135deg, #1d4ed8, #3b82f6)' : 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {agreementChecked && <Text style={{ color: '#fff', fontSize: '12px' }}>✓</Text>}
            </View>
          </View>
          <Text style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '12px' }}>我已阅读并同意</Text>
          <Text style={{ color: '#3b82f6', fontSize: '12px', padding: '4px 2px' }} onClick={() => openAgreement('service')}>《服务协议》</Text>
          <Text style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '12px' }}>和</Text>
          <Text style={{ color: '#3b82f6', fontSize: '12px', padding: '4px 2px' }} onClick={() => openAgreement('privacy')}>《隐私政策》</Text>
        </View>

        {/* 底部装饰 */}
        <View style={{ position: 'absolute', bottom: '40px', display: 'flex', alignItems: 'center', gap: '8px' }}>
          <View style={{ width: '6px', height: '6px', borderRadius: '50%', background: '#3b82f6', boxShadow: '0 0 10px rgba(59, 130, 246, 0.8)' }} />
          <Text style={{ color: 'rgba(255, 255, 255, 0.3)', fontSize: '11px' }}>安全加密连接</Text>
          <View style={{ width: '6px', height: '6px', borderRadius: '50%', background: '#6366f1', boxShadow: '0 0 10px rgba(99, 102, 241, 0.8)' }} />
        </View>
      </View>
    </View>
  );
};

export default QRConfirmPage;
