/**
 * 客服工作台 - 工单管理
 */
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Plus, MessageSquare, Ticket as TicketIcon, Users, Building } from 'lucide-react'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Input, Label, Select } from '../../components/ui/Input'
import Modal from '../../components/ui/Modal'
import PageGuide from '../../components/ui/PageGuide'
import api from '../../lib/api'

export default function SupportDashboard() {
  const [tab, setTab] = useState<'tickets' | 'tenants' | 'chat'>('tickets')
  const [showCreate, setShowCreate] = useState(false)
  const [form, setForm] = useState({ title: '', content: '', category: '', priority: 'NORMAL' })
  const [selectedTicket, setSelectedTicket] = useState<any>(null)
  const [reply, setReply] = useState('')
  const queryClient = useQueryClient()

  const { data: tickets = [], isLoading } = useQuery({
    queryKey: ['support-tickets'],
    queryFn: () => api.get('/support/tickets').then(r => r.data.data),
  })

  const { data: tenants = [] } = useQuery({
    queryKey: ['support-tenants'],
    queryFn: () => api.get('/support/tenants').then(r => r.data.data),
    enabled: tab === 'tenants',
  })

  const createMutation = useMutation({
    mutationFn: (data: any) => api.post('/support/tickets', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['support-tickets'] })
      setShowCreate(false)
      setForm({ title: '', content: '', category: '', priority: 'NORMAL' })
      toast.success('工单已创建')
    },
  })

  const replyMutation = useMutation({
    mutationFn: (data: { id: string; content: string }) => api.post(`/support/tickets/${data.id}/messages`, { content: data.content }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['support-tickets'] })
      setReply('')
    },
  })

  const closeMutation = useMutation({
    mutationFn: (id: string) => api.post(`/support/tickets/${id}/close`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['support-tickets'] })
      setSelectedTicket(null)
      toast.success('工单已关闭')
    },
  })

  return (
    <div className="space-y-4">
      <PageGuide>客服工作台，集中处理员工咨询和工单。支持查看工单列表、处理进度跟踪、回复消息。关联：工单可关联员工档案，处理结果同步到花名册。</PageGuide>
      <div>
        <h1 className="text-xl font-semibold text-gray-900">客服工作台</h1>
        <p className="text-sm text-gray-500 mt-1">工单管理、客户会话、租户数据穿透</p>
      </div>

      <div className="flex gap-2 border-b">
        <button onClick={() => setTab('tickets')} className={`px-4 py-2 text-sm font-medium border-b-2 ${tab === 'tickets' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}>
          <TicketIcon className="w-4 h-4 inline mr-1" />工单管理
        </button>
        <button onClick={() => setTab('tenants')} className={`px-4 py-2 text-sm font-medium border-b-2 ${tab === 'tenants' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}>
          <Building className="w-4 h-4 inline mr-1" />租户管理
        </button>
        <button onClick={() => setTab('chat')} className={`px-4 py-2 text-sm font-medium border-b-2 ${tab === 'chat' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}>
          <MessageSquare className="w-4 h-4 inline mr-1" />客户会话
        </button>
      </div>

      {tab === 'tickets' && (
        <Card className="p-4">
          <div className="flex justify-between items-center mb-3">
            <span className="text-sm font-medium">工单列表</span>
            <Button size="sm" onClick={() => setShowCreate(true)}>
              <Plus className="w-4 h-4 mr-1" />提交工单
            </Button>
          </div>
          {isLoading ? (
            <div className="text-center py-8 text-gray-400 text-sm">加载中...</div>
          ) : tickets.length === 0 ? (
            <div className="text-center py-8 text-gray-400 text-sm">暂无工单</div>
          ) : (
            <div className="space-y-2">
              {tickets.map((t: any) => (
                <div
                  key={t.id}
                  className="border rounded-md p-3 hover:bg-gray-50 cursor-pointer"
                  onClick={() => setSelectedTicket(t)}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">{t.title}</span>
                    <div className="flex items-center gap-2">
                      <span className={`text-xs px-2 py-0.5 rounded ${t.status === 'OPEN' ? 'bg-blue-50 text-blue-600' : t.status === 'IN_PROGRESS' ? 'bg-amber-50 text-amber-600' : t.status === 'RESOLVED' ? 'bg-green-50 text-green-600' : 'bg-gray-100 text-gray-500'}`}>
                        {t.status === 'OPEN' ? '待处理' : t.status === 'IN_PROGRESS' ? '处理中' : t.status === 'RESOLVED' ? '已解决' : '已关闭'}
                      </span>
                      <span className={`text-xs px-2 py-0.5 rounded ${t.priority === 'URGENT' ? 'bg-red-50 text-red-600' : t.priority === 'HIGH' ? 'bg-orange-50 text-orange-600' : 'bg-gray-100 text-gray-500'}`}>
                        {t.priority === 'URGENT' ? '紧急' : t.priority === 'HIGH' ? '高' : t.priority === 'NORMAL' ? '普通' : '低'}
                      </span>
                    </div>
                  </div>
                  <div className="text-xs text-gray-500 mt-1">{t.org?.name} · {t._count?.messages || 0}条回复 · {new Date(t.createdAt).toLocaleString()}</div>
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      {tab === 'tenants' && (
        <Card className="p-4">
          <div className="text-sm font-medium mb-3">租户列表</div>
          {tenants.length === 0 ? (
            <div className="text-center py-8 text-gray-400 text-sm">暂无租户</div>
          ) : (
            <div className="space-y-2">
              {tenants.map((t: any) => (
                <div key={t.id} className="border rounded-md p-3">
                  <div className="flex items-center justify-between">
                    <div>
                      <span className="text-sm font-medium">{t.name}</span>
                      <span className="text-xs text-gray-400 ml-2">{t.plan}套餐</span>
                    </div>
                    <div className="text-xs text-gray-500">
                      {t._count?.employees || 0}员工 · {t._count?.users || 0}用户
                    </div>
                  </div>
                  <div className="text-xs text-gray-400 mt-1">
                    联系人：{t.contactName || '未设置'} · {t.contactPhone || '无'}
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      {tab === 'chat' && (
        <Card className="p-4">
          <div className="text-center py-8 text-gray-400 text-sm">客户会话功能开发中</div>
        </Card>
      )}

      {/* 创建工单弹窗 */}
      {showCreate && (
        <Modal open onClose={() => setShowCreate(false)} title="提交工单">
          <div className="space-y-3">
            <div>
              <Label>标题 *</Label>
              <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="简要描述问题" />
            </div>
            <div>
              <Label>内容 *</Label>
              <textarea value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} placeholder="详细描述问题" rows={4} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>分类</Label>
                <Select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
                  <option value="">请选择</option>
                  <option value="BUG">系统Bug</option>
                  <option value="CONSULT">功能咨询</option>
                  <option value="DATA">数据问题</option>
                  <option value="OTHER">其他</option>
                </Select>
              </div>
              <div>
                <Label>优先级</Label>
                <Select value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })}>
                  <option value="LOW">低</option>
                  <option value="NORMAL">普通</option>
                  <option value="HIGH">高</option>
                  <option value="URGENT">紧急</option>
                </Select>
              </div>
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="secondary" onClick={() => setShowCreate(false)}>取消</Button>
              <Button onClick={() => createMutation.mutate(form)} disabled={!form.title || !form.content}>提交</Button>
            </div>
          </div>
        </Modal>
      )}

      {/* 工单详情弹窗 */}
      {selectedTicket && (
        <Modal open onClose={() => setSelectedTicket(null)} title={selectedTicket.title} size="lg">
          <div className="space-y-3">
            <div className="text-xs text-gray-500">{selectedTicket.org?.name} · {new Date(selectedTicket.createdAt).toLocaleString()}</div>
            <div className="text-sm text-gray-700 bg-gray-50 p-3 rounded-md">{selectedTicket.content}</div>
            {selectedTicket.messages?.map((m: any, i: number) => (
              <div key={i} className={`text-sm p-2 rounded-md ${m.senderRole === 'SUPPORT' ? 'bg-blue-50 text-right' : 'bg-gray-50'}`}>
                <div className="text-xs text-gray-400 mb-1">{m.senderRole === 'SUPPORT' ? '客服' : '客户'} · {new Date(m.createdAt).toLocaleString()}</div>
                {m.content}
              </div>
            ))}
            {selectedTicket.status !== 'CLOSED' && (
              <>
                <div className="flex gap-2">
                  <Input value={reply} onChange={(e) => setReply(e.target.value)} placeholder="输入回复内容" onKeyDown={(e) => { if (e.key === 'Enter' && reply) replyMutation.mutate({ id: selectedTicket.id, content: reply }) }} />
                  <Button onClick={() => reply && replyMutation.mutate({ id: selectedTicket.id, content: reply })}>回复</Button>
                </div>
                <div className="flex justify-end">
                  <Button variant="secondary" onClick={() => closeMutation.mutate(selectedTicket.id)}>关闭工单</Button>
                </div>
              </>
            )}
          </div>
        </Modal>
      )}
    </div>
  )
}
