import React, { useState, useEffect, useCallback } from 'react'
import { View, Text, ScrollView, Input } 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 { getAllTickets, getTicketReplies, replyTicket, updateTicketStatus } from '@/api/app/ticket'
import { getPageList, TICKET_STATUS_NAME, TICKET_PRIORITY_NAME, TICKET_CATEGORY_NAME, ticketStatusColor } from '@/utils/devcenter'

definePageConfig({ navigationBarTitleText: '工单处理' })

const AdminTicketsPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [loading, setLoading] = useState(true)
  const [list, setList] = useState<any[]>([])
  const [detail, setDetail] = useState<any>(null)
  const [replies, setReplies] = useState<any[]>([])
  const [replyText, setReplyText] = useState('')

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

  const openDetail = async (item: any) => {
    setDetail(item)
    setReplyText('')
    try {
      const r = await getTicketReplies(item.ticketId)
      setReplies(Array.isArray(r) ? r : getPageList(r))
    } catch (e) {
      setReplies([])
    }
  }
  const sendReply = async () => {
    if (!replyText.trim() || !detail) return
    try {
      await replyTicket(detail.ticketId, replyText)
      Taro.showToast({ title: '已回复', icon: 'none' })
      setReplyText('')
      openDetail(detail)
    } catch (e: any) {
      Taro.showToast({ title: e?.message || '回复失败', icon: 'none' })
    }
  }
  const setStatus = async (status: string) => {
    if (!detail) return
    try {
      await updateTicketStatus(detail.ticketId, status)
      Taro.showToast({ title: '已更新', icon: 'none' })
      setDetail(null)
      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((t) => (
              <CellRow
                key={t.ticketId}
                title={t.title || '工单'}
                subtitle={`#${t.ticketNo || t.ticketId} · ${TICKET_CATEGORY_NAME[t.category as string] || ''} · ${t.submitUserName || ''}`}
                statusText={TICKET_STATUS_NAME[t.status as string]}
                statusColor={ticketStatusColor(t.status)}
                onClick={() => openDetail(t)}
              />
            ))}
          </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.title}</Text>
            <Text className='text-xs text-gray-500 block mb-3'>
              {TICKET_STATUS_NAME[detail.status as string]} · {TICKET_PRIORITY_NAME[detail.priority as string]} ·{' '}
              {detail.assigneeName ? '处理人 ' + detail.assigneeName : '未分配'}
            </Text>
            <ScrollView scrollY style={{ maxHeight: '35vh' }}>
              {replies.length === 0 ? (
                <Text className='text-xs text-gray-400'>暂无回复</Text>
              ) : (
                replies.map((r, i) => (
                  <View key={i} className='bg-gray-100 rounded-lg p-2 mb-2'>
                    <Text className='text-sm text-gray-700'>{r.content || r.replyContent || ''}</Text>
                    <Text className='text-xs text-gray-400 mt-1 block'>
                      {r.userName || r.replierName || ''} · {(r.createTime || '').slice(0, 16)}
                    </Text>
                  </View>
                ))
              )}
            </ScrollView>
            <View className='flex items-center gap-2 mt-3'>
              <Input
                className='flex-1 bg-gray-100 rounded-lg px-3 py-2 text-sm'
                placeholder='输入回复...'
                value={replyText}
                onInput={(e: any) => setReplyText(e.detail.value)}
              />
              <View className='px-4 py-2 rounded-lg' style={{ background: '#2563eb' }} onClick={sendReply}>
                <Text className='text-white text-sm'>回复</Text>
              </View>
            </View>
            <View className='flex gap-3 mt-3'>
              <View className='flex-1 py-2 rounded-lg text-center' style={{ background: '#16a34a' }} onClick={() => setStatus('resolved')}>
                <Text className='text-sm text-white'>标记已解决</Text>
              </View>
              <View className='flex-1 py-2 rounded-lg text-center' style={{ background: '#6b7280' }} onClick={() => setStatus('closed')}>
                <Text className='text-sm text-white'>关闭</Text>
              </View>
            </View>
            <View className='mt-2 text-center' onClick={() => setDetail(null)}>
              <Text className='text-xs text-gray-400'>关闭</Text>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default AdminTicketsPage
