import React, { useState, useEffect, useCallback } from 'react'
import { View, Text, ScrollView, Input, Button, Image } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useScrollHeight } from '@/hooks/useScrollHeight'
import { getMyRegisterList, addSubordinate, updateSubordinate, MemberRegister } from '@/api/shop/shopMemberRegister'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '录入下级',
})

const InviteSubordinatePage: React.FC = () => {
  const router = useRouter()
  const { user, isLoggedIn } = useUser()
  const scrollHeight = useScrollHeight()
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [list, setList] = useState<MemberRegister[]>([])
  const [showAddModal, setShowAddModal] = useState(false)
  const [editingItem, setEditingItem] = useState<MemberRegister | null>(null)

  // 表单数据
  const [phone, setPhone] = useState('')
  const [realName, setRealName] = useState('')

  // 从首页跳转过来自动弹出添加弹窗
  useEffect(() => {
    const { from } = router.params
    if (from === 'home') {
      setShowAddModal(true)
    }
  }, [router.params])

  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    fetchList()
  }, [isLoggedIn])

  const fetchList = async () => {
    try {
      setLoading(true)
      const data = await getMyRegisterList({ page: 1, limit: 100 })
      setList(data || [])
    } catch (e: any) {
      console.error('获取列表失败:', e)
      Taro.showToast({ title: e.message || '获取列表失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 手机号验证
  const validatePhone = (p: string) => {
    return /^1[3-9]\d{9}$/.test(p)
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!validatePhone(phone)) {
      Taro.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }

    setSubmitting(true)
    try {
      if (editingItem) {
        // 修改
        const res = await updateSubordinate({
          id: editingItem.id,
          phone: phone.trim(),
          realName: realName.trim(),
        })
        if (res.code === 0) {
          Taro.showToast({ title: '修改成功', icon: 'success' })
          setShowAddModal(false)
          resetForm()
          fetchList()
        } else {
          Taro.showToast({ title: res.message || '修改失败', icon: 'none' })
        }
      } else {
        // 新增
        const res = await addSubordinate({
          phone: phone.trim(),
          realName: realName.trim(),
        })
        if (res.code === 0) {
          Taro.showToast({ title: '录入成功', icon: 'success' })
          setShowAddModal(false)
          resetForm()
          fetchList()
        } else {
          Taro.showToast({ title: res.message || '录入失败', icon: 'none' })
        }
      }
    } catch (e: any) {
      Taro.showToast({ title: e.message || '操作失败', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

  // 重置表单
  const resetForm = () => {
    setPhone('')
    setRealName('')
    setEditingItem(null)
  }

  // 打开添加弹窗
  const openAddModal = () => {
    resetForm()
    setShowAddModal(true)
  }

  // 打开编辑弹窗
  const openEditModal = (item: MemberRegister) => {
    setEditingItem(item)
    setPhone(item.phone)
    setRealName(item.realName || '')
    setShowAddModal(true)
  }

  // 跳转到支付页面
  const goToPay = (item: MemberRegister) => {
    Taro.navigateTo({
      url: `/pages/user/register-pay/index?phone=${item.phone}&registerId=${item.id}`,
    })
  }

  // 获取状态文本
  const getStatusText = (item: MemberRegister) => {
    if (item.status === 1) return { text: '已完成', color: 'text-green-500', bg: 'bg-green-50' }
    if (item.status === 2) return { text: '已取消', color: 'text-gray-400', bg: 'bg-gray-100' }
    if (item.registerFeeStatus === 1) return { text: '待审核', color: 'text-orange-500', bg: 'bg-orange-50' }
    return { text: '待支付注册费', color: 'text-blue-500', bg: 'bg-blue-50' }
  }

  // 统计
  const stats = {
    total: list.length,
    pending: list.filter(l => l.status === 0).length,
    completed: list.filter(l => l.status === 1).length,
  }

  if (!isLoggedIn) return null

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {/* 顶部说明 */}
        <View className='mx-3 mt-3 p-4 rounded-xl' style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
          <Text className='text-white text-sm font-medium block'>录入下级会员</Text>
          <Text className='text-white text-xs opacity-80 mt-1 block leading-relaxed'>
            请输入下级会员的手机号，下级需支付198元注册费后成为正式会员
          </Text>
        </View>

        {/* 统计卡片 */}
        <View className='mx-3 mt-3 bg-white rounded-xl p-4'>
          <View className='flex justify-around'>
            <View className='text-center'>
              <Text className='text-2xl font-bold text-gray-800'>{stats.total}</Text>
              <Text className='text-xs text-gray-400 mt-1 block'>已录入</Text>
            </View>
            <View className='text-center'>
              <Text className='text-2xl font-bold text-blue-500'>{stats.pending}</Text>
              <Text className='text-xs text-gray-400 mt-1 block'>待支付</Text>
            </View>
            <View className='text-center'>
              <Text className='text-2xl font-bold text-green-500'>{stats.completed}</Text>
              <Text className='text-xs text-gray-400 mt-1 block'>已完成</Text>
            </View>
          </View>
        </View>

        {/* 录入按钮 */}
        <View className='mx-3 mt-3'>
          <Button
            className='bg-blue-500 text-white rounded-full py-3'
            style={{ backgroundColor: '#667eea' }}
            onClick={openAddModal}
          >
            <Text className='text-white font-medium'>+ 录入下级</Text>
          </Button>
        </View>

        {/* 列表 */}
        <View className='mx-3 mt-3 mb-4'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>下级列表</Text>

          {loading ? (
            <View className='bg-white rounded-xl p-6 text-center'>
              <Text className='text-gray-400'>加载中...</Text>
            </View>
          ) : list.length === 0 ? (
            <EmptyState text='暂无下级记录' subText='点击上方按钮录入下级会员' />
          ) : (
            <View className='space-y-3'>
              {list.map((item) => {
                const status = getStatusText(item)
                return (
                  <View key={item.id} className='bg-white rounded-xl p-4'>
                    <View className='flex items-center justify-between'>
                      <View className='flex items-center gap-3'>
                        <View className='w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center'>
                          <Text className='text-lg'>👤</Text>
                        </View>
                        <View>
                          <Text className='text-gray-800 font-medium'>
                            {item.realName || '未填写姓名'}
                          </Text>
                          <Text className='text-gray-500 text-sm mt-0.5'>
                            {item.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}
                          </Text>
                        </View>
                      </View>
                      <View className={`px-2 py-1 rounded-full ${status.bg}`}>
                        <Text className={`text-xs ${status.color}`}>{status.text}</Text>
                      </View>
                    </View>

                    {/* 费用信息 */}
                    <View className='mt-3 pt-3 border-t border-gray-100 flex justify-between text-xs'>
                      <View>
                        <Text className='text-gray-400'>会员费(线下)</Text>
                        <Text className='text-gray-600 mt-0.5'>¥298.00</Text>
                      </View>
                      <View className='text-right'>
                        <Text className='text-gray-400'>注册费(平台)</Text>
                        <Text className='text-gray-600 mt-0.5'>¥198.00</Text>
                      </View>
                    </View>

                    {/* 操作按钮 */}
                    <View className='mt-3 flex gap-2'>
                      <Button
                        size='mini'
                        className='flex-1 rounded-full'
                        style={{ borderColor: '#ddd', borderWidth: 1 }}
                        onClick={() => openEditModal(item)}
                        disabled={item.status === 1}
                      >
                        <Text className='text-gray-600 text-xs'>修改</Text>
                      </Button>
                      {item.registerFeeStatus === 0 && (
                        <Button
                          size='mini'
                          className='flex-1 rounded-full bg-blue-500 text-white'
                          style={{ backgroundColor: '#667eea' }}
                          onClick={() => goToPay(item)}
                        >
                          <Text className='text-white text-xs'>查看支付</Text>
                        </Button>
                      )}
                    </View>

                    <Text className='text-gray-300 text-xs mt-2 block'>
                      录入时间: {item.createTime}
                    </Text>
                  </View>
                )
              })}
            </View>
          )}
        </View>
      </ScrollView>

      {/* 添加/编辑弹窗 */}
      {showAddModal && (
        <View className='fixed inset-0 z-50'>
          {/* 遮罩 */}
          <View
            className='absolute inset-0 bg-black bg-opacity-50'
            onClick={() => { setShowAddModal(false); resetForm() }}
          />
          {/* 内容 */}
          <View className='absolute bottom-0 left-0 right-0 bg-white rounded-t-2xl p-5'>
            <View className='flex justify-between items-center mb-4'>
              <Text className='text-lg font-medium text-gray-800'>
                {editingItem ? '修改下级信息' : '录入下级'}
              </Text>
              <Text
                className='text-gray-400 text-xl'
                onClick={() => { setShowAddModal(false); resetForm() }}
              >
                ×
              </Text>
            </View>

            <View className='mb-4'>
              <Text className='text-sm text-gray-600 mb-2 block'>下级手机号 *</Text>
              <Input
                className='border border-gray-200 rounded-lg px-4 py-3 text-base'
                type='number'
                maxlength={11}
                placeholder='请输入下级手机号'
                value={phone}
                onInput={(e) => setPhone(e.detail.value)}
              />
            </View>

            <View className='mb-4'>
              <Text className='text-sm text-gray-600 mb-2 block'>下级姓名(选填)</Text>
              <Input
                className='border border-gray-200 rounded-lg px-4 py-3 text-base'
                placeholder='请输入下级姓名'
                value={realName}
                onInput={(e) => setRealName(e.detail.value)}
              />
            </View>

            <View className='bg-blue-50 rounded-lg p-3 mb-4'>
              <Text className='text-xs text-blue-600 leading-relaxed block'>
                温馨提示：下级需支付198元注册费后方可成为正式会员，请确保手机号填写正确。
              </Text>
            </View>

            <Button
              className='rounded-full py-3'
              style={{ backgroundColor: '#667eea' }}
              loading={submitting}
              onClick={handleSubmit}
            >
              <Text className='text-white font-medium'>
                {editingItem ? '保存修改' : '确认录入'}
              </Text>
            </Button>
          </View>
        </View>
      )}
    </View>
  )
}

export default InviteSubordinatePage
