import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import type { PartnerBillDto } from '@dukang/shared-types';
import { isLoggedIn, request } from '../lib/api';

type StatusFilter = 'all' | 'pending' | 'settled' | 'reviewing';

function fmtMoney(n: number) {
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function billStatusLabel(status: string) {
  switch (status) {
    case 'DRAFT': return '待结算';
    case 'CONFIRMED': return '审核中';
    case 'PAID': return '已结算';
    default: return status;
  }
}

function billStatusClass(status: string) {
  switch (status) {
    case 'DRAFT': return 'partner-settlement-status--pending';
    case 'CONFIRMED': return 'partner-settlement-status--reviewing';
    case 'PAID': return 'partner-settlement-status--settled';
    default: return '';
  }
}

function billPeriodLabel(periodStart: string) {
  const d = new Date(periodStart);
  if (Number.isNaN(d.getTime())) return '—';
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}

function billMonthLabel(year: number, month: number) {
  return `${year}年${month}月`;
}

export default function SettlementPage() {
  const navigate = useNavigate();
  const [bills, setBills] = useState<PartnerBillDto[]>([]);
  const now = new Date();
  const [month, setMonth] = useState({ year: now.getFullYear(), month: now.getMonth() + 1 });
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');

  useEffect(() => {
    if (!isLoggedIn()) { navigate('/login'); return; }
    request<PartnerBillDto[]>('PARTNER_H5', '/partner/settlement/bills').then(setBills);
  }, [navigate]);

  const summary = useMemo(() => {
    const pending = bills.filter((b) => b.status === 'DRAFT');
    const settled = bills.filter((b) => b.status === 'PAID');
    const currentMonth = bills.filter((b) => {
      const d = new Date(b.periodStart);
      return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth();
    });
    return {
      pendingTotal: pending.reduce((s, b) => s + Number(b.totalAmount || 0), 0),
      settledTotal: settled.reduce((s, b) => s + Number(b.totalAmount || 0), 0),
      monthEstimate: currentMonth.reduce((s, b) => s + Number(b.totalAmount || 0), 0),
    };
  }, [bills, now]);

  const filteredBills = useMemo(() => {
    return bills.filter((b) => {
      const d = new Date(b.periodStart);
      const matchMonth = d.getFullYear() === month.year && d.getMonth() + 1 === month.month;
      if (!matchMonth) return false;
      if (statusFilter === 'all') return true;
      if (statusFilter === 'pending') return b.status === 'DRAFT';
      if (statusFilter === 'settled') return b.status === 'PAID';
      if (statusFilter === 'reviewing') return b.status === 'CONFIRMED';
      return true;
    });
  }, [bills, month, statusFilter]);

  const monthOptions = useMemo(() => {
    const opts: Array<{ year: number; month: number }> = [];
    for (let i = 0; i < 6; i++) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      opts.push({ year: d.getFullYear(), month: d.getMonth() + 1 });
    }
    return opts;
  }, [now]);

  function openBill(bill: PartnerBillDto) {
    navigate(bill.id ? `/center/bills?id=${bill.id}` : '/center/bills');
  }

  const statusTabs: Array<{ key: StatusFilter; label: string }> = [
    { key: 'all', label: '全部' },
    { key: 'pending', label: '待结算' },
    { key: 'settled', label: '已结算' },
    { key: 'reviewing', label: '审核中' },
  ];

  return (
    <div className="page-no-tab partner-settlement-page">
      <PageHeader title="财务对账中心" onBack={() => navigate('/')} />

      <main className="partner-settlement-body">
        <section className="partner-settlement-summary">
          <div className="partner-settlement-summary-deco" aria-hidden>
            <span className="material-symbols-outlined">account_balance_wallet</span>
          </div>
          <p className="partner-settlement-summary-label">待结算总额</p>
          <div className="partner-settlement-summary-amount">
            <span className="partner-settlement-currency">¥</span>
            {fmtMoney(summary.pendingTotal)}
          </div>
          <div className="partner-settlement-summary-grid">
            <div>
              <p className="partner-settlement-summary-sub">累计已结算</p>
              <p className="partner-settlement-summary-value">¥{fmtMoney(summary.settledTotal)}</p>
            </div>
            <div className="partner-settlement-summary-divider" />
            <div>
              <p className="partner-settlement-summary-sub">本月预估收益</p>
              <p className="partner-settlement-summary-value partner-settlement-summary-value--accent">
                ¥{fmtMoney(summary.monthEstimate)}
              </p>
            </div>
          </div>
        </section>

        <section className="partner-settlement-filters">
          <select
            className="partner-settlement-month"
            value={`${month.year}-${month.month}`}
            onChange={(e) => {
              const [y, m] = e.target.value.split('-').map(Number);
              setMonth({ year: y, month: m });
            }}
          >
            {monthOptions.map((opt) => (
              <option key={`${opt.year}-${opt.month}`} value={`${opt.year}-${opt.month}`}>
                {billMonthLabel(opt.year, opt.month)}
              </option>
            ))}
          </select>
          <button type="button" className="partner-settlement-status-btn">
            <span className="material-symbols-outlined">filter_list</span>
            状态
          </button>
        </section>

        <div className="partner-settlement-chips">
          {statusTabs.map((tab) => (
            <button
              key={tab.key}
              type="button"
              className={`partner-settlement-chip${statusFilter === tab.key ? ' partner-settlement-chip--active' : ''}`}
              onClick={() => setStatusFilter(tab.key)}
            >
              {tab.label}
            </button>
          ))}
        </div>

        <section className="partner-settlement-list-section">
          <h3 className="partner-settlement-list-title">对账明细记录</h3>

          {filteredBills.length === 0 && (
            <div className="empty" style={{ padding: '32px 0' }}>暂无对账记录</div>
          )}

          <div className="partner-settlement-list">
            {filteredBills.map((bill) => (
              <button
                key={bill.id}
                type="button"
                className="partner-settlement-item"
                onClick={() => openBill(bill)}
              >
                <div className="partner-settlement-item-main">
                  <div className="partner-settlement-item-head">
                    <span className="partner-settlement-item-no">{bill.billNo}</span>
                    <span className={`partner-settlement-status ${billStatusClass(bill.status)}`}>
                      {billStatusLabel(bill.status)}
                    </span>
                  </div>
                  <p className="partner-settlement-item-meta">
                    <span className="material-symbols-outlined">event</span>
                    {billPeriodLabel(bill.periodStart)}
                    <span className="partner-settlement-dot" />
                    订单分佣 ¥{fmtMoney(Number(bill.orderCommission || 0))}
                  </p>
                  <p className={`partner-settlement-item-amount${bill.status === 'DRAFT' ? ' text-primary' : ''}`}>
                    ¥{fmtMoney(Number(bill.totalAmount || 0))}
                  </p>
                </div>
                <span className="material-symbols-outlined text-muted">chevron_right</span>
              </button>
            ))}
          </div>

          {filteredBills.length > 0 && (
            <p className="partner-settlement-footer-note">已展示全部记录</p>
          )}
        </section>
      </main>
    </div>
  );
}
