/** Export invoice types that affect item visibility (tipo factura for operation_type === exp). */
export type ExportInvoiceType = 'NODES' | 'AFIJO' | 'DONAC' | 'SCRAP';

export interface InvoiceItemVisibility {
	showCrTrackingHeader: boolean;
	showEighthRule: boolean;
	showFdaFcc: boolean;
	showCertificateOfOrigin: boolean;
	showIdentifiersTab: boolean;
	/** Show block: Genera Descarga? + Tipo Importación + Tipo Búsqueda + Factura de Impo + Línea (expo, or import CR). */
	showExportLinkToImportBlock: boolean;
	/** Show Met Valor, Valor Det., Motivo De Uso in Continuación tab (expo). */
	showExportValuationFields: boolean;
	/** Show Met Valor, Valor Det., Motivo De Uso for import (e.g. Cambio de Régimen). */
	showValuationFields: boolean;
	/** Show block: Genera Descarga? + Factura de Expo + Línea de Expo (importación reparación, REP). */
	showRepairLinkToExportBlock: boolean;
	/** Continuación tab: TAX PAID + Forma Pago. */
	showContinuationTaxPayment: boolean;
	/** Continuación tab: IGI Amount + IGI Payment Method. */
	showContinuationIgi: boolean;
	/** Continuación tab: Machinery and equipment location. */
	showContinuationLocation: boolean;
	/** Continuación tab: Military Equipment checkbox. */
	showContinuationMilitary: boolean;
	/** Continuación tab: Own Equipment + Omit Annex 31. */
	showContinuationOwnOmitAnnex: boolean;
	/** Continuación tab: Lot + Entry No. */
	showContinuationLotEntry: boolean;
	/** Continuación tab: Consider in A31. */
	showContinuationConsiderA31: boolean;
	/** Continuación tab: Extra Description in Spanish. */
	showContinuationExtraDescription: boolean;
	/** Etiquetado tab: Quantity, Valuation, Assets Table. */
	showLabelingEnhanced: boolean;
	/** Identificadores tab: Special Assets table for MEX. */
	showMexicanIdEnhanced: boolean;
	/** Etiquetado tab visibility. */
	showLabelingTab: boolean;
	/** Etiquetado tab: Usage Reason field. */
	showUsageReason: boolean;
	/** Etiquetado tab: Standard fields (Label No, Type, Observations). */
	showLabelingStandard: boolean;
	/** Etiquetado tab: Quantity field. */
	showLabelingQuantity: boolean;
	/** Etiquetado tab: Observations field. */
	showLabelingObservations: boolean;
	/** Etiquetado tab: Valuation field (Valor Det). */
	showLabelingValuationValue: boolean;
	/** Etiquetado tab: Valuation Method selector. */
	showLabelingValuationMethod: boolean;
	/** Etiquetado tab: Whole left section (Legend + all fields). */
	showLabelingLeftSection: boolean;
}

const defaultVisibility: InvoiceItemVisibility = {
	showCrTrackingHeader: true,
	showEighthRule: true,
	showFdaFcc: true,
	showCertificateOfOrigin: true,
	showIdentifiersTab: true,
	showExportLinkToImportBlock: false,
	showExportValuationFields: false,
	showValuationFields: false,
	showRepairLinkToExportBlock: false,
	showContinuationTaxPayment: true,
	showContinuationIgi: true,
	showContinuationLocation: true,
	showContinuationMilitary: true,
	showContinuationOwnOmitAnnex: true,
	showContinuationLotEntry: true,
	showContinuationConsiderA31: true,
	showContinuationExtraDescription: true,
	showLabelingEnhanced: false,
	showMexicanIdEnhanced: false,
	showLabelingTab: true,
	showUsageReason: false,
	showLabelingStandard: true,
	showLabelingQuantity: false,
	showLabelingObservations: true,
	showLabelingValuationValue: false,
	showLabelingValuationMethod: true,
	showLabelingLeftSection: true
};

function normalizeInvoiceType(invoiceType?: string | null): string {
	return String(invoiceType || '')
		.trim()
		.toUpperCase();
}

function normalizeOperationType(operationType?: string | number | null): 'imp' | 'exp' | null {
	if (operationType === null || operationType === undefined || operationType === '') {
		return null;
	}

	if (typeof operationType === 'number') {
		if (operationType === 1) return 'exp';
		if (operationType === 2) return 'imp';
	}

	const normalized = String(operationType)
		.trim()
		.toLowerCase();

	if (normalized === '1' || normalized === 'exp' || normalized === 'export' || normalized === 'exportacion') {
		return 'exp';
	}

	if (normalized === '2' || normalized === 'imp' || normalized === 'import' || normalized === 'importacion') {
		return 'imp';
	}

	return null;
}

const EXPORT_INVOICE_TYPES: ExportInvoiceType[] = ['NODES', 'AFIJO', 'DONAC', 'SCRAP'];

function normalizeExportInvoiceType(exportInvoiceType?: string | null): ExportInvoiceType {
	const normalized = String(exportInvoiceType || '')
		.trim()
		.toUpperCase();
	if (EXPORT_INVOICE_TYPES.includes(normalized as ExportInvoiceType)) {
		return normalized as ExportInvoiceType;
	}
	return 'AFIJO';
}

export function getVisibility(
	invoiceType?: string | null,
	operationType?: string | number | null
): InvoiceItemVisibility {
	if (normalizeOperationType(operationType) === 'exp') {
		const exportType = normalizeExportInvoiceType(invoiceType);
		// Base visibility for export: existing flags stay true; export-only flags set by type.
		const expVisibility: InvoiceItemVisibility = {
			...defaultVisibility,
			showExportLinkToImportBlock: true,
			showExportValuationFields: true,
			showLabelingEnhanced: true,
			showUsageReason: true,
			showLabelingValuationValue: true,
			showLabelingStandard: false,
			showLabelingObservations: false,
			showLabelingQuantity: false
		};

		// CHECK FOR EXPORT REPAIR (REP / REPAR)
		const upInvoiceType = normalizeInvoiceType(invoiceType);
		if (upInvoiceType === 'REP' || upInvoiceType === 'REPAR') {
			return {
				...expVisibility,
				showLabelingValuationMethod: false,
				showLabelingValuationValue: false,
				showUsageReason: false,
				showLabelingLeftSection: false
			};
		}

		// Per-type overrides can be added here (e.g. hide valuation for SCRAP).
		switch (exportType) {
			case 'NODES':
			case 'AFIJO':
			case 'DONAC':
			case 'SCRAP':
				return expVisibility;
			default:
				return expVisibility;
		}
	}

	switch (normalizeInvoiceType(invoiceType)) {
		case 'TEM':
		case 'DEF':
			return {
				...defaultVisibility,
				showCrTrackingHeader: false,
				showFdaFcc: false,
				showLabelingEnhanced: true,
				showLabelingQuantity: true,
				showLabelingObservations: true,
				showLabelingValuationValue: true
			};

		case 'CR':
			return {
				...defaultVisibility,
				showEighthRule: false,
				showIdentifiersTab: true,
				showValuationFields: true,
				showUsageReason: true,
				showLabelingEnhanced: true,
				showLabelingQuantity: false,
				showLabelingStandard: false,
				showLabelingObservations: false
			};

		case 'REP':
		case 'REPAR':
			// Continuación: solo campos de la captura (sin Valoración, FDA/FCC, Regla Octava, Own/Omit, Lote/Entrada, Consider A31)
			return {
				...defaultVisibility,
				showCrTrackingHeader: false,
				showRepairLinkToExportBlock: true,
				showValuationFields: false,
				showFdaFcc: false,
				showCertificateOfOrigin: true,
				showEighthRule: false,
				showContinuationTaxPayment: true,
				showContinuationIgi: true,
				showContinuationLocation: true,
				showContinuationMilitary: true,
				showContinuationOwnOmitAnnex: false,
				showContinuationLotEntry: false,
				showContinuationConsiderA31: false,
				showContinuationExtraDescription: true,
				showLabelingEnhanced: true,
				showLabelingQuantity: true,
				showLabelingStandard: true,
				showLabelingObservations: false,
				showLabelingValuationValue: false,
				showLabelingValuationMethod: true
			};

		case 'MEX':
			// Compras Mexicanas: lo esencial + localización (como otros tipos); sin IGI, militar, A31, Own/Omit
			return {
				...defaultVisibility,
				showCrTrackingHeader: false,
				showEighthRule: false,
				showFdaFcc: false,
				showCertificateOfOrigin: false,
				showIdentifiersTab: true,
				showMexicanIdEnhanced: true,
				showLabelingTab: false,
				showContinuationIgi: false,
				showContinuationLocation: true,
				showContinuationMilitary: false,
				showContinuationOwnOmitAnnex: false,
				showContinuationConsiderA31: false
			};

		default:
			return defaultVisibility;
	}
}

export function isExportOperation(operationType?: string | number | null): boolean {
	return normalizeOperationType(operationType) === 'exp';
}