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'>鑫龙家电 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'>
          鑫龙商贸电器是一家专注于家用电器销售、安装及维修服务的本地经营部。
          我们提供冰箱、洗衣机、空调、电视、厨房电器、生活小家电等多种品类，涵盖售前咨询、
          售后安装、维护保养及故障维修等一站式家电服务。
        </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: '电视、冰箱、洗衣机等全品类家电销售' },
          { icon: '❄️', title: '空调服务', desc: '空调销售、安装、加氟、清洗及维修' },
          { icon: '🍳', title: '厨房电器', desc: '油烟机、燃气灶、热水器等厨卫电器' },
          { icon: '🛠️', title: '安装维修', desc: '专业师傅上门安装、检测及故障维修' },
          { 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'>
              <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: '大新里南718号' },
            { label: '联系电话', value: '18269229683' },
            { label: '营业时间', value: '9:00 ~ 18:00' },
          ].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'>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.5)' }}
          onClick={handleCloseLogin}
          catchMove
        >
          <View
            className='rounded-2xl bg-white'
            style={{ width: '340px', padding: '24px 20px' }}
            onClick={(e) => e.stopPropagation()}
          >
            <View className='mb-3 flex items-center justify-between'>
              <Text className='text-lg font-bold text-gray-800'>开发者登录</Text>
              <Text
                className='text-lg text-gray-400'
                style={{ padding: '4px 8px' }}
                onClick={handleCloseLogin}
              >
                ✕
              </Text>
            </View>
            <Text className='mb-5 block text-xs text-gray-400'>
              仅限开发测试使用，通过手机号+验证码登录指定账号
            </Text>

            <View className='mb-3'>
              <Input
                type='number'
                placeholder='请输入手机号码'
                maxLength={11}
                value={formData.phone || ''}
                onChange={(val) => setFormData({ ...formData, phone: val })}
                style={{ backgroundColor: '#f5f5f5', borderRadius: '8px' }}
              />
            </View>

            <View className='mb-6 flex items-center bg-white rounded-lg pr-2'>
              <Input
                type='number'
                placeholder='请输入6位验证码'
                maxLength={6}
                value={formData.code || ''}
                onChange={(val) => setFormData({ ...formData, code: val })}
                style={{ backgroundColor: '#f5f5f5', borderRadius: '8px' }}
              />
              <Button
                size='small'
                type={countdown > 0 ? 'default' : 'primary'}
                loading={sendingCode}
                disabled={sendingCode || countdown > 0}
                onClick={handleSendCode}
              >
                {countdown > 0 ? `${countdown}s` : sendingCode ? '发送中' : '获取验证码'}
              </Button>
            </View>

            <View className='flex justify-center'>
              <Button
                type='primary'
                size='large'
                className='w-full rounded-lg p-2'
                loading={loading}
                disabled={loading}
                onClick={handleLogin}
              >
                {loading ? '登录中...' : '登录'}
              </Button>
            </View>
          </View>
        </View>
      )}
    </ScrollView>
  )
}

export default AboutPage
