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

definePageConfig({ navigationBarTitleText: '我的工单' })

const CATEGORIES = ['bug', 'feature', 'consultation', 'complaint', 'other']
const PRIORITIES = ['urgent', 'high', 'normal', 'low']

const MyTicketsPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [loading, setLoading] = useState(true)
  const [list, setList] = useState<any[]>([])
  const [showCreate, setShowCreate] = useState(false)
  const [detail, setDetail] = useState<any>(null)
  const [replies, setReplies] = useState<any[]>([])
  const [replyText, setReplyText] = useState('')
  const [createForm, setCreateForm] = useState({ title: '', category: 'bug', priority: 'normal', description: '' })
  const [submitting, setSubmitting] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await getMyTickets({ 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 submit = async () => {
    if (!createForm.title.trim()) {
      Taro.showToast({ title: '请填写标题', icon: 'none' })
      return
    }
    setSubmitting(true)
    try {
      await submitTicket({ ...createForm, content: createForm.description })
      Taro.showToast({ title: '提交成功', icon: 'success' })
      setShowCreate(false)
      load()
    } catch (e: any) {
      Taro.showToast({ title: e?.message || '提交失败', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <View className='min-h-screen bg-gray-100'>
      <NavBar
        title='我的工单'
        rightText='提交'
        onRightClick={() => {
          setCreateForm({ title: '', category: 'bug', priority: 'normal', description: '' })
          setShowCreate(true)
        }}
      />
      <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.createTime || '').slice(0, 10)}`}
                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-2'>{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]}
            </Text>
            <ScrollView scrollY style={{ maxHeight: '40vh' }}>
              {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) => 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='mt-2 text-center' onClick={() => setDetail(null)}>
              <Text className='text-xs text-gray-400'>关闭</Text>
            </View>
          </View>
        </View>
      )}

      {showCreate && (
        <View style={{ position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.4)', zIndex: 999 }}>
          <View className='absolute bottom-0 left-0 right-0 bg-white rounded-t-2xl p-4'>
            <Text className='text-base font-medium block mb-3'>提交工单</Text>
            <View className='mb-3'>
              <Text className='text-xs text-gray-500 block mb-1'>标题</Text>
              <Input
                className='bg-gray-100 rounded-lg px-3 py-2 text-sm'
                placeholder='一句话描述问题'
                value={createForm.title}
                onInput={(e) => setCreateForm({ ...createForm, title: e.detail.value })}
              />
            </View>
            <View className='mb-3'>
              <Text className='text-xs text-gray-500 block mb-1'>类型</Text>
              <View className='flex flex-wrap gap-2'>
                {CATEGORIES.map((c) => (
                  <View
                    key={c}
                    className='px-3 py-1 rounded-full text-xs'
                    style={createForm.category === c ? { background: '#2563eb', color: '#fff' } : { background: '#f3f4f6', color: '#374151' }}
                    onClick={() => setCreateForm({ ...createForm, category: c })}
                  >
                    <Text>{TICKET_CATEGORY_NAME[c]}</Text>
                  </View>
                ))}
              </View>
            </View>
            <View className='mb-3'>
              <Text className='text-xs text-gray-500 block mb-1'>优先级</Text>
              <View className='flex flex-wrap gap-2'>
                {PRIORITIES.map((p) => (
                  <View
                    key={p}
                    className='px-3 py-1 rounded-full text-xs'
                    style={createForm.priority === p ? { background: '#2563eb', color: '#fff' } : { background: '#f3f4f6', color: '#374151' }}
                    onClick={() => setCreateForm({ ...createForm, priority: p })}
                  >
                    <Text>{TICKET_PRIORITY_NAME[p]}</Text>
                  </View>
                ))}
              </View>
            </View>
            <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={createForm.description}
                onInput={(e) => setCreateForm({ ...createForm, description: e.detail.value })}
                style={{ height: '80px' }}
              />
            </View>
            <View className='flex gap-3'>
              <View className='flex-1 py-2.5 rounded-lg bg-gray-100 text-center' onClick={() => setShowCreate(false)}>
                <Text className='text-sm text-gray-600'>取消</Text>
              </View>
              <View className='flex-1 py-2.5 rounded-lg text-center' style={{ background: '#2563eb' }} onClick={submit}>
                <Text className='text-sm text-white'>{submitting ? '提交中...' : '提交'}</Text>
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default MyTicketsPage
