import React, { useState, useEffect } from 'react'
import { View, Text, Button } from '@tarojs/components'
import Taro, { usePullDownRefresh } from '@tarojs/taro'
import { pageApply, reviewApply } from '@/api/developer/developer'
import type { Apply, ApplyParam, ApplyStatus, ApplyType } from '@/types/developer'
import './audit.scss'

// 类型配置
const TYPE_CONFIG: Record<ApplyType, { label: string; icon: string }> = {
  developer: { label: '开发者申请', icon: '🛠️' },
  project: { label: '项目权限', icon: '📁' },
  member: { label: '成员权限', icon: '👥' },
}

// 状态配置
const STATUS_CONFIG: Record<ApplyStatus, { label: string; color: string; bgColor: string }> = {
  pending: { label: '待审核', color: '#faad14', bgColor: '#fffbe6' },
  approved: { label: '已通过', color: '#52c41a', bgColor: '#f6ffed' },
  rejected: { label: '已拒绝', color: '#ff4d4f', bgColor: '#fff1f0' },
}

const AuditPage: React.FC = () => {
  const [loading, setLoading] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [list, setList] = useState<Apply[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [currentTab, setCurrentTab] = useState<'pending' | 'approved' | 'rejected' | 'all'>('pending')
  const [processing, setProcessing] = useState<number | null>(null)

  // 加载数据
  const loadData = async (pageNum: number = 1, isRefresh = false) => {
    if (loading) return
    setLoading(true)
    if (isRefresh) setRefreshing(true)

    try {
      const params: ApplyParam = {
        page: pageNum,
        limit: 20,
        status: currentTab === 'all' ? undefined : currentTab,
      }
      const data = await pageApply(params)

      if (pageNum === 1) {
        setList(data?.records || [])
      } else {
        setList(prev => [...prev, ...(data?.records || [])])
      }

      const total = data?.total || 0
      const records = data?.records || []
      setHasMore(records.length > 0 && (pageNum * 20) < total)
      setPage(pageNum)
    } catch (err) {
      console.error('加载失败', err)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  useEffect(() => {
    loadData(1)
  }, [currentTab])

  // 下拉刷新
  usePullDownRefresh(() => {
    loadData(1, true)
  })

  // 加载更多
  const onReachBottom = () => {
    if (hasMore && !loading) {
      loadData(page + 1)
    }
  }

  // 审批
  const handleReview = async (item: Apply, status: 'approved' | 'rejected') => {
    setProcessing(item.id!)
    try {
      await reviewApply(item.id!, status)
      Taro.showToast({ title: status === 'approved' ? '已通过' : '已拒绝', icon: 'success' })
      loadData(1)
    } catch (err) {
      console.error('审批失败', err)
      Taro.showToast({ title: '操作失败', icon: 'none' })
    } finally {
      setProcessing(null)
    }
  }

  // 格式化日期
  const formatDate = (dateStr?: string) => {
    if (!dateStr) return '-'
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }

  // Tab 配置
  const tabs: { key: 'pending' | 'approved' | 'rejected' | 'all'; label: string }[] = [
    { key: 'pending', label: '待审核' },
    { key: 'approved', label: '已通过' },
    { key: 'rejected', label: '已拒绝' },
    { key: 'all', label: '全部' },
  ]

  return (
    <View className="audit-page">
      {/* 头部 */}
      <View className="audit-page__header">
        <Text className="audit-page__title">📋 权限审批</Text>
      </View>

      {/* Tab */}
      <View className="audit-page__tabs">
        {tabs.map((tab) => (
          <View
            key={tab.key}
            className={`audit-page__tab ${currentTab === tab.key ? 'active' : ''}`}
            onClick={() => setCurrentTab(tab.key)}
          >
            {tab.label}
            {tab.key === 'pending' && (
              <View className="audit-page__tab-badge">
                {list.filter(i => i.status === 'pending').length}
              </View>
            )}
          </View>
        ))}
      </View>

      {/* 列表 */}
      <View className="audit-page__list">
        {list.length === 0 && !loading ? (
          <View className="audit-page__empty">
            <Text className="audit-page__empty-icon">📭</Text>
            <Text className="audit-page__empty-text">暂无申请记录</Text>
          </View>
        ) : (
          list.map((item) => (
            <View key={item.id} className="audit-card">
              <View className="audit-card__header">
                <View className="audit-card__applicant">
                  <View className="audit-card__avatar">
                    {item.applicantAvatar ? (
                      <View
                        className="audit-card__avatar-img"
                        style={{ backgroundImage: `url(${item.applicantAvatar})` }}
                      />
                    ) : (
                      <Text className="audit-card__avatar-text">
                        {(item.applicantName || '?').charAt(0).toUpperCase()}
                      </Text>
                    )}
                  </View>
                  <View className="audit-card__applicant-info">
                    <Text className="audit-card__name">{item.applicantName}</Text>
                    <Text className="audit-card__type">
                      {TYPE_CONFIG[item.type as ApplyType]?.icon} {TYPE_CONFIG[item.type as ApplyType]?.label}
                    </Text>
                  </View>
                </View>
                <View
                  className="audit-card__status"
                  style={{
                    color: STATUS_CONFIG[item.status as ApplyStatus]?.color,
                    background: STATUS_CONFIG[item.status as ApplyStatus]?.bgColor,
                  }}
                >
                  {STATUS_CONFIG[item.status as ApplyStatus]?.label}
                </View>
              </View>

              <View className="audit-card__body">
                <View className="audit-card__row">
                  <Text className="audit-card__label">申请目标:</Text>
                  <Text className="audit-card__value">{item.targetName || '-'}</Text>
                </View>
                {item.reason && (
                  <View className="audit-card__row">
                    <Text className="audit-card__label">申请理由:</Text>
                    <Text className="audit-card__value">{item.reason}</Text>
                  </View>
                )}
                <View className="audit-card__row">
                  <Text className="audit-card__label">申请时间:</Text>
                  <Text className="audit-card__value">{formatDate(item.createTime)}</Text>
                </View>
                {item.reviewerName && (
                  <View className="audit-card__row">
                    <Text className="audit-card__label">审核人:</Text>
                    <Text className="audit-card__value">{item.reviewerName}</Text>
                  </View>
                )}
                {item.reviewTime && (
                  <View className="audit-card__row">
                    <Text className="audit-card__label">审核时间:</Text>
                    <Text className="audit-card__value">{formatDate(item.reviewTime)}</Text>
                  </View>
                )}
              </View>

              {item.reviewRemark && (
                <View className="audit-card__remark">
                  <Text className="audit-card__remark-label">审核备注:</Text>
                  <Text className="audit-card__remark-content">{item.reviewRemark}</Text>
                </View>
              )}

              {item.status === 'pending' && (
                <View className="audit-card__actions">
                  <Button
                    className="audit-card__btn audit-card__btn--reject"
                    size="mini"
                    loading={processing === item.id}
                    onClick={() => handleReview(item, 'rejected')}
                  >
                    拒绝
                  </Button>
                  <Button
                    className="audit-card__btn audit-card__btn--approve"
                    size="mini"
                    loading={processing === item.id}
                    onClick={() => handleReview(item, 'approved')}
                  >
                    通过
                  </Button>
                </View>
              )}
            </View>
          ))
        )}

        {/* 加载状态 */}
        {loading && list.length > 0 && (
          <View className="audit-page__loading">
            <Text>加载中...</Text>
          </View>
        )}

        {!hasMore && list.length > 0 && (
          <View className="audit-page__no-more">
            <Text>没有更多了</Text>
          </View>
        )}
      </View>
    </View>
  )
}

export default AuditPage
