/**
 * melk-county-agencies-panel.js — بنگاه شهرستان با بانک فرم استاندارد CRM
 */
import { renderFormSections, collectFormData, validateRequired } from './melk-form-renderer.js';

const STATUS_COLORS = {
    draft: '#94a3b8', submitted: '#3b82f6', under_review: '#8b5cf6',
    in_progress: '#f59e0b', resolved: '#22c55e', closed: '#64748b',
};
const PRIORITY_COLORS = {
    low: '#94a3b8', normal: '#3b82f6', high: '#f59e0b', urgent: '#ef4444',
};

export function renderCountyAgenciesPanel(esc, { canManage = false } = {}) {
    return `<div class="em-ext-panel" data-ref="countyPanel">
        <div class="em-ext-intro em-ext-intro--county">
            <div class="em-ext-intro__text">
                <h2>🏘️ بنگاه‌های شهرستان</h2>
                <p>انتخاب فرم استاندارد → تکمیل → پیگیری فرآیند و گزارش‌گیری</p>
            </div>
            <div class="em-ext-intro__flow">
                <span class="em-flow-step">📝 ثبت</span><span class="em-flow-arrow">→</span>
                <span class="em-flow-step">📤 ارسال</span><span class="em-flow-arrow">→</span>
                <span class="em-flow-step">🔍 بررسی</span><span class="em-flow-arrow">→</span>
                <span class="em-flow-step">✅ حل</span>
            </div>
            <div class="em-ext-kpis" data-ref="countyKpis"></div>
        </div>
        <div class="em-ext-toolbar">
            <select class="red-sel" data-ref="countyTypeFilter">
                <option value="">همه انواع</option>
                <option value="demand">تقاضا</option>
                <option value="property_buy">خرید ملک</option>
                <option value="property_search">جستجوی ملک</option>
                <option value="partnership">مشارکت</option>
                <option value="legal_issue">مسئله حقوقی</option>
                <option value="valuation">کارشناسی</option>
                <option value="problem">مشکل/چالش</option>
                <option value="other">سایر</option>
            </select>
            <select class="red-sel" data-ref="countyStatusFilter">
                <option value="">همه وضعیت‌ها</option>
                <option value="draft">پیش‌نویس</option>
                <option value="submitted">ارسال‌شده</option>
                <option value="under_review">در حال بررسی</option>
                <option value="in_progress">در دست اقدام</option>
                <option value="resolved">حل‌شده</option>
                <option value="closed">بسته</option>
            </select>
            ${canManage ? '' : '<button type="button" class="red-btn" data-ref="myCountyBtn">درخواست‌های من</button>'}
            <button type="button" class="red-btn red-btn--primary" data-ref="newCountyBtn">➕ درخواست جدید</button>
            <button type="button" class="red-btn" data-ref="reloadCountyBtn">↻</button>
        </div>

        <div class="em-listing-wizard" data-ref="countyWizard" style="display:none">
            <div class="em-wizard-steps">
                <span class="em-wiz-step em-wiz-step--active" data-cr-step="1">۱. انتخاب فرم</span>
                <span class="em-wiz-step" data-cr-step="2">۲. تکمیل اطلاعات</span>
                <span class="em-wiz-step" data-cr-step="3">۳. ارسال</span>
            </div>
            <div data-ref="crStepBank" class="em-wizard-pane">
                <h3>📚 بانک فرم‌های بنگاه شهرستان</h3>
                <p class="em-form-bank-hint">فرم مناسب نوع درخواست را انتخاب کنید — فیلدها برای گزارش‌گیری و مدیریت فرآیند استاندارد شده‌اند</p>
                <div class="em-form-bank-grid" data-ref="countyFormBankGrid"></div>
            </div>
            <div data-ref="crStepFill" class="em-wizard-pane" style="display:none">
                <div class="em-selected-form-head" data-ref="crSelectedHead"></div>
                <div data-ref="crDynamicFields"></div>
                <div class="em-ext-actions">
                    <button type="button" class="red-btn" data-ref="crBackBankBtn">← بازگشت</button>
                    <button type="button" class="red-btn red-btn--primary" data-ref="crToSubmitBtn">ادامه →</button>
                    <button type="button" class="red-btn" data-ref="cancelCountyBtn">انصراف</button>
                </div>
            </div>
            <div data-ref="crStepSubmit" class="em-wizard-pane" style="display:none">
                <div class="em-spec-review" data-ref="crReview"></div>
                <div class="em-ext-actions">
                    <button type="button" class="red-btn" data-ref="crBackFillBtn">← بازگشت</button>
                    <button type="button" class="red-btn" data-ref="saveCountyDraftBtn">💾 پیش‌نویس</button>
                    <button type="button" class="red-btn red-btn--primary" data-ref="saveCountySubmitBtn">📤 ارسال</button>
                </div>
            </div>
        </div>

        <div class="em-ext-list" data-ref="countyList"></div>
        <div class="em-listing-modal" data-ref="countyModal" style="display:none">
            <div class="em-listing-modal__box">
                <div class="em-listing-modal__head">
                    <h3 data-ref="countyModalTitle">فرم درخواست</h3>
                    <button type="button" class="em-listing-modal__close" data-ref="countyModalClose">✕</button>
                </div>
                <div class="em-listing-modal__body" data-ref="countyModalBody"></div>
            </div>
        </div>
    </div>`;
}

export async function bindCountyAgenciesPanel(root, { request, esc, toast, can }) {
    const $ = (n) => root.querySelector(`[data-ref="${n}"]`);
    const canManage = can('melk.manage') || can('melk.county.manage') || can('*');
    let mineOnly = !canManage;
    let formBank = [];
    let selectedConfig = null;
    let requestsCache = [];

    try {
        const bankRes = await request('GET', 'melk/county-form-bank');
        formBank = bankRes?.data ?? [];
    } catch { /* ignore */ }

    function statusBadge(item) {
        const color = STATUS_COLORS[item.status] || '#64748b';
        return `<span class="em-status" style="background:${color}">${esc(item.status_label)}</span>`;
    }

    function priorityBadge(item) {
        const color = PRIORITY_COLORS[item.priority] || '#64748b';
        return `<span class="em-badge" style="background:${color};color:#fff">${esc(item.priority_label)}</span>`;
    }

    function adminActions(item) {
        if (!canManage) return '';
        return `<div class="em-ext-card-actions" data-admin-id="${item.id}">
            <select class="red-sel em-status-sel" data-status-id="${item.id}">
                <option value="submitted" ${item.status === 'submitted' ? 'selected' : ''}>ارسال‌شده</option>
                <option value="under_review" ${item.status === 'under_review' ? 'selected' : ''}>در حال بررسی</option>
                <option value="in_progress" ${item.status === 'in_progress' ? 'selected' : ''}>در دست اقدام</option>
                <option value="resolved" ${item.status === 'resolved' ? 'selected' : ''}>حل‌شده</option>
                <option value="closed" ${item.status === 'closed' ? 'selected' : ''}>بسته</option>
            </select>
            <button type="button" class="red-btn red-btn--primary em-status-save" data-status-save="${item.id}">به‌روز وضعیت</button>
        </div>`;
    }

    function setCrStep(step) {
        root.querySelectorAll('[data-cr-step]').forEach(el => {
            el.classList.toggle('em-wiz-step--active', +el.dataset.crStep === step);
            el.classList.toggle('em-wiz-step--done', +el.dataset.crStep < step);
        });
        $('crStepBank').style.display = step === 1 ? '' : 'none';
        $('crStepFill').style.display = step === 2 ? '' : 'none';
        $('crStepSubmit').style.display = step === 3 ? '' : 'none';
    }

    function renderFormBank() {
        const grid = $('countyFormBankGrid');
        if (!grid) return;
        grid.innerHTML = formBank.length ? formBank.map(f => `
            <button type="button" class="em-form-bank-card" data-cr-form-key="${esc(f.form_key)}">
                <span class="em-form-bank-icon">${esc(f.icon || '📋')}</span>
                <strong>${esc(f.title)}</strong>
                <span class="em-form-bank-sub">${esc(f.subtitle || '')}</span>
                <span class="em-form-bank-std">${esc(f.standard || '')}</span>
            </button>
        `).join('') : '<div class="em-empty-inline">فرمی در بانک نیست</div>';
        grid.querySelectorAll('[data-cr-form-key]').forEach(btn => {
            btn.addEventListener('click', () => selectCountyForm(btn.dataset.crFormKey));
        });
    }

    async function selectCountyForm(formKey) {
        try {
            const res = await request('GET', `melk/county-form-config?form_key=${encodeURIComponent(formKey)}`);
            selectedConfig = res?.data;
            if (!selectedConfig) { toast('فرم یافت نشد', true); return; }
            $('crSelectedHead').innerHTML = `
                <div class="em-selected-form-badge">${esc(selectedConfig.icon || '📋')}</div>
                <div><strong>${esc(selectedConfig.title)}</strong>
                <span class="em-form-bank-sub">${esc(selectedConfig.subtitle || '')}</span></div>`;
            $('crDynamicFields').innerHTML = renderFormSections(selectedConfig.sections || [], esc);
            setCrStep(2);
        } catch (e) { toast(e.message, true); }
    }

    function showCountyModal(r) {
        $('countyModalTitle').textContent = `${r.form_template_icon || '📋'} ${r.form_template_title || r.request_type_label}`;
        const rows = (r.form_attachment || []).map(f =>
            `<div class="em-form-attach-row em-form-attach-row--full"><span>${esc(f.label)}</span><strong>${esc(f.value)}</strong></div>`
        ).join('');
        $('countyModalBody').innerHTML = `
            ${r.form_template_standard ? `<p class="em-form-attach-std">${esc(r.form_template_standard)}</p>` : ''}
            <div class="em-form-attach-sheet">${rows || '<p>بدون فرم پیوست</p>'}</div>
            <p class="em-form-attach-meta"><code dir="ltr">${esc(r.request_key)}</code></p>`;
        $('countyModal').style.display = '';
    }

    function requestCard(r) {
        const hasForm = r.form_template_key && (r.form_attachment?.length || Object.keys(r.form_data || {}).length);
        const formBadge = hasForm
            ? `<span class="em-badge em-badge--form">${esc(r.form_template_icon || '📋')} ${esc(r.form_template_title || '')}</span>` : '';
        const preview = (r.form_attachment || []).slice(0, 3).map(f =>
            `<div class="em-form-attach-row"><span>${esc(f.label)}</span><strong>${esc(f.value)}</strong></div>`
        ).join('');
        const viewBtn = hasForm
            ? `<button type="button" class="red-btn red-btn--sm em-view-cr-form" data-cr-id="${r.id}">📋 فرم درخواست</button>` : '';
        return `<div class="em-ext-card em-ext-card--county">
            <div class="em-ext-card-head">
                <strong>${esc(r.title)}</strong>
                <span class="em-badge">${esc(r.request_type_label)}</span>
                ${formBadge}
                ${priorityBadge(r)}
                ${statusBadge(r)}
            </div>
            <div class="em-ext-card-meta">
                <code dir="ltr">${esc(r.request_key)}</code> ·
                ${esc(r.county)}${r.city ? ' / ' + esc(r.city) : ''} ·
                ${esc(r.agency_name || r.created_by_name)}
            </div>
            <p class="em-ext-desc">${esc((r.description || '').slice(0, 200))}</p>
            ${preview ? `<div class="em-form-attach-preview">${preview}</div>` : ''}
            ${r.admin_note ? `<p class="em-ext-note">یادداشت مدیر: ${esc(r.admin_note)}</p>` : ''}
            <div class="em-ext-card-actions">${viewBtn}${adminActions(r)}</div>
        </div>`;
    }

    async function load() {
        const list = $('countyList');
        list.innerHTML = '<div class="em-empty-inline">...</div>';
        const qs = new URLSearchParams();
        if ($('countyTypeFilter')?.value) qs.set('request_type', $('countyTypeFilter').value);
        if ($('countyStatusFilter')?.value) qs.set('status', $('countyStatusFilter').value);
        if (mineOnly) qs.set('mine', '1');
        try {
            const items = (await request('GET', `melk/county-requests${qs.toString() ? '?' + qs : ''}`))?.data ?? [];
            requestsCache = items;
            const kpis = $('countyKpis');
            if (kpis) {
                const open = items.filter(i => !['resolved', 'closed'].includes(i.status)).length;
                const urgent = items.filter(i => i.priority === 'urgent').length;
                kpis.innerHTML = `
                    <div class="em-kpi"><strong>${items.length}</strong><span>کل درخواست</span></div>
                    <div class="em-kpi em-kpi--warn"><strong>${open}</strong><span>باز</span></div>
                    <div class="em-kpi em-kpi--urgent"><strong>${urgent}</strong><span>فوری</span></div>`;
            }
            list.innerHTML = items.length
                ? items.map(r => requestCard(r)).join('')
                : '<div class="em-empty-inline">درخواستی یافت نشد.</div>';

            list.querySelectorAll('.em-view-cr-form').forEach(btn => {
                btn.addEventListener('click', () => {
                    const r = requestsCache.find(x => x.id === +btn.dataset.crId);
                    if (r) showCountyModal(r);
                });
            });
            list.querySelectorAll('.em-status-save').forEach(btn => {
                btn.addEventListener('click', async () => {
                    const id = btn.dataset.statusSave;
                    const sel = list.querySelector(`[data-status-id="${id}"]`);
                    try {
                        await request('PUT', `melk/county-requests/${id}/status`, { status: sel?.value });
                        toast('وضعیت به‌روز شد');
                        load();
                    } catch (e) { toast(e.message, true); }
                });
            });
        } catch (e) {
            list.innerHTML = `<div class="em-empty-inline">${esc(e.message)}</div>`;
        }
    }

    function resetWizard() {
        selectedConfig = null;
        setCrStep(1);
        renderFormBank();
    }

    async function save(status) {
        if (!selectedConfig) { toast('فرم انتخاب نشده', true); return; }
        const formData = collectFormData($('crDynamicFields'));
        try {
            await request('POST', 'melk/county-requests', {
                form_template_key: selectedConfig.form_key,
                form_data: formData,
                request_type: selectedConfig.request_type,
                status,
            });
            $('countyWizard').style.display = 'none';
            resetWizard();
            toast(status === 'submitted' ? 'درخواست ارسال شد' : 'پیش‌نویس ذخیره شد');
            load();
        } catch (e) { toast(e.message, true); }
    }

    $('newCountyBtn')?.addEventListener('click', () => {
        resetWizard();
        $('countyWizard').style.display = '';
        $('countyWizard').scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
    $('cancelCountyBtn')?.addEventListener('click', () => { $('countyWizard').style.display = 'none'; resetWizard(); });
    $('crBackBankBtn')?.addEventListener('click', () => setCrStep(1));
    $('crBackFillBtn')?.addEventListener('click', () => setCrStep(2));
    $('crToSubmitBtn')?.addEventListener('click', () => {
        if (!selectedConfig) return;
        const missing = validateRequired($('crDynamicFields'), selectedConfig.sections || []);
        if (missing.length) { toast('فیلدهای الزامی: ' + missing.join('، '), true); return; }
        const data = collectFormData($('crDynamicFields'));
        $('crReview').innerHTML = `<h4>بررسی — ${esc(selectedConfig.title)}</h4>
            <div class="em-form-attach-preview">${Object.entries(data).filter(([,v]) => v).map(([k,v]) =>
                `<div class="em-form-attach-row"><span>${esc(k)}</span><strong>${esc(Array.isArray(v)?v.join('، '):String(v))}</strong></div>`
            ).join('')}</div>`;
        setCrStep(3);
    });
    $('saveCountyDraftBtn')?.addEventListener('click', () => save('draft'));
    $('saveCountySubmitBtn')?.addEventListener('click', () => save('submitted'));
    $('countyModalClose')?.addEventListener('click', () => { $('countyModal').style.display = 'none'; });
    $('countyModal')?.addEventListener('click', (e) => { if (e.target === $('countyModal')) $('countyModal').style.display = 'none'; });
    $('reloadCountyBtn')?.addEventListener('click', load);
    $('countyTypeFilter')?.addEventListener('change', load);
    $('countyStatusFilter')?.addEventListener('change', load);
    $('myCountyBtn')?.addEventListener('click', () => {
        mineOnly = !mineOnly;
        $('myCountyBtn').classList.toggle('red-btn--primary', mineOnly);
        load();
    });

    renderFormBank();
    await load();
}
