import React, { useState, useEffect, useCallback } from 'react'
import { View, Text, ScrollView, Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar'
import CellRow from '@/components/common/CellRow'
import Loading from '@/components/common/Loading'
import { useUser } from '@/hooks/useUser'
import { pageAppDomain, verifyDomain, activeDomain, rejectDomain, disableDomain } from '@/api/app/appDomain'
import { getPageList, DOMAIN_STATUS_NAME, domainStatusColor } from '@/utils/devcenter'

definePageConfig({ navigationBarTitleText: '域名绑定审核' })

const DomainReviewPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [loading, setLoading] = useState(true)
  const [list, setList] = useState<any[]>([])
  const [detail, setDetail] = useState<any>(null)
  const [rejectReason, setRejectReason] = useState('')
  const [busy, setBusy] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await pageAppDomain({ page: 1, limit: 50 })
      setList(getPageList(data))
    } catch (e) {
      // ignore
    } finally {
      setLoading(false)
    }
  }, [])
  useEffect(() => {
    if (isLoggedIn) load()
  }, [isLoggedIn, load])

  const act = async (fn: () => Promise<any>, okMsg: string) => {
    setBusy(true)
    try {
      await fn()
      Taro.showToast({ title: okMsg, icon: 'none' })
      setDetail(null)
      setRejectReason('')
      load()
    } catch (e: any) {
      Taro.showToast({ title: e?.message || '操作失败', icon: 'none' })
    } finally {
      setBusy(false)
    }
  }

  return (
    <View className='min-h-screen bg-gray-100'>
      <NavBar title='域名绑定审核' />
      <ScrollView scrollY>
        {loading ? (
          <Loading />
        ) : list.length === 0 ? (
          <View className='flex flex-col items-center justify-center py-24'>
            <Text className='text-gray-400 text-sm'>暂无域名申请</Text>
          </View>
        ) : (
          <View className='mt-3'>
            {list.map((d) => (
              <CellRow
                key={d.id}
                title={d.domain || '域名'}
                subtitle={`${d.tenantName || ''} · ${d.targetIp || ''}`}
                statusText={DOMAIN_STATUS_NAME[d.status as number]}
                statusColor={domainStatusColor(d.status)}
                onClick={() => {
                  setRejectReason('')
                  setDetail(d)
                }}
              />
            ))}
          </View>
        )}
      </ScrollView>

      {detail && (
        <View style={{ position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.4)', zIndex: 999 }} onClick={() => setDetail(null)}>
          <View className='absolute bottom-0 left-0 right-0 bg-white rounded-t-2xl p-4' onClick={(e) => e.stopPropagation()}>
            <Text className='text-base font-medium block mb-1'>{detail.domain}</Text>
            <Text className='text-xs text-gray-500 block mb-3'>
              {detail.tenantName} · 目标IP {detail.targetIp}
            </Text>
            <View className='flex flex-wrap gap-2 mb-3'>
              <View className='px-3 py-1.5 rounded-lg text-sm text-white' style={{ background: '#0ea5e9' }} onClick={() => act(() => verifyDomain(detail.id), '已触发校验')}>
                <Text>检测解析</Text>
              </View>
              <View className='px-3 py-1.5 rounded-lg text-sm text-white' style={{ background: '#16a34a' }} onClick={() => act(() => activeDomain(detail.id), '已生效')}>
                <Text>通过生效</Text>
              </View>
              <View className='px-3 py-1.5 rounded-lg text-sm text-white' style={{ background: '#6b7280' }} onClick={() => act(() => disableDomain(detail.id), '已停用')}>
                <Text>停用</Text>
              </View>
            </View>
            <View className='mb-2'>
              <Text className='text-xs text-gray-500 block mb-1'>拒绝原因</Text>
              <Textarea
                className='bg-gray-100 rounded-lg px-3 py-2 text-sm w-full'
                placeholder='填写拒绝原因'
                value={rejectReason}
                onInput={(e: any) => setRejectReason(e.detail.value)}
                style={{ height: '60px' }}
              />
            </View>
            <View
              className='py-2.5 rounded-lg text-center'
              style={{ background: '#dc2626' }}
              onClick={() => {
                if (!rejectReason.trim()) {
                  Taro.showToast({ title: '请填写原因', icon: 'none' })
                  return
                }
                act(() => rejectDomain(detail.id, rejectReason), '已拒绝')
              }}
            >
              <Text className='text-sm text-white'>拒绝</Text>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default DomainReviewPage
