import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { TICKET_TYPE_LABELS, type TicketTypeDto } from '@dukang/shared-types';
import SubPageHeader from '../components/SubPageHeader';
import { request } from '../lib/api';
import { usePageView } from '../lib/usePageView';

type TicketRow = {
  id: string;
  ticketNo: string;
  ticketType: TicketTypeDto;
  status: string;
  orderNo?: string;
  remark?: string;
  createdAt: string;
};

const STATUS_LABEL: Record<string, string> = {
  PENDING: '待处理',
  OPEN: '处理中',
  RESOLVED: '已完成',
  REJECTED: '已驳回',
  CLOSED: '已关闭',
};

export default function AfterSaleListPage() {
  usePageView('after_sale_list_view');
  const navigate = useNavigate();
  const [items, setItems] = useState<TicketRow[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    request<{ items: TicketRow[] }>('USER_H5', '/trade/after-sale-tickets?pageSize=50')
      .then((res) => setItems(res.items ?? []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="after-sale-page">
      <SubPageHeader title="我的售后" onBack={() => navigate(-1)} />
      <main className="after-sale-body">
        {loading ? (
          <p className="after-sale-empty">加载中…</p>
        ) : items.length === 0 ? (
          <div className="after-sale-empty-box">
            <p className="after-sale-empty">暂无售后工单</p>
            <button type="button" className="after-sale-primary" onClick={() => navigate('/after-sale')}>
              申请售后
            </button>
          </div>
        ) : (
          <div className="after-sale-order-list">
            {items.map((t) => (
              <div key={t.id} className="after-sale-order-item after-sale-ticket-card">
                <div className="after-sale-ticket-head">
                  <span>{TICKET_TYPE_LABELS[t.ticketType] ?? t.ticketType}</span>
                  <span className="after-sale-ticket-status">{STATUS_LABEL[t.status] ?? t.status}</span>
                </div>
                <p className="after-sale-order-no">{t.ticketNo}</p>
                <p className="after-sale-order-meta">订单 {t.orderNo ?? '—'} · {new Date(t.createdAt).toLocaleString()}</p>
                {t.remark ? <p className="after-sale-order-meta">{t.remark}</p> : null}
              </div>
            ))}
            <button type="button" className="after-sale-primary" onClick={() => navigate('/after-sale')}>
              新建售后
            </button>
          </div>
        )}
      </main>
    </div>
  );
}
