import Swal from 'sweetalert2';

export interface RepresentanteLegalOption {
    CodConCli: number;
    NomConCli?: string | null;
    NIFConCli?: string | null;
    CarConCli?: string | null;
    EsRepLeg?: boolean;
    label: string;
}

export interface CondicionesParticularesModalValues {
    comercial: string;
    canal: string;
    CodConCli: string;
}

function readStored(): { comercial: string; canal: string } {
    try {
        return {
            comercial: localStorage.getItem('eneon_comercial') || '0',
            canal: localStorage.getItem('eneon_canal') || '',
        };
    } catch {
        return { comercial: '0', canal: '' };
    }
}

function persist(comercial: string, canal: string): void {
    try {
        localStorage.setItem('eneon_comercial', comercial);
        localStorage.setItem('eneon_canal', canal);
    } catch {
        // localStorage no disponible
    }
}

function buildRepresentanteSelectHtml(representantes: RepresentanteLegalOption[]): string {
    const options = representantes
        .map((rep) => {
            const selected = rep.EsRepLeg ? ' selected' : '';
            return `<option value="${rep.CodConCli}"${selected}>${rep.label}</option>`;
        })
        .join('');

    return `
        <label for="swal-representante" class="swal2-label d-block text-start mb-1 mt-2">Representante legal</label>
        <select id="swal-representante" class="swal2-input" style="width:100%;padding:0.5rem;">
            <option value="">Seleccionar representante...</option>
            ${options}
        </select>
    `;
}

/**
 * Modal Canal + Comercial + Representante legal (TipProCom 1 y 2 — Condiciones Particulares).
 */
export async function promptCondicionesParticulares(
    representantesLegales: RepresentanteLegalOption[],
    defaults?: Partial<CondicionesParticularesModalValues>
): Promise<CondicionesParticularesModalValues | null> {
    const stored = readStored();
    const currentCanal = defaults?.canal ?? stored.canal;
    const currentComercial = defaults?.comercial ?? (stored.comercial || '0');
    const selectHtml = buildRepresentanteSelectHtml(representantesLegales);

    const result = await Swal.fire({
        title: 'Indica Canal y Comercial',
        html:
            `<input id="swal-canal" class="swal2-input" placeholder="Canal" value="${currentCanal}">` +
            `<input id="swal-comercial" class="swal2-input" placeholder="Comercial" value="${currentComercial}">` +
            selectHtml,
        focusConfirm: false,
        showCancelButton: true,
        confirmButtonText: 'Guardar y continuar',
        width: 520,
        preConfirm: () => {
            const c = (document.getElementById('swal-comercial') as HTMLInputElement)?.value ?? '0';
            const ca = (document.getElementById('swal-canal') as HTMLInputElement)?.value ?? '';
            const codConCli = (document.getElementById('swal-representante') as HTMLSelectElement)?.value ?? '';

            if (!ca.trim()) {
                Swal.showValidationMessage('El canal es obligatorio');
                return null;
            }

            if (representantesLegales.length > 0 && !codConCli.trim()) {
                Swal.showValidationMessage('Debe seleccionar un representante legal');
                return null;
            }

            return {
                comercial: (c.trim() || '0'),
                canal: ca.trim(),
                CodConCli: codConCli.trim(),
            };
        },
    });

    if (result.isConfirmed && result.value) {
        const values = result.value as CondicionesParticularesModalValues;
        persist(values.comercial, values.canal);
        return values;
    }

    return null;
}
