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 {
  pageGitAccounts,
  approveGitAccount,
  rejectGitAccount,
  pagePermissionRequests,
  approvePermissionRequest,
  rejectPermissionRequest,
} from '@/api/app/developer'
import { getPageList } from '@/utils/devcenter'

definePageConfig({ navigationBarTitleText: 'Git / 权限审核' })

const GitReviewPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [tab, setTab] = useState<'git' | 'perm'>('git')
  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 = tab === 'git' ? await pageGitAccounts({ page: 1, limit: 50 }) : await pagePermissionRequests({ page: 1, limit: 50 })
      setList(getPageList(data))
    } catch (e) {
      // ignore
    } finally {
      setLoading(false)
    }
  }, [tab])
  useEffect(() => {
    if (isLoggedIn) load()
  }, [isLoggedIn, load])

  const approve = async (item: any) => {
    try {
      if (tab === 'git') await approveGitAccount(item.id)
      else await approvePermissionRequest(item.id)
      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 {
      if (tab === 'git') await rejectGitAccount(item.id, rejectReason)
      else await rejectPermissionRequest(item.id, rejectReason)
      Taro.showToast({ title: '已拒绝', icon: 'none' })
      setDetail(null)
      setRejectReason('')
      load()
    } catch (e: any) {
      Taro.showToast({ title: e?.message || '操作失败', icon: 'none' })
    }
  }

  const titleOf = (item: any) =>
    tab === 'git' ? item.username || item.gitUsername || 'Git 账号' : item.gitUsername || item.repoName || '权限申请'

  return (
    <View className='min-h-screen bg-gray-100'>
      <NavBar title='Git / 权限审核' />
      <View className='flex bg-white'>
        <View
          className={`flex-1 text-center py-3 text-sm ${tab === 'git' ? 'font-medium border-b-2 text-blue-500' : 'text-gray-500'}`}
          style={tab === 'git' ? { borderBottomColor: '#2563eb' } : {}}
          onClick={() => setTab('git')}
        >
          <Text>Git 账号</Text>
        </View>
        <View
          className={`flex-1 text-center py-3 text-sm ${tab === 'perm' ? 'font-medium border-b-2 text-blue-500' : 'text-gray-500'}`}
          style={tab === 'perm' ? { borderBottomColor: '#2563eb' } : {}}
          onClick={() => setTab('perm')}
        >
          <Text>权限申请</Text>
        </View>
      </View>
      <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((item) => (
              <CellRow
                key={item.id}
                title={titleOf(item)}
                subtitle={tab === 'git' ? `状态：${item.status || 'pending'}` : `${item.repoName || item.repo || ''} · ${item.reason || ''}`}
                onClick={() => {
                  setRejectReason('')
                  setDetail(item)
                }}
              />
            ))}
          </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'>{titleOf(detail)}</Text>
            <Text className='text-xs text-gray-500 block mb-3'>{tab === 'git' ? detail.email || '' : detail.reason || ''}</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 GitReviewPage
