import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  INVOICE_KIND_LABELS,
  INVOICE_STATUS_LABELS,
  INVOICE_TITLE_TYPE_LABELS,
  type InvoiceDto,
} from '@dukang/shared-types';
import SubPageHeader from '../components/SubPageHeader';
import { request } from '../lib/api';

export default function InvoiceListPage() {
  const navigate = useNavigate();
  const [items, setItems] = useState<InvoiceDto[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    request<{ items: InvoiceDto[] }>('USER_H5', '/trade/invoices?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('/invoices/apply')}>
              申请发票
            </button>
          </div>
        ) : (
          <div className="after-sale-order-list">
            {items.map((inv) => (
              <div key={inv.id} className="after-sale-order-item after-sale-ticket-card">
                <div className="after-sale-ticket-head">
                  <span>
                    {INVOICE_TITLE_TYPE_LABELS[inv.titleType]} · {INVOICE_KIND_LABELS[inv.invoiceKind]}
                  </span>
                  <span className="after-sale-ticket-status">
                    {INVOICE_STATUS_LABELS[inv.status]}
                  </span>
                </div>
                <p className="after-sale-order-no">{inv.titleName}</p>
                <p className="after-sale-order-meta">
                  {inv.invoiceNo} · 订单 {inv.orderNo ?? inv.orderId}
                </p>
                {inv.status === 'ISSUED' && inv.fileUrl ? (
                  <a className="after-sale-file-link" href={inv.fileUrl} target="_blank" rel="noreferrer">
                    查看/下载发票
                  </a>
                ) : null}
              </div>
            ))}
            <button type="button" className="after-sale-primary" onClick={() => navigate('/invoices/apply')}>
              申请发票
            </button>
          </div>
        )}
      </main>
    </div>
  );
}
