frappe.ui.form.on("Tax Period Closing Settings", {
	refresh(frm) {
		frm.trigger("render_detection_status");
		frm.trigger("render_regime_explanation");
		frm.trigger("setup_buttons");
	},

	setup_buttons(frm) {
		// Auto-detect button — always available
		if (frm.doc.company) {
			frm.add_custom_button(__("Auto-detect from Company"), () => {
				frm.set_value("auto_detect_on_save", 1);
				frm.save();
			}, __("Setup"));

			frm.add_custom_button(__("Auto-detect Accounts"), () => {
				frm.trigger("detect_accounts");
			}, __("Setup"));
		}

		// Load defaults buttons
		frm.add_custom_button(__("Load Default AZ Rates"), () => {
			frm.trigger("load_default_rates");
		}, __("Setup"));

		frm.add_custom_button(__("Load Default Account Map"), () => {
			if (!frm.doc.company) {
				frappe.msgprint(__("Please select a Company first."));
				return;
			}
			frm.trigger("detect_accounts_and_map");
		}, __("Setup"));
	},

	company(frm) {
		if (frm.doc.company && frm.doc.auto_detect_on_save) {
			frappe.show_alert({
				message: __("Company changed. Save to run auto-detection."),
				indicator: "blue"
			});
		}
		frm.trigger("render_detection_status");
	},

	default_tax_regime(frm) {
		frm.trigger("render_regime_explanation");
		frm.trigger("sync_regime_enables");
	},

	// ── Sync regime with enables ──────────────────────────

	sync_regime_enables(frm) {
		const regime = frm.doc.default_tax_regime;
		if (regime === "General (VAT + Profit)") {
			frm.set_value("enable_vat", 1);
			frm.set_value("enable_profit_tax", 1);
			frm.set_value("enable_simplified_tax", 0);
		} else if (regime === "Simplified Tax" || regime === "Special Regime") {
			frm.set_value("enable_vat", 0);
			frm.set_value("enable_profit_tax", 0);
			frm.set_value("enable_simplified_tax", 1);
		}
	},

	// ── Contradiction warnings in real-time ───────────────

	enable_vat(frm) {
		if (frm.doc.enable_vat && frm.doc.default_tax_regime !== "General (VAT + Profit)") {
			frappe.show_alert({
				message: __("VAT is typically not applicable in Simplified/Special regime."),
				indicator: "orange"
			});
		}
	},

	enable_profit_tax(frm) {
		if (frm.doc.enable_profit_tax && frm.doc.default_tax_regime !== "General (VAT + Profit)") {
			frappe.show_alert({
				message: __("Profit Tax is replaced by Simplified Tax in non-General regimes."),
				indicator: "orange"
			});
		}
	},

	enable_simplified_tax(frm) {
		if (frm.doc.enable_simplified_tax && frm.doc.default_tax_regime === "General (VAT + Profit)") {
			frappe.show_alert({
				message: __("Simplified Tax is not applicable in General (VAT + Profit) regime."),
				indicator: "orange"
			});
		}
	},

	auto_submit_entries(frm) {
		if (frm.doc.auto_submit_entries) {
			frappe.confirm(
				__("Auto-submit means journal entries will be posted immediately and will affect account balances. Submitted entries require cancellation to undo. Are you sure?"),
				() => {},
				() => { frm.set_value("auto_submit_entries", 0); }
			);
		}
	},

	enable_period_closing(frm) {
		if (frm.doc.enable_period_closing && frm.doc.auto_submit_entries) {
			frappe.show_alert({
				message: __("Warning: Both auto-submit and period closing are ON. Period Closing Voucher is irreversible once submitted."),
				indicator: "red"
			});
		}
	},

	vat_input_account(frm) {
		if (frm.doc.vat_input_account && frm.doc.vat_output_account
			&& frm.doc.vat_input_account === frm.doc.vat_output_account) {
			frappe.show_alert({
				message: __("VAT Input and Output accounts must be different!"),
				indicator: "red"
			});
			frm.set_value("vat_input_account", "");
		}
	},

	vat_output_account(frm) {
		if (frm.doc.vat_input_account && frm.doc.vat_output_account
			&& frm.doc.vat_input_account === frm.doc.vat_output_account) {
			frappe.show_alert({
				message: __("VAT Input and Output accounts must be different!"),
				indicator: "red"
			});
			frm.set_value("vat_output_account", "");
		}
	},

	profit_tax_advance_method(frm) {
		if (frm.doc.profit_tax_advance_method === "1/4 of Previous Year Tax"
			&& !frm.doc.profit_tax_previous_year_amount) {
			frappe.show_alert({
				message: __("Please enter the previous year's total profit tax amount below."),
				indicator: "orange"
			});
		}
	},

	// ── Regime Explanation HTML ────────────────────────────

	render_regime_explanation(frm) {
		const regime = frm.doc.default_tax_regime || "";
		let html = "";

		const explanations = {
			"General (VAT + Profit)": {
				color: "#28a745",
				icon: "📊",
				taxes: [
					__("VAT (ƏDV) — 18%, monthly, declaration by 20th of next month"),
					__("Profit Tax (Mənfəət) — 20%, annual declaration (Mar 31), quarterly advances"),
					__("Property Tax (Əmlak) — 1%, annual declaration, quarterly advances"),
				],
				note: __("Most common regime for medium/large businesses with VAT registration.")
			},
			"Simplified Tax": {
				color: "#17a2b8",
				icon: "📋",
				taxes: [
					__("Simplified Tax — 2%/4%/8% of revenue, quarterly"),
					__("Property Tax (Əmlak) — 1%, annual declaration, quarterly advances"),
				],
				note: __("For micro/small businesses WITHOUT VAT registration. Replaces VAT + Profit Tax.")
			},
			"Special Regime": {
				color: "#6f42c1",
				icon: "🏗",
				taxes: [
					__("Special Simplified Tax — rates vary by activity type"),
					__("Property Tax (Əmlak) — 1%, annual declaration, quarterly advances"),
				],
				note: __("For construction, real estate, housing, cash withdrawals. Uses special declaration forms.")
			}
		};

		const info = explanations[regime];
		if (info) {
			html = `
				<div style="padding: 12px; border-left: 4px solid ${info.color}; background: #f8f9fa; border-radius: 4px; margin-bottom: 10px;">
					<div style="font-weight: bold; color: ${info.color}; margin-bottom: 8px;">
						${info.icon} ${regime}
					</div>
					<div style="font-size: 12px; margin-bottom: 8px;">
						<strong>${__("Applicable taxes:")}</strong><br>
						${info.taxes.map(t => `&nbsp;&nbsp;• ${t}`).join("<br>")}
					</div>
					<div style="font-size: 11px; color: #666; font-style: italic;">
						${info.note}
					</div>
				</div>
			`;
		}

		if (frm.fields_dict.regime_explanation_html) {
			frm.fields_dict.regime_explanation_html.$wrapper.html(html);
		}
	},

	// ── Detection Status HTML ─────────────────────────────

	render_detection_status(frm) {
		if (!frm.doc.company) {
			if (frm.fields_dict.detection_status_html) {
				frm.fields_dict.detection_status_html.$wrapper.html(
					`<div style="padding: 10px; color: #999; font-size: 12px;">${__("Select a Company to enable auto-detection.")}</div>`
				);
			}
			return;
		}

		const checks = [
			{
				label: __("Company"),
				ok: !!frm.doc.company,
				value: frm.doc.company || __("Not set")
			},
			{
				label: __("Tax Regime"),
				ok: !!frm.doc.default_tax_regime,
				value: frm.doc.default_tax_regime || __("Not detected")
			},
			{
				label: __("VAT Accounts"),
				ok: frm.doc.default_tax_regime !== "General (VAT + Profit)" || (!!frm.doc.vat_input_account && !!frm.doc.vat_output_account),
				value: frm.doc.vat_input_account && frm.doc.vat_output_account
					? `${frm.doc.vat_input_account} / ${frm.doc.vat_output_account}`
					: (frm.doc.default_tax_regime !== "General (VAT + Profit)" ? __("N/A (Simplified)") : __("Not set"))
			},
			{
				label: __("Account Mapping"),
				ok: (frm.doc.account_map || []).length > 0,
				value: __("{0} mappings", [(frm.doc.account_map || []).length])
			},
			{
				label: __("Tax Rates"),
				ok: (frm.doc.tax_rates || []).length > 0,
				value: __("{0} rates", [(frm.doc.tax_rates || []).length])
			},
			{
				label: __("Cost Center"),
				ok: !!frm.doc.default_cost_center,
				value: frm.doc.default_cost_center || __("Will use company default")
			}
		];

		let html = '<div style="display: flex; flex-wrap: wrap; gap: 6px; padding: 5px 0;">';
		for (const c of checks) {
			const color = c.ok ? "#28a745" : "#dc3545";
			const bg = c.ok ? "#d4edda" : "#f8d7da";
			const icon = c.ok ? "✓" : "✗";
			html += `
				<div style="background: ${bg}; border: 1px solid ${color}; border-radius: 4px; padding: 4px 8px; font-size: 11px;" title="${c.value}">
					<span style="color: ${color}; font-weight: bold;">${icon}</span> ${c.label}
				</div>
			`;
		}
		html += '</div>';

		if (frm.fields_dict.detection_status_html) {
			frm.fields_dict.detection_status_html.$wrapper.html(html);
		}
	},

	// ── Detect Accounts ───────────────────────────────────

	detect_accounts(frm) {
		frappe.call({
			method: "taxes_az.taxes_az.doctype.tax_period_closing_settings.tax_period_closing_settings.auto_detect_accounts",
			args: { company: frm.doc.company },
			callback(r) {
				if (!r.message || !r.message.accounts) return;

				const accounts = r.message.accounts;
				let found = [];

				if (accounts["226"]) {
					frm.set_value("vat_input_account", accounts["226"].name);
					found.push(`VAT Input → ${accounts["226"].name}`);
				}
				if (accounts["521.3"]) {
					frm.set_value("vat_output_account", accounts["521.3"].name);
					found.push(`VAT Output → ${accounts["521.3"].name}`);
				}
				if (accounts["341"]) {
					frm.set_value("closing_account", accounts["341"].name);
					found.push(`Closing Account → ${accounts["341"].name}`);
				}

				if (found.length) {
					frappe.show_alert({
						message: __("Found {0} accounts", [found.length]),
						indicator: "green"
					});
				} else {
					frappe.show_alert({
						message: __("No standard AZ accounts found. Set up manually."),
						indicator: "orange"
					});
				}

				frm.trigger("render_detection_status");
			}
		});
	},

	detect_accounts_and_map(frm) {
		frappe.call({
			method: "taxes_az.taxes_az.doctype.tax_period_closing_settings.tax_period_closing_settings.auto_detect_accounts",
			args: { company: frm.doc.company },
			callback(r) {
				if (!r.message || !r.message.accounts) return;
				const accounts = r.message.accounts;

				// Set individual account fields
				if (accounts["226"]) frm.set_value("vat_input_account", accounts["226"].name);
				if (accounts["521.3"]) frm.set_value("vat_output_account", accounts["521.3"].name);
				if (accounts["341"]) frm.set_value("closing_account", accounts["341"].name);

				// Build account mapping table
				const map_defs = [
					{ tax_type: "Profit Tax (Mənfəət)", debit: "901", credit: "521.1" },
					{ tax_type: "Simplified Tax (Sadələşdirilmiş)", debit: "731", credit: "521.9" },
					{ tax_type: "Property Tax (Əmlak)", debit: "731", credit: "521.5" },
					{ tax_type: "Land Tax (Torpaq)", debit: "731", credit: "521.6" },
					{ tax_type: "Excise Tax (Aksiz)", debit: "731", credit: "521.4" },
					{ tax_type: "Mining Tax (Mədən)", debit: "731", credit: "521.8" },
					{ tax_type: "Road Tax (Yol)", debit: "731", credit: "521.7" },
				];

				frm.doc.account_map = [];
				let mapped = 0;

				for (const def of map_defs) {
					const debit_acc = accounts[def.debit];
					const credit_acc = accounts[def.credit];

					if (debit_acc && credit_acc) {
						let row = frm.add_child("account_map");
						row.tax_type = def.tax_type;
						row.debit_account = debit_acc.name;
						row.credit_account = credit_acc.name;
						mapped++;
					}
				}

				frm.refresh_field("account_map");
				frappe.show_alert({
					message: __("{0} account mappings created from Chart of Accounts", [mapped]),
					indicator: mapped > 0 ? "green" : "orange"
				});

				frm.trigger("render_detection_status");
			}
		});
	},

	// ── Load Default Rates ────────────────────────────────

	load_default_rates(frm) {
		const defaults = [
			{ tax_type: "VAT (ƏDV)", rate: 18, description: __("Standard VAT rate — Maddə 159 Tax Code") },
			{ tax_type: "Profit Tax (Mənfəət)", rate: 20, description: __("Corporate profit tax — Maddə 104 Tax Code") },
			{ tax_type: "Simplified Tax - Trade Baku (Sadələşdirilmiş - Ticarət Bakı)", rate: 2, description: __("Retail/wholesale trade in Baku — Maddə 220.1") },
			{ tax_type: "Simplified Tax - Catering (Sadələşdirilmiş - İaşə)", rate: 8, description: __("Catering/public food services — Maddə 220.1") },
			{ tax_type: "Simplified Tax - Other (Sadələşdirilmiş - Digər)", rate: 4, description: __("Other activities — Maddə 220.1") },
			{ tax_type: "Property Tax (Əmlak)", rate: 1, description: __("Fixed assets — Maddə 199 Tax Code") },
			{ tax_type: "Unemployment Insurance Employer (İşsizlik - İşəgötürən)", rate: 0.5, description: __("Employer contribution — İşsizlikdən sığorta haqqında qanun") },
			{ tax_type: "Unemployment Insurance Employee (İşsizlik - İşçi)", rate: 0.5, description: __("Employee withholding — İşsizlikdən sığorta haqqında qanun") },
			{ tax_type: "DSMF Employer (DSMF - İşəgötürən)", rate: 22, description: __("Social insurance employer — DSMF qanunu") },
			{ tax_type: "DSMF Employee (DSMF - İşçi)", rate: 3, description: __("Social insurance employee — DSMF qanunu") },
			{ tax_type: "Medical Insurance Employer (Tibbi sığorta - İşəgötürən)", rate: 2, description: __("Medical insurance employer — İcbari tibbi sığorta qanunu") },
			{ tax_type: "Medical Insurance Employee (Tibbi sığorta - İşçi)", rate: 2, description: __("Medical insurance employee — İcbari tibbi sığorta qanunu") }
		];

		frm.doc.tax_rates = [];
		defaults.forEach(d => {
			let row = frm.add_child("tax_rates");
			row.tax_type = d.tax_type;
			row.rate = d.rate;
			row.description = d.description;
		});

		frm.refresh_field("tax_rates");
		frappe.show_alert({
			message: __("{0} default AZ tax rates loaded", [defaults.length]),
			indicator: "green"
		});
	}
});
