import React, { useState, useEffect } from 'react';
import { View, Text, Button, Image } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { loginByOpenId } from '@/api/passport/wx-login';
import { saveStorageByLoginUser, SERVER_API_URL } from '@/utils/server';
import { TenantId } from '@/config/app';

// 邀请相关接口使用独立的 API 域名
const INVITE_API_URL = 'https://websopy-api.websoft.top';

/**
 * 邀请加入确认页面
 *
 * 流程：
 * 1. 扫码进入 → 调用 loginByOpenId 判断登录状态
 * 2. 已注册   → isLoggedIn=true  → 显示「确认加入」按钮 → 点击直接加入（带 access_token）
 * 3. 未注册   → isLoggedIn=false → 显示「微信手机号授权」按钮
 *            → 授权成功 → 注册/登录 → isLoggedIn=true → 自动执行加入
 */

interface InviteInfo {
  appId: string;
  appName: string;
  appLogo: string;
  inviterName: string;
  roleName: string;
}

type AgreementType = 'service' | 'privacy';
type PageStatus = 'loading' | 'checking' | 'invite' | 'error';

const InvitePage: React.FC = () => {
  const router = useRouter();

  const [pageStatus, setPageStatus] = useState<PageStatus>('loading');
  const [inviteInfo, setInviteInfo] = useState<InviteInfo | null>(null);
  const [authLoading, setAuthLoading] = useState(false);
  const [agreementChecked, setAgreementChecked] = useState(false);
  const [token, setToken] = useState<string>('');
  const [error, setError] = useState<string>('');
  /**
   * true  = 已注册已登录，按钮文字「确认加入」（仍走 getPhoneNumber 获取 code 传给后端）
   * false = 未注册，按钮文字「微信手机号快速加入」，授权后先注册登录再加入
   */
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);

  useEffect(() => {
    initPage();
  }, [router.params]);

  // ── 初始化 ──────────────────────────────────────────
  const initPage = async () => {
    const params = router.params;
    let inviteToken = params.scene || params.token || params.qrCodeKey || '';

    if (params.q && !inviteToken) {
      try {
        const decodedUrl = decodeURIComponent(params.q);
        const url = new URL(decodedUrl);
        inviteToken = url.searchParams.get('token') || url.searchParams.get('qrCodeKey') || '';
      } catch {
        inviteToken = decodeURIComponent(params.q);
      }
    }

    if (!inviteToken) {
      setError('无效的邀请链接');
      setPageStatus('error');
      return;
    }

    setToken(inviteToken);
    Taro.setStorageSync('invite_token', inviteToken);

    // 先获取邀请信息，再检查登录状态（并行更好，但 inviteInfo 失败要 error）
    await checkLoginStatus(inviteToken);
  };

  // ── loginByOpenId 检查登录状态 ──────────────────────
  const checkLoginStatus = async (inviteToken: string) => {
    setPageStatus('checking');
    try {
      const wxRes = await Taro.login();
      if (!wxRes.code) throw new Error('获取微信登录凭证失败');

      const loginRes = await loginByOpenId({
        code: wxRes.code,
        tenantId: parseInt(TenantId) || 1,
      });

      console.log('loginByOpenId 结果:', loginRes);

      if (loginRes.success && loginRes.data?.access_token) {
        // ✅ 已注册：保存登录信息，显示「确认加入」
        saveStorageByLoginUser(loginRes.data.access_token, loginRes.data.user as any);
        setIsLoggedIn(true);
      } else {
        // ❌ 未注册：显示手机号授权按钮
        console.log('用户未注册，显示手机号授权按钮');
        setIsLoggedIn(false);
      }

      // 两种情况都需要获取邀请信息
      await fetchInviteInfo(inviteToken);
      setPageStatus('invite');
    } catch (err: any) {
      console.error('检查登录状态失败:', err);
      setError(err.message || '初始化失败，请重试');
      setPageStatus('error');
    }
  };

  // ── 获取邀请信息 ─────────────────────────────────────
  const fetchInviteInfo = async (inviteToken: string) => {
    const res = await Taro.request({
      url: `${INVITE_API_URL}/api/_app/developer/invite/info?token=${encodeURIComponent(inviteToken)}`,
      method: 'GET',
      header: { 'content-type': 'application/json', TenantId },
    });

    console.log('邀请信息接口响应:', res);

    if (res.data.code === 200 || res.data.code === 0) {
      setInviteInfo(res.data.data);
    } else {
      throw new Error(res.data.message || '邀请信息获取失败');
    }
  };

  /**
   * 已登录用户：点击「确认加入」
   * 后端已改造支持已登录用户直接加入（不传 code，从 Authorization 头识别用户）
   */
  const handleConfirmJoin = async () => {
    const accessToken = Taro.getStorageSync('access_token');
    if (!accessToken) {
      Taro.showToast({ title: '登录状态异常，请刷新重试', icon: 'none' });
      return;
    }

    try {
      setAuthLoading(true);
      // 已登录用户不传 code，后端从 Authorization 头识别用户
      await doJoinAppForLoggedInUser(accessToken);
    } catch (err: any) {
      console.error('确认加入失败:', err);
      Taro.showToast({ title: err.message || '加入失败，请重试', icon: 'none' });
    } finally {
      setAuthLoading(false);
    }
  };

  /**
   * 未注册用户：手机号授权回调
   * 先用 code 注册/登录，再用新的 wx.login code 调加入接口
   */
  const handleGetPhoneNumber = async (e: any) => {
    const { code, encryptedData, iv, errMsg } = e.detail;

    if (!agreementChecked) {
      Taro.showToast({ title: '请先同意服务协议和隐私政策', icon: 'none' });
      return;
    }
    if (errMsg?.includes('fail')) {
      Taro.showToast({ title: '需要授权手机号才能加入', icon: 'none' });
      return;
    }
    if (!code) {
      Taro.showToast({ title: '获取授权信息失败，请重试', icon: 'none' });
      return;
    }

    try {
      setAuthLoading(true);

      // 1. 用手机号授权码完成注册/登录
      console.log('未注册用户，先注册/登录再加入');
      const loginRes = await Taro.request({
        url: `${SERVER_API_URL}/wx-login/loginByMpWxPhone`,
        method: 'POST',
        data: {
          code,
          encryptedData,
          iv,
          tenantId: parseInt(TenantId) || 1,
          notVerifyPhone: true,
        },
        header: { 'content-type': 'application/json', TenantId },
      });

      console.log('手机号注册/登录结果:', loginRes);

      if (loginRes.data.code !== 0 && loginRes.data.code !== 200) {
        throw new Error(loginRes.data.message || '注册/登录失败');
      }

      const { access_token, user } = loginRes.data.data || {};
      if (!access_token) throw new Error('登录失败，未获取到 token');

      // 2. 保存登录信息
      saveStorageByLoginUser(access_token, user);
      setIsLoggedIn(true);

      // 3. 手机号授权码已被消耗，重新获取 wx.login code 调加入接口
      console.log('注册成功，重新获取 wx.login code 调加入接口');
      const wxRes = await Taro.login();
      if (!wxRes.code) throw new Error('获取微信登录凭证失败');

      await doJoinAppForNewUser(wxRes.code, access_token);
    } catch (err: any) {
      console.error('手机号授权登录失败:', err);
      Taro.showToast({ title: err.message || '授权失败，请重试', icon: 'none' });
    } finally {
      setAuthLoading(false);
    }
  };

  /**
   * 已登录用户调用加入接口（不传 code，后端从 Authorization 头识别用户）
   */
  const doJoinAppForLoggedInUser = async (accessToken: string) => {
    const inviteToken = Taro.getStorageSync('invite_token') || token;
    console.log('doJoinAppForLoggedInUser, inviteToken:', inviteToken, 'accessToken:', accessToken ? '有' : '无');

    const res = await Taro.request({
      url: `${INVITE_API_URL}/api/_app/developer/invite/accept`,
      method: 'POST',
      data: {
        token: inviteToken,
        // 已登录用户不传 code，后端从 Authorization 头识别用户
      },
      header: {
        'content-type': 'application/json',
        TenantId,
        Authorization: `Bearer ${accessToken}`,
      },
    });

    console.log('加入应用接口响应:', res);

    if (res.data.code === 200 || res.data.code === 0) {
      Taro.removeStorageSync('invite_token');
      Taro.showToast({ title: '加入成功', icon: 'success', duration: 1500 });
      setTimeout(() => Taro.switchTab({ url: '/pages/index/index' }), 1500);
    } else {
      throw new Error(res.data.message || '加入失败');
    }
  };

  /**
   * 未注册用户调用加入接口（传 code，后端用 code 获取手机号创建用户）
   */
  const doJoinAppForNewUser = async (wxCode: string, accessToken: string) => {
    const inviteToken = Taro.getStorageSync('invite_token') || token;
    console.log('doJoinAppForNewUser, inviteToken:', inviteToken, 'wxCode:', wxCode ? '有' : '无', 'accessToken:', accessToken ? '有' : '无');

    const res = await Taro.request({
      url: `${INVITE_API_URL}/api/_app/developer/invite/accept`,
      method: 'POST',
      data: {
        token: inviteToken,
        code: wxCode,
      },
      header: {
        'content-type': 'application/json',
        TenantId,
        Authorization: `Bearer ${accessToken}`,
      },
    });

    console.log('加入应用接口响应:', res);

    if (res.data.code === 200 || res.data.code === 0) {
      Taro.removeStorageSync('invite_token');
      Taro.showToast({ title: '加入成功', icon: 'success', duration: 1500 });
      setTimeout(() => Taro.switchTab({ url: '/pages/index/index' }), 1500);
    } else {
      throw new Error(res.data.message || '加入失败');
    }
  };

  // ── 拒绝 / 打开协议 ─────────────────────────────────
  const handleReject = () => Taro.switchTab({ url: '/pages/index/index' });

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

  // ── Loading / Checking 状态 ──────────────────────────
  if (pageStatus === 'loading' || pageStatus === 'checking') {
    return (
      <View className="min-h-screen flex items-center justify-center"
        style={{ background: 'linear-gradient(135deg, #0a0a1a 0%, #0d1528 50%, #0a1520 100%)' }}>
        <View className="flex flex-col items-center">
          <View style={{
            width: '40px', height: '40px',
            border: '3px solid rgba(59, 130, 246, 0.3)',
            borderTopColor: '#3b82f6', borderRadius: '50%',
            animation: 'spin 1s linear infinite',
          }} />
          <Text style={{ color: 'rgba(255, 255, 255, 0.6)', marginTop: '16px', fontSize: '14px' }}>
            {pageStatus === 'checking' ? '检查登录状态...' : '加载中...'}
          </Text>
        </View>
      </View>
    );
  }

  // ── 错误状态 ─────────────────────────────────────────
  if (pageStatus === 'error') {
    return (
      <View className="min-h-screen flex items-center justify-center"
        style={{ background: 'linear-gradient(135deg, #0a0a1a 0%, #0d1528 50%, #0a1520 100%)' }}>
        <View className="flex flex-col items-center px-8">
          <Text style={{ fontSize: '64px', marginBottom: '20px' }}>❌</Text>
          <Text style={{ color: '#ef4444', fontSize: '16px', textAlign: 'center', marginBottom: '24px' }}>{error}</Text>
          <Button onClick={handleReject} style={{
            background: 'rgba(255, 255, 255, 0.1)', color: '#fff',
            borderRadius: '20px', fontSize: '14px', padding: '8px 24px',
          }}>
            返回首页
          </Button>
        </View>
      </View>
    );
  }

  // ── 邀请确认页面 ──────────────────────────────────────
  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: '10%', size: 4, delay: '0s' },
        { top: '20%', left: '85%', size: 3, delay: '0.5s' },
        { top: '70%', left: '8%', size: 4, delay: '1s' },
        { top: '75%', left: '88%', size: 3, delay: '1.5s' },
      ].map((p, i) => (
        <View key={i} style={{
          position: 'absolute', top: p.top, left: p.left,
          width: p.size, height: p.size, borderRadius: '50%',
          background: i % 2 === 0 ? '#3b82f6' : '#6366f1',
          boxShadow: i % 2 === 0
            ? '0 0 10px rgba(59, 130, 246, 0.8)'
            : '0 0 10px rgba(99, 102, 241, 0.8)',
          animationDelay: p.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">

        {/* 邀请卡片 */}
        <View style={{
          width: '100%', maxWidth: '360px',
          background: 'rgba(255, 255, 255, 0.05)',
          borderRadius: '24px', border: '1px solid rgba(255, 255, 255, 0.1)',
          padding: '32px 24px', backdropFilter: 'blur(20px)',
        }}>

          {/* 应用 Logo + 名称 */}
          <View className="flex flex-col items-center mb-8">
            <View style={{
              width: '80px', height: '80px', borderRadius: '20px',
              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: '16px', overflow: 'hidden',
            }}>
              {inviteInfo?.appLogo
                ? <Image src={inviteInfo.appLogo} style={{ width: '60px', height: '60px', borderRadius: '12px' }} />
                : <Text style={{ fontSize: '36px' }}>🚀</Text>
              }
            </View>
            <Text style={{ fontSize: '22px', fontWeight: '700', color: '#fff', marginBottom: '8px' }}>
              {inviteInfo?.appName || 'Websopy'}
            </Text>
            <View style={{
              padding: '4px 12px', borderRadius: '12px',
              background: 'rgba(59, 130, 246, 0.2)', border: '1px solid rgba(59, 130, 246, 0.3)',
            }}>
              <Text style={{ color: '#3b82f6', fontSize: '12px' }}>邀请你加入应用</Text>
            </View>
          </View>

          {/* 邀请人 */}
          <View className="flex items-center justify-center mb-6">
            <Text style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '13px' }}>
              邀请人：{inviteInfo?.inviterName || '某位用户'}
            </Text>
          </View>

          {/* 分隔线 */}
          <View style={{
            height: '1px',
            background: 'linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent)',
            marginBottom: '24px',
          }} />

          {/* 协议勾选 */}
          {!isLoggedIn && (
            <View className="flex items-center justify-center mb-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={{
            width: '100%',
            background: 'linear-gradient(135deg, #1d4ed8 0%, #3b82f6 50%, #6366f1 100%)',
            borderRadius: '24px', padding: '2px',
            boxShadow: '0 0 30px rgba(59, 130, 246, 0.4)',
          }}>
            {isLoggedIn ? (
              /* 已登录：普通按钮，不弹手机号授权，直接调后端 */
              <Button
                onClick={handleConfirmJoin}
                disabled={authLoading}
                style={{
                  width: '100%', height: '48px', fontSize: '16px', fontWeight: '600',
                  color: '#fff', background: 'transparent', borderRadius: '22px',
                  border: 'none', padding: '0', boxSizing: 'border-box', lineHeight: '48px',
                }}
              >
                {authLoading ? '处理中...' : '确认加入'}
              </Button>
            ) : (
              /* 未注册：手机号授权按钮 */
              <Button
                open-type="getPhoneNumber"
                onGetPhoneNumber={handleGetPhoneNumber}
                disabled={authLoading}
                style={{
                  width: '100%', height: '48px', fontSize: '16px', fontWeight: '600',
                  color: '#fff', background: 'transparent', borderRadius: '22px',
                  border: 'none', padding: '0', boxSizing: 'border-box', lineHeight: '48px',
                }}
              >
                {authLoading ? '处理中...' : '微信手机号快速加入'}
              </Button>
            )}
          </View>

          {/* 拒绝 */}
          <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: '16px' }}
            onClick={handleReject}>
            <Text style={{ color: 'rgba(255, 255, 255, 0.4)', fontSize: '14px' }}>暂不加入</Text>
          </View>
        </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 InvitePage;
