/**
 * 工单中心
 */
import { useState, useEffect } from 'react';
import { View, Text, Image, Input, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { pageTicket, getTicketStats, createTicket, closeTicket, rateTicket } from '../../api/ticket';
import type { Ticket, TicketStats } from '../../types/ticket';
import './index.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 TicketCenter() {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [total, setTotal] = useState(0);
  const [stats, setStats] = useState<TicketStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState('all');
  const [keyword, setKeyword] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [showDetail, setShowDetail] = useState<Ticket | null>(null);
  
  // 创建表单
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    type: 'technical' as Ticket['type'],
    priority: 'medium' as Ticket['priority'],
    category: 'api' as Ticket['category']
  });

  useEffect(() => {
    loadStats();
    loadTickets();
  }, []);

  // 加载统计
  const loadStats = async () => {
    try {
      const data = await getTicketStats();
      setStats(data);
    } catch (e) {
      console.error('加载统计失败', e);
    }
  };

  // 加载工单列表
  const loadTickets = async () => {
    setLoading(true);
    try {
      const params: any = { page: 1, pageSize: 20 };
      if (status !== 'all') params.status = status;
      if (keyword) params.keyword = keyword;
      
      const data = await pageTicket(params);
      setTickets(data.list);
      setTotal(data.total);
    } catch (e) {
      console.error('加载工单失败', e);
    } finally {
      setLoading(false);
    }
  };

  // 创建工单
  const handleCreate = async () => {
    if (!formData.title.trim()) {
      Taro.showToast({ title: '请填写标题', icon: 'none' });
      return;
    }
    if (!formData.content.trim()) {
      Taro.showToast({ title: '请填写内容', icon: 'none' });
      return;
    }
    
    try {
      await createTicket(formData);
      Taro.showToast({ title: '提交成功', icon: 'success' });
      setShowCreate(false);
      setFormData({ title: '', content: '', type: 'technical', priority: 'medium', category: 'api' });
      loadTickets();
      loadStats();
    } catch (e) {
      Taro.showToast({ title: '提交失败', icon: 'none' });
    }
  };

  // 关闭工单
  const handleClose = async (id: string) => {
    Taro.showModal({
      title: '确认关闭',
      content: '确定要关闭这个工单吗？',
      success: async (res) => {
        if (res.confirm) {
          await closeTicket(id);
          Taro.showToast({ title: '已关闭', icon: 'success' });
          loadTickets();
        }
      }
    });
  };

  // 评价工单
  const handleRate = (ticket: Ticket) => {
    Taro.showModal({
      title: '工单评价',
      editable: true,
      placeholderText: '请输入您的反馈（选填）',
      success: async (res) => {
        if (res.confirm) {
          await rateTicket(ticket.id, 5, res.content || '');
          Taro.showToast({ title: '感谢您的反馈', icon: 'success' });
          loadTickets();
        }
      }
    });
  };

  // 查看详情
  const handleViewDetail = (ticket: Ticket) => {
    Taro.navigateTo({ url: `/developer/ticket/detail?id=${ticket.id}` });
  };

  // 格式化时间
  const formatTime = (time: string) => {
    const date = new Date(time.replace(' ', 'T'));
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) return '刚刚';
    if (diff < 3600000) return `${Math.floor(diff / 60000)} 分钟前`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)} 小时前`;
    return time.slice(0, 10);
  };

  // 格式化解决时间
  const formatResolveTime = (minutes?: number) => {
    if (!minutes) return '-';
    if (minutes < 60) return `${minutes} 分钟`;
    return `${(minutes / 60).toFixed(1)} 小时`;
  };

  return (
    <View className="ticket-center">
      {/* 统计卡片 */}
      {stats && (
        <View className="stats-cards">
          <View className="stats-card">
            <Text className="stats-num">{stats.total}</Text>
            <Text className="stats-label">全部工单</Text>
          </View>
          <View className="stats-card warning">
            <Text className="stats-num">{stats.pending}</Text>
            <Text className="stats-label">待处理</Text>
          </View>
          <View className="stats-card processing">
            <Text className="stats-num">{stats.processing}</Text>
            <Text className="stats-label">处理中</Text>
          </View>
          <View className="stats-card success">
            <Text className="stats-num">{stats.resolved}</Text>
            <Text className="stats-label">已解决</Text>
          </View>
        </View>
      )}

      {/* 筛选栏 */}
      <View className="filter-bar">
        <ScrollView className="status-tabs" scrollX>
          {[
            { value: 'all', label: '全部' },
            { value: 'pending', label: '待处理' },
            { value: 'processing', label: '处理中' },
            { value: 'resolved', label: '已解决' },
            { value: 'closed', label: '已关闭' }
          ].map(tab => (
            <View
              key={tab.value}
              className={`status-tab ${status === tab.value ? 'active' : ''}`}
              onClick={() => { setStatus(tab.value); loadTickets(); }}
            >
              {tab.label}
              {tab.value !== 'all' && stats && tab.value === 'pending' && stats.pending > 0 && (
                <View className="tab-badge">{stats.pending}</View>
              )}
            </View>
          ))}
        </ScrollView>
        
        <Button className="create-btn" onClick={() => setShowCreate(true)}>
          + 提交工单
        </Button>
      </View>

      {/* 工单列表 */}
      <ScrollView className="ticket-list" scrollY>
        {loading ? (
          <View className="loading"><Text>加载中...</Text></View>
        ) : tickets.length === 0 ? (
          <View className="empty">
            <Text>暂无工单</Text>
          </View>
        ) : (
          tickets.map(ticket => (
            <View key={ticket.id} className="ticket-card" onClick={() => handleViewDetail(ticket)}>
              <View className="ticket-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="ticket-meta">
                <View className="meta-left">
                  <View className="priority-tag" style={{ color: PRIORITY_MAP[ticket.priority]?.color }}>
                    {PRIORITY_MAP[ticket.priority]?.label}
                  </View>
                  <Text className="type-text">{TYPE_MAP[ticket.type]}</Text>
                  {ticket.responseCount > 0 && (
                    <Text className="reply-count">{ticket.responseCount} 条回复</Text>
                  )}
                </View>
                <Text className="time-text">{formatTime(ticket.createTime)}</Text>
              </View>
              
              {ticket.status === 'resolved' && (
                <View className="ticket-footer">
                  {ticket.solution && (
                    <Text className="solution-text">解决方案：{ticket.solution}</Text>
                  )}
                  <View className="footer-actions">
                    {!ticket.rating && (
                      <Button className="action-btn" onClick={(e) => { e.stopPropagation(); handleRate(ticket); }}>
                        评价
                      </Button>
                    )}
                    {ticket.rating && (
                      <Text className="rating-text">⭐ {ticket.rating}分</Text>
                    )}
                  </View>
                </View>
              )}
              
              {ticket.status === 'pending' && (
                <View className="ticket-footer">
                  <Button className="action-btn close" onClick={(e) => { e.stopPropagation(); handleClose(ticket.id); }}>
                    关闭工单
                  </Button>
                </View>
              )}
            </View>
          ))
        )}
      </ScrollView>

      {/* 创建工单弹窗 */}
      {showCreate && (
        <View className="modal-mask" onClick={() => setShowCreate(false)}>
          <View className="create-modal" onClick={(e) => e.stopPropagation()}>
            <View className="modal-header">
              <Text className="modal-title">提交工单</Text>
              <Text className="modal-close" onClick={() => setShowCreate(false)}>✕</Text>
            </View>
            
            <ScrollView className="modal-body" scrollY>
              <View className="form-item">
                <Text className="form-label">问题类型</Text>
                <View className="type-selector">
                  {Object.entries(TYPE_MAP).map(([key, label]) => (
                    <View
                      key={key}
                      className={`type-option ${formData.type === key ? 'active' : ''}`}
                      onClick={() => setFormData({ ...formData, type: key as Ticket['type'], category: key as Ticket['category'] })}
                    >
                      {label}
                    </View>
                  ))}
                </View>
              </View>
              
              <View className="form-item">
                <Text className="form-label">优先级</Text>
                <View className="priority-selector">
                  {Object.entries(PRIORITY_MAP).map(([key, { label, color }]) => (
                    <View
                      key={key}
                      className={`priority-option ${formData.priority === key ? 'active' : ''}`}
                      style={{ 
                        borderColor: formData.priority === key ? color : '#ddd',
                        color: formData.priority === key ? color : '#666'
                      }}
                      onClick={() => setFormData({ ...formData, priority: key as Ticket['priority'] })}
                    >
                      {label}
                    </View>
                  ))}
                </View>
              </View>
              
              <View className="form-item">
                <Text className="form-label">标题 <Text className="required">*</Text></Text>
                <Input
                  className="form-input"
                  placeholder="请简要描述您的问题"
                  value={formData.title}
                  onInput={(e) => setFormData({ ...formData, title: e.detail.value })}
                />
              </View>
              
              <View className="form-item">
                <Text className="form-label">详细描述 <Text className="required">*</Text></Text>
                <View className="textarea-wrap">
                  <textarea
                    className="form-textarea"
                    placeholder="请详细描述您遇到的问题，包括：\n1. 问题描述\n2. 复现步骤\n3. 错误信息\n4. 环境信息"
                    value={formData.content}
                    onInput={(e) => setFormData({ ...formData, content: e.detail.value })}
                  />
                </View>
              </View>
            </ScrollView>
            
            <View className="modal-footer">
              <Button className="submit-btn" onClick={handleCreate}>提交工单</Button>
            </View>
          </View>
        </View>
      )}
    </View>
  );
}
