/**
 * ContractCalSection.js — برنامه پرداخت (همه قراردادها)
 * نمایش اقساط آینده + سررسیدگذشته
 */
import SectionBase from "../../accounting/SectionBase.js";

const TYPE_COLOR = {
    purchase:'#3b82f6', construction:'#f97316', sale:'#10b981',
    lease:'#8b5cf6',    consulting:'#6b7280',
};
const TYPE_LABEL = {
    purchase:'خرید ملک', construction:'پیمانکاری', sale:'فروش واحد',
    lease:'اجاره', consulting:'مشاوره',
};

export default class ContractCalSection extends SectionBase {

    async template() { return `<div data-ref="root"></div>`; }

    async afterRender() {
        await this._render();
    }

    async _render() {
        const root = this.ref('root');
        root.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get('/contracts/payments/upcoming');
            const payments = res?.data ?? [];
            this._renderPayments(root, payments);
        } catch {
            root.innerHTML = `<div class="acc-error">خطا در بارگذاری</div>`;
        }
    }

    _renderPayments(root, payments) {
        if (!payments.length) {
            root.innerHTML = `<div class="acc-empty" style="margin-top:40px;">هیچ قسط معوقی وجود ندارد ✅</div>`;
            return;
        }

        const today = new Date().toISOString().split('T')[0];
        const overdue   = payments.filter(p => p.due_date && p.due_date < today);
        const thisWeek  = payments.filter(p => {
            if (!p.due_date || p.due_date < today) return false;
            const diff = (new Date(p.due_date) - new Date(today)) / 86400000;
            return diff <= 7;
        });
        const upcoming = payments.filter(p => {
            if (!p.due_date || p.due_date < today) return false;
            const diff = (new Date(p.due_date) - new Date(today)) / 86400000;
            return diff > 7;
        });

        const totalOverdue  = overdue.reduce((s,p) => s+parseFloat(p.amount||0), 0);
        const totalThisWeek = thisWeek.reduce((s,p) => s+parseFloat(p.amount||0), 0);
        const totalUpcoming = upcoming.reduce((s,p) => s+parseFloat(p.amount||0), 0);

        const fmt = v => new Intl.NumberFormat('fa-IR').format(Math.round(v));

        const card = (p) => `
            <div class="contract-cal-item" style="border-right:3px solid ${TYPE_COLOR[p.contract_type]||'#94a3b8'}">
                <div class="contract-cal-item__meta">
                    <span class="contract-type-badge" style="background:${TYPE_COLOR[p.contract_type]||'#94a3b8'};font-size:10px;">
                        ${TYPE_LABEL[p.contract_type]||p.contract_type}
                    </span>
                    ${p.contract_number ? `<span style="font-size:11px;color:#94a3b8;">№ ${p.contract_number}</span>` : ''}
                    ${p.parcel_code ? `<span style="font-size:11px;color:#64748b;">📍 پلاک ${p.parcel_code}</span>` : ''}
                </div>
                <div class="contract-cal-item__title">${p.contract_title||'—'}</div>
                <div class="contract-cal-item__desc">${p.description||`قسط ${p.installment_no}`}</div>
                <div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px;">
                    <b style="font-size:15px;color:#1e293b;">${fmt(p.amount)} ریال</b>
                    <span style="font-size:11px;color:#64748b;">
                        📅 ${p.due_date}
                        ${p.days_until !== null ? (p.days_until < 0
                            ? `<span style="color:#ef4444;">(${Math.abs(p.days_until)} روز گذشته)</span>`
                            : `<span style="color:#64748b;">(${p.days_until} روز دیگر)</span>`)
                        : ''}
                    </span>
                </div>
            </div>`;

        const section = (title, color, items, total) => items.length ? `
            <div class="contract-cal-section">
                <div class="contract-cal-section__header" style="border-right:4px solid ${color};">
                    <span>${title}</span>
                    <span class="contract-cal-total">${fmt(total)} ریال — ${items.length} قسط</span>
                </div>
                ${items.map(card).join('')}
            </div>` : '';

        root.innerHTML = `
        <div style="max-width:700px;">
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:24px;">
                <div class="contract-kpi-card" style="border-top:3px solid #ef4444;">
                    <div class="contract-kpi-label">⚠️ سررسیدگذشته</div>
                    <div class="contract-kpi-value" style="color:#ef4444;">${fmt(totalOverdue)}</div>
                    <div class="contract-kpi-sub">${overdue.length} قسط — ریال</div>
                </div>
                <div class="contract-kpi-card" style="border-top:3px solid #f59e0b;">
                    <div class="contract-kpi-label">📅 این هفته</div>
                    <div class="contract-kpi-value" style="color:#d97706;">${fmt(totalThisWeek)}</div>
                    <div class="contract-kpi-sub">${thisWeek.length} قسط — ریال</div>
                </div>
                <div class="contract-kpi-card" style="border-top:3px solid #3b82f6;">
                    <div class="contract-kpi-label">🔜 آینده</div>
                    <div class="contract-kpi-value" style="color:#3b82f6;">${fmt(totalUpcoming)}</div>
                    <div class="contract-kpi-sub">${upcoming.length} قسط — ریال</div>
                </div>
            </div>
            ${section('⚠️ سررسیدگذشته — فوری', '#ef4444', overdue,   totalOverdue)}
            ${section('📅 این هفته',             '#f59e0b', thisWeek,  totalThisWeek)}
            ${section('🔜 اقساط آینده',           '#3b82f6', upcoming,  totalUpcoming)}
            ${!overdue.length && !thisWeek.length && !upcoming.length
                ? '<div class="acc-empty" style="margin-top:40px;">همه اقساط تسویه شده است ✅</div>' : ''}
        </div>`;
    }
}
