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 { pagePublishReviews, approvePublishReview, rejectPublishReview } from '@/api/app/appProduct'
import { getPageList, APP_TYPE_NAME, PUBLISH_STATUS_NAME, publishStatusColor } from '@/utils/devcenter'

definePageConfig({ navigationBarTitleText: '应用审核' })

const AppReviewPage: 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 load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await pagePublishReviews({ page: 1, limit: 50 })
      setList(getPageList(data))
    } catch (e) {
      // ignore
    } finally {
      setLoading(false)
    }
  }, [])
  useEffect(() => {
    if (isLoggedIn) load()
  }, [isLoggedIn, load])

  const approve = async (item: any) => {
    try {
      await approvePublishReview(item.productId)
      Taro.showToast({ title: '已通过', icon: 'success' })
      setDetail(null)
      load()
    } catch (e: any) {
      Taro.showToast({ title: e?.message || '操作失败', icon: 'none' })
    }
  }
  const reject = async (item: any) => {
    if (!rejectReason.trim()) {
      Taro.showToast({ title: '请填写拒绝原因', icon: 'none' })
      return
    }
    try {
      await rejectPublishReview({ productId: item.productId, rejectReason })
      Taro.showToast({ title: '已拒绝', icon: 'none' })
      setDetail(null)
      setRejectReason('')
      load()
    } catch (e: any) {
      Taro.showToast({ title: e?.message || '操作失败', icon: 'none' })
    }
  }

  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((app) => (
              <CellRow
                key={app.productId}
                title={app.productName || '未命名'}
                subtitle={`${APP_TYPE_NAME[app.appType as number] || ''} · ${app.developer || ''}`}
                statusText={PUBLISH_STATUS_NAME[app.publishStatus as string] || '待审核'}
                statusColor={publishStatusColor(app.publishStatus)}
                onClick={() => {
                  setRejectReason('')
                  setDetail(app)
                }}
              />
            ))}
          </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.productName}</Text>
            <Text className='text-xs text-gray-500 block mb-3'>{detail.description || '暂无描述'}</Text>
            <View className='mb-4'>
              <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: '70px' }}
              />
            </View>
            <View className='flex gap-3'>
              <View className='flex-1 py-2.5 rounded-lg text-center' style={{ background: '#16a34a' }} onClick={() => approve(detail)}>
                <Text className='text-sm text-white'>通过</Text>
              </View>
              <View className='flex-1 py-2.5 rounded-lg text-center' style={{ background: '#dc2626' }} onClick={() => reject(detail)}>
                <Text className='text-sm text-white'>拒绝</Text>
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default AppReviewPage
