import { StyleGenerator } from '@pdfdraft/core/lib/html';
import {
	DEFAULT_TOTAL_BLOCK_SETTINGS,
	type TotalBlockSettings,
} from './constants/types';

const styleGenerator = new StyleGenerator();

export function totalBlockToHTML(data: any): string {
	const props: TotalBlockSettings = {
		...DEFAULT_TOTAL_BLOCK_SETTINGS,
		...(data.props ?? {}),
	};

	const style = styleGenerator.generateElementStyle(data.style);
	const textColor = props.textStyle?.color;
	const textFontFamily = props.textStyle?.fontFamily;
	const textAlign = props.textAlign ?? 'right';
	const rowLabelCss = `text-align:${textAlign};padding:4px 10px 4px 0;font-weight:600;${textColor ? `color:${textColor};` : ''}`;
	const rowAmountCss = `text-align:${textAlign};padding:4px 0;white-space:nowrap;${textColor ? `color:${textColor};` : ''}`;

	const rows: string[] = [];

	rows.push(
		`<tr data-pdfdraft-total-row="subtotal" data-enabled="${props.showSubtotal ? '1' : '0'}" data-amount="{{subtotal}}">
			<td style="${rowLabelCss}">Subtotal</td>
			<td style="${rowAmountCss}">{{currency_symbol}} {{subtotal}}</td>
		</tr>`,
	);
	rows.push(
		`<tr data-pdfdraft-total-row="total_discount" data-enabled="${props.showDiscount ? '1' : '0'}" data-amount="{{total_discount}}">
			<td style="${rowLabelCss}">Discount</td>
			<td style="${rowAmountCss}">{{currency_symbol}} {{total_discount}}</td>
		</tr>`,
	);
	rows.push(
		`<tr data-pdfdraft-total-row="total_tax" data-enabled="${props.showTax ? '1' : '0'}" data-amount="{{total_tax}}">
			<td style="${rowLabelCss}">Tax</td>
			<td style="${rowAmountCss}">{{currency_symbol}} {{total_tax}}</td>
		</tr>`,
	);
	rows.push(
		`<tr data-pdfdraft-total-row="grand_total" data-enabled="1" data-amount="{{grand_total}}">
			<td style="${rowLabelCss}">Total</td>
			<td style="${rowAmountCss}">{{currency_symbol}} {{grand_total}}</td>
		</tr>`,
	);

	return `
		<div id="${data.id}" data-type="woocommerce_total_block" style="${style}">
			<table style="width:100%;height:100%;border-collapse:collapse;table-layout:fixed;font-size:13px;line-height:1.35;${textFontFamily ? `font-family:${textFontFamily};` : ''}">
				<colgroup><col style="width:50%"/><col style="width:50%"/></colgroup>
				<tbody>
					${rows.join('')}
				</tbody>
			</table>
		</div>
	`;
}
