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

export default function BillsPage() {
  const navigate = useNavigate();
  const [bills, setBills] = useState<Array<Record<string, unknown>>>([]);
  const [confirmed, setConfirmed] = useState(false);
  const [submitting, setSubmitting] = useState(false);

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

  const bill = bills[0];

  function confirmBill() {
    if (!confirmed) return;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      alert('申请已提交，请耐心等待打款审核。（preV1 演示）');
    }, 1500);
  }

  return (
    <div className="partner-bills-page">
      <PageHeader title="待确认账单" onBack={() => navigate('/center')} />

      <div className="partner-bill-stepper">
        <div className="partner-stepper-inner">
          <div className="partner-stepper-line" aria-hidden>
            <div className="partner-stepper-line-fill" style={{ width: '50%' }} />
          </div>
          <div className="partner-step">
            <div className="partner-step-circle partner-step-circle--sm partner-step-circle--done">
              <span className="material-symbols-outlined" style={{ fontSize: 14, fontVariationSettings: "'FILL' 1" }}>check</span>
            </div>
            <span className="partner-step-label partner-step-label--active">数据核算</span>
          </div>
          <div className="partner-step">
            <div className="partner-step-circle partner-step-circle--sm partner-step-circle--active">2</div>
            <span className="partner-step-label partner-step-label--active">账单确认</span>
          </div>
          <div className="partner-step">
            <div className="partner-step-circle partner-step-circle--sm">3</div>
            <span className="partner-step-label">申请打款</span>
          </div>
        </div>
      </div>

      {!bill && <div className="empty">暂无账单</div>}

      {bill && (
        <section className="partner-bill-card">
          <div className="partner-bill-card-bar" />
          <div style={{ padding: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
              <div>
                <p className="label-md text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>SETTLEMENT PERIOD</p>
                <h2 className="headline-lg" style={{ fontSize: 20 }}>{String(bill.billNo || '月度结算账单')}</h2>
              </div>
              <span className="partner-status-pill partner-status-pill--paused">{String(bill.status || '待确认')}</span>
            </div>

            <div className="partner-bill-amount">
              <p className="text-muted body-md" style={{ marginBottom: 8 }}>应结总金额</p>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 4 }}>
                <span className="text-primary" style={{ fontWeight: 700, fontSize: 20 }}>¥</span>
                <span className="amount-xl">{Number(bill.totalAmount || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}</span>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div className="partner-info-row">
                <span className="text-variant body-md">订单分佣收入</span>
                <span className="body-md" style={{ fontWeight: 700 }}>¥ {(Number(bill.totalAmount || 0) * 0.82).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}</span>
              </div>
              <div className="partner-info-row">
                <span className="text-variant body-md">核销权益分佣</span>
                <span className="body-md" style={{ fontWeight: 700 }}>¥ {(Number(bill.totalAmount || 0) * 0.18).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}</span>
              </div>
            </div>
          </div>
        </section>
      )}

      {bills.length > 1 && (
        <div style={{ padding: '0 20px' }}>
          <h3 className="headline-md" style={{ marginBottom: 12 }}>历史账单</h3>
          {bills.slice(1).map((b) => (
            <div key={String(b.id)} className="partner-store-card" style={{ margin: '0 0 12px' }}>
              <div className="partner-store-card-header" style={{ marginBottom: 0 }}>
                <div>
                  <p className="body-md">{String(b.billNo)}</p>
                  <p className="label-md text-muted">{String(b.status)}</p>
                </div>
                <span className="amount-lg" style={{ fontSize: 18 }}>¥{Number(b.totalAmount).toFixed(2)}</span>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="partner-info-banner" style={{ marginTop: 16 }}>
        <span className="material-symbols-outlined text-primary" style={{ fontVariationSettings: "'FILL' 1" }}>info</span>
        <p className="body-md text-variant" style={{ lineHeight: 1.5 }}>
          账单确认后将正式进入打款流程。如有异议，请在确认前联系城市运营经理核实数据。
        </p>
      </div>

      {bill && (
        <footer className="partner-bill-footer">
          <label className="partner-checkbox-row" style={{ marginBottom: 16 }}>
            <input type="checkbox" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} />
            <span>我已核对数据无误，同意根据此账单进行结算</span>
          </label>
          <button
            type="button"
            className="partner-btn-primary"
            disabled={!confirmed || submitting}
            style={{ opacity: confirmed ? 1 : 0.5 }}
            onClick={confirmBill}
          >
            {submitting ? '正在提交...' : '确认并申请打款'}
            {!submitting && <span className="material-symbols-outlined">payments</span>}
          </button>
        </footer>
      )}
    </div>
  );
}
