/**
 * 工单详情页
 */
import { useState, useEffect } from 'react';
import { View, Text, Image, Input, ScrollView, Button } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { getTicketDetail, listTicketReply, replyTicket } from '../../api/ticket';
import type { Ticket, TicketReply } from '../../types/ticket';
import './detail.scss';

const STATUS_MAP: Record<string, { label: string; color: string }> = {
  pending: { label: '待处理', color: '#ff9500' },
  processing: { label: '处理中', color: '#007aff' },
  waiting: { label: '等待回复', color: '#5856d6' },
  resolved: { label: '已解决', color: '#34c759' },
  closed: { label: '已关闭', color: '#999' },
  rejected: { label: '已拒绝', color: '#ff3b30' }
};

const PRIORITY_MAP: Record<string, { label: string; color: string }> = {
  low: { label: '低', color: '#34c759' },
  medium: { label: '中', color: '#ff9500' },
  high: { label: '高', color: '#ff3b30' },
  urgent: { label: '紧急', color: '#af52de' }
};

const TYPE_MAP: Record<string, string> = {
  technical: '技术问题',
  billing: '账单问题',
  account: '账户问题',
  feature: '功能建议',
  bug: 'Bug 反馈',
  other: '其他'
};

export default function TicketDetail() {
  const router = useRouter();
  const [ticket, setTicket] = useState<Ticket | null>(null);
  const [replies, setReplies] = useState<TicketReply[]>([]);
  const [loading, setLoading] = useState(true);
  const [replyContent, setReplyContent] = useState('');
  const [sending, setSending] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    const { id } = router.params;
    if (!id) return;
    
    setLoading(true);
    try {
      const [ticketData, repliesData] = await Promise.all([
        getTicketDetail(id),
        listTicketReply(id)
      ]);
      setTicket(ticketData);
      setReplies(repliesData);
    } catch (e) {
      console.error('加载失败', e);
    } finally {
      setLoading(false);
    }
  };

  // 发送回复
  const handleReply = async () => {
    if (!replyContent.trim()) {
      Taro.showToast({ title: '请输入回复内容', icon: 'none' });
      return;
    }
    
    if (!ticket) return;
    
    setSending(true);
    try {
      const reply = await replyTicket(ticket.id, replyContent);
      setReplies([...replies, reply]);
      setReplyContent('');
      Taro.showToast({ title: '发送成功', icon: 'success' });
    } catch (e) {
      Taro.showToast({ title: '发送失败', icon: 'none' });
    } finally {
      setSending(false);
    }
  };

  // 格式化时间
  const formatTime = (time: string) => {
    const date = new Date(time.replace(' ', 'T'));
    return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  if (loading) {
    return (
      <View className="ticket-detail">
        <View className="loading"><Text>加载中...</Text></View>
      </View>
    );
  }

  if (!ticket) {
    return (
      <View className="ticket-detail">
        <View className="empty"><Text>工单不存在</Text></View>
      </View>
    );
  }

  return (
    <View className="ticket-detail">
      {/* 工单信息 */}
      <View className="ticket-info">
        <View className="info-header">
          <Text className="ticket-no">{ticket.ticketNo}</Text>
          <View 
            className="status-tag"
            style={{ background: STATUS_MAP[ticket.status]?.color + '20', color: STATUS_MAP[ticket.status]?.color }}
          >
            {STATUS_MAP[ticket.status]?.label}
          </View>
        </View>
        
        <Text className="ticket-title">{ticket.title}</Text>
        
        <View className="info-meta">
          <View 
            className="priority-badge"
            style={{ color: PRIORITY_MAP[ticket.priority]?.color }}
          >
            优先级：{PRIORITY_MAP[ticket.priority]?.label}
          </View>
          <Text className="type-text">类型：{TYPE_MAP[ticket.type]}</Text>
          <Text className="time-text">{formatTime(ticket.createTime)}</Text>
        </View>
      </View>

      {/* 问题内容 */}
      <View className="content-section">
        <View className="section-label">问题描述</View>
        <View className="content-body">
          <View className="user-message">
            <Image 
              className="user-avatar"
              src={ticket.creatorAvatar}
            />
            <View className="message-content">
              <View className="message-header">
                <Text className="user-name">{ticket.creatorName}</Text>
              </View>
              <View className="message-body">
                <Text className="message-text">{ticket.content}</Text>
              </View>
            </View>
          </View>
        </View>
      </View>

      {/* 回复列表 */}
      {replies.length > 0 && (
        <View className="replies-section">
          <View className="section-label">沟通记录 ({replies.length})</View>
          <View className="replies-list">
            {replies.map(reply => (
              <View 
                key={reply.id}
                className={`reply-item ${reply.senderRole === 'support' ? 'support' : ''}`}
              >
                <Image 
                  className="reply-avatar"
                  src={reply.senderAvatar}
                />
                <View className="reply-content">
                  <View className="reply-header">
                    <Text className="reply-name">
                      {reply.senderName}
                      {reply.senderRole === 'support' && (
                        <Text className="support-tag">客服</Text>
                      )}
                    </Text>
                    <Text className="reply-time">{formatTime(reply.createTime)}</Text>
                  </View>
                  <View className="reply-body">
                    <Text className="reply-text">{reply.content}</Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* 解决方案 */}
      {ticket.status === 'resolved' && ticket.solution && (
        <View className="solution-section">
          <View className="section-label">解决方案</View>
          <View className="solution-content">
            <Text>{ticket.solution}</Text>
          </View>
        </View>
      )}

      {/* 回复输入框 */}
      {ticket.status !== 'closed' && ticket.status !== 'resolved' && (
        <View className="reply-input">
          <Input
            className="input-field"
            placeholder="请输入回复内容..."
            value={replyContent}
            onInput={(e) => setReplyContent(e.detail.value)}
            onConfirm={handleReply}
          />
          <Button 
            className="send-btn"
            onClick={handleReply}
            loading={sending}
          >
            发送
          </Button>
        </View>
      )}
    </View>
  );
}
