import React, { useState, useRef, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import { Input, Button } from '@nutui/nutui-react-taro'
import { loginBySms, sendSmsCaptcha } from '@/api/passport/login'
import type { LoginParam } from '@/api/passport/login/model'
import { useUserContext } from '@/contexts/UserContext'

definePageConfig({
  navigationBarTitleText: '关于我们',
})

/** 触发隐藏登录的点击次数 */
const DEV_LOGIN_CLICK_COUNT = 11

const AboutPage: React.FC = () => {
  const { syncFromStorage } = useUserContext()

  // ---- 隐藏开发者登录相关状态 ----
  const clickCountRef = useRef(0)
  const lastClickTime = useRef(0)
  const [showLogin, setShowLogin] = useState(false)

  const [loading, setLoading] = useState(false)
  const [sendingCode, setSendingCode] = useState(false)
  const [countdown, setCountdown] = useState(0)
  const [formData, setFormData] = useState<LoginParam>({ phone: '', code: '' })

  // 倒计时
  useEffect(() => {
    if (countdown <= 0) return
    const timer = setTimeout(() => setCountdown(countdown - 1), 1000)
    return () => clearTimeout(timer)
  }, [countdown])

    /** 点击版权信息 —— 累计 11 次弹出隐藏登录 */
  const handleCopyrightClick = () => {
    const now = Date.now()
    // 超过 3 秒未点击则重新计数
    if (now - lastClickTime.current > 3000) {
      clickCountRef.current = 1
    } else {
      clickCountRef.current += 1
    }
    lastClickTime.current = now

    const current = clickCountRef.current
    const remaining = DEV_LOGIN_CLICK_COUNT - current

    if (current >= DEV_LOGIN_CLICK_COUNT) {
      clickCountRef.current = 0
      setShowLogin(true)
      return
    }

    // 从第 6 次开始给步数提示
    if (current >= 6) {
      Taro.showToast({
        title: `再点击 ${remaining} 次开启开发者登录`,
        icon: 'none',
        duration: 1200,
      })
    }
  }

  /** 校验手机号 */
  const validatePhone = (phone: string): boolean => /^1[3-9]\d{9}$/.test(phone)

  /** 发送短信验证码 */
  const handleSendCode = async () => {
    if (!formData.phone) {
      Taro.showToast({ title: '请输入手机号码', icon: 'none' })
      return
    }
    if (!validatePhone(formData.phone)) {
      Taro.showToast({ title: '请输入正确的手机号码', icon: 'none' })
      return
    }
    if (sendingCode || countdown > 0) return

    try {
      setSendingCode(true)
      await sendSmsCaptcha({ phone: formData.phone })
      Taro.showToast({ title: '验证码已发送', icon: 'success' })
      setCountdown(60)
    } catch (error: any) {
      Taro.showToast({ title: error.message || '发送失败', icon: 'none' })
    } finally {
      setSendingCode(false)
    }
  }

  /** 登录提交 */
  const handleLogin = async () => {
    if (loading) return
    if (!formData.phone || !validatePhone(formData.phone)) {
      Taro.showToast({ title: '请输入正确的手机号码', icon: 'none' })
      return
    }
    if (!formData.code || formData.code.length !== 6) {
      Taro.showToast({ title: '请输入6位验证码', icon: 'none' })
      return
    }

    try {
      setLoading(true)
      await loginBySms({ phone: formData.phone, code: formData.code })
      // loginBySms 内部已写入 storage，这里同步 React 登录态
      syncFromStorage()
      Taro.showToast({ title: '登录成功', icon: 'success' })
      // 重置表单并关闭弹窗
      setFormData({ phone: '', code: '' })
      setCountdown(0)
      setTimeout(() => setShowLogin(false), 800)
    } catch (error: any) {
      Taro.showToast({ title: error.message || '登录失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  /** 关闭弹窗时重置状态 */
  const handleCloseLogin = () => {
    if (loading) return
    setShowLogin(false)
    setFormData({ phone: '', code: '' })
    setCountdown(0)
  }

  return (
    <ScrollView scrollY className='min-h-screen bg-gray-50'>
      {/* 头部品牌区 */}
      <View className='bg-white py-10 flex flex-col items-center'>
        <View className='w-20 h-20 rounded-2xl bg-gradient-to-br from-blue-400 to-blue-600 flex items-center justify-center shadow-lg mb-4'>
          <Text className='text-white text-4xl font-bold'>威</Text>
        </View>
        <Text className='text-xl font-bold text-gray-800'>威数谱软件</Text>
        <Text className='text-sm text-gray-400 mt-1'>websopy v1.0.0</Text>
      </View>

      {/* 公司简介 / 品牌故事 */}
      <View className='bg-white mx-3 mt-3 rounded-xl p-4' style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }}>
        <Text className='text-base font-medium text-gray-800 mb-3 block'>品牌故事</Text>
        <Text className='text-sm text-gray-600 leading-relaxed'>
          威数谱软件（websopy）是南宁市网宿信息科技有限公司旗下的数字化服务品牌，
          致力于为中小企业提供一站式软件产品与信息化解决方案。我们以"让每一家企业
          都能轻松用上专业的软件"为使命，依托云计算、移动互联网与大数据技术，
          打造覆盖企业管理、营销获客到客户服务的全链路软件矩阵。
        </Text>
        <Text className='text-sm text-gray-600 leading-relaxed mt-2'>
          自创立以来，威数谱始终秉持"专业、务实、共赢"的价值观，已为零售、家电、
          本地生活等多个行业的数百家客户提供服务。我们相信，技术的价值在于落地——
          用更简单的产品、更透明的服务，帮助客户把生意做得更好。
        </Text>
        <Text className='text-sm text-gray-600 leading-relaxed mt-2'>
          未来，威数谱将继续以产品力为核心，与合作伙伴携手同行，让数字化能力成为
          中小企业稳健增长的底座。
        </Text>
      </View>

      {/* 核心业务 */}
      <View className='bg-white mx-3 mt-3 rounded-xl p-4' style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }}>
        <Text className='text-base font-medium text-gray-800 mb-3 block'>核心业务</Text>
        {[
          { icon: '🖥️', title: '企业管理软件', desc: 'ERP / CRM / OA 等数字化管理工具' },
          { icon: '🌐', title: '品牌官网建设', desc: '企业官网、品牌站、营销落地页定制' },
          { icon: '📱', title: '移动应用开发', desc: '微信小程序、跨端 APP 定制开发' },
          { icon: '🔗', title: '系统集成对接', desc: '第三方平台 API 对接与数据打通' },
          { icon: '📊', title: '数据智能分析', desc: '经营数据可视化与业务洞察' },
          { icon: '✅', title: '技术服务支持', desc: '部署运维、培训陪跑、售后无忧' },
        ].map((item, idx) => (
          <View
            key={idx}
            className={`flex items-start gap-3 py-3 ${idx < 5 ? 'border-b border-gray-50' : ''}`}
          >
            <Text className='text-2xl mt-0.5'>{item.icon}</Text>
            <View className='flex-1 flex flex-col'>
              <Text className='text-sm font-medium text-gray-700'>{item.title}</Text>
              <Text className='text-xs text-gray-400 mt-0.5'>{item.desc}</Text>
            </View>
          </View>
        ))}
      </View>

      {/* 联系我们 */}
      <View className='bg-white mx-3 mt-3 rounded-xl p-4' style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }}>
        <Text className='text-base font-medium text-gray-800 mb-3 block'>联系我们</Text>
        <View className='flex flex-col gap-2'>
          {[
            { label: '公司名称', value: '南宁市网宿信息科技有限公司' },
            { label: '品牌名称', value: '威数谱软件（websopy）' },
            { label: '公司总部', value: '南宁市良庆区五象大道401号五象航洋城（总部基地）1号楼1226室' },
            { label: '联系电话', value: '0771-5386339' },
            { label: '电子邮箱', value: 'websopy@163.com' },
            { label: '官方网站', value: 'websoft.top / websopy.com' },
          ].map((item, idx) => (
            <View key={idx} className='flex items-start justify-between'>
              <Text className='text-sm text-gray-500 flex-shrink-0'>{item.label}</Text>
              <Text className='text-sm text-gray-700 text-right ml-2'>{item.value}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* 底部版权 */}
      <View className='flex flex-col items-center py-8' onClick={handleCopyrightClick}>
        <Text className='text-xs text-gray-400'>Copyright © 2024 南宁市网宿信息科技有限公司</Text>
        <Text className='text-xs text-gray-400 mt-1'>威数谱软件 websopy · All Rights Reserved</Text>
      </View>

      {/* 隐藏的开发者登录弹窗 */}
      {showLogin && (
        <View
          className='fixed inset-0 z-[9999] flex items-center justify-center'
          style={{ backgroundColor: 'rgba(0,0,0,0.55)' }}
          onClick={handleCloseLogin}
          catchMove
        >
          <View
            className='rounded-3xl bg-white'
            style={{ width: '320px', padding: '32px 24px' }}
            onClick={(e) => e.stopPropagation()}
          >
            {/* 标题栏 */}
            <View className='mb-2 flex items-center justify-between'>
              <Text className='text-xl font-bold text-gray-800'>开发者登录</Text>
              <Text
                className='text-xl text-gray-300 leading-none cursor-pointer active:opacity-60'
                style={{ padding: '6px', lineHeight: 1 }}
                onClick={handleCloseLogin}
              >
                ✕
              </Text>
            </View>
            <Text className='mb-6 block text-xs text-gray-400 leading-relaxed'>
              仅限开发测试使用，通过手机号+验证码登录指定账号
            </Text>

            {/* 手机号输入框 */}
            <View className='mb-4'>
              <Input
                type='number'
                placeholder='请输入手机号码'
                maxLength={11}
                value={formData.phone || ''}
                onChange={(val) => setFormData({ ...formData, phone: val })}
                style={{
                  backgroundColor: '#fff5f5',
                  borderRadius: '12px',
                  height: '48px',
                  paddingLeft: '16px',
                  paddingRight: '16px',
                  fontSize: '15px',
                  border: '1.5px solid #e53e3e',
                  boxSizing: 'border-box',
                }}
              />
            </View>

            {/* 验证码输入 + 获取按钮 */}
            <View className='mb-8 flex items-center gap-3'>
              <View className='flex-1'>
                <Input
                  type='number'
                  placeholder='请输入6位验证码'
                  maxLength={6}
                  value={formData.code || ''}
                  onChange={(val) => setFormData({ ...formData, code: val })}
                  style={{
                    backgroundColor: '#fff5f5',
                    borderRadius: '12px',
                    height: '48px',
                    paddingLeft: '16px',
                    paddingRight: '12px',
                    fontSize: '15px',
                    border: '1.5px solid #e53e3e',
                    boxSizing: 'border-box',
                  }}
                />
              </View>
              <Button
                size='small'
                type={countdown > 0 ? 'default' : 'primary'}
                loading={sendingCode}
                disabled={sendingCode || countdown > 0}
                onClick={handleSendCode}
                style={{
                  height: '48px',
                  minWidth: '110px',
                  borderRadius: '12px',
                  fontSize: '13px',
                  fontWeight: 500,
                  flexShrink: 0,
                  ...(countdown > 0 ? {
                    backgroundColor: '#f0f0f0',
                    color: '#999',
                  } : {
                    backgroundColor: '#e53e3e',
                    borderColor: '#e53e3e',
                  }),
                }}
              >
                {countdown > 0 ? `${countdown}s 后重发` : sendingCode ? '发送中' : '获取验证码'}
              </Button>
            </View>

            {/* 登录按钮 */}
            <View className='flex justify-center'>
              <Button
                block
                type='primary'
                size='large'
                loading={loading}
                disabled={loading}
                onClick={handleLogin}
                style={{
                  height: '50px',
                  borderRadius: '14px',
                  fontSize: '17px',
                  fontWeight: 600,
                  letterSpacing: '2px',
                  background: loading
                    ? '#c0c0c0'
                    : 'linear-gradient(135deg, #fc5c5c 0%, #e53e3e 100%)',
                  border: 'none',
                  boxShadow: loading
                    ? 'none'
                    : '0 6px 20px rgba(229, 62, 62, 0.35)',
                }}
              >
                {loading ? '登录中...' : '登 录'}
              </Button>
            </View>
          </View>
        </View>
      )}
    </ScrollView>
  )
}

export default AboutPage
