package de.assecutor.votianlt.service;

import de.assecutor.votianlt.model.invoices.SystemInvoiceData;
import de.assecutor.votianlt.model.invoices.SystemInvoiceItem;
import org.springframework.stereotype.Service;

import com.itextpdf.html2pdf.HtmlConverter;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class SystemInvoiceService {

    private final SystemCompanyProfileService systemCompanyProfileService;

    public SystemInvoiceService(SystemCompanyProfileService systemCompanyProfileService) {
        this.systemCompanyProfileService = systemCompanyProfileService;
    }

    public byte[] generateInvoicePdfFromHtml() throws Exception {
        // Read the HTML template
        String htmlContent = readHtmlTemplate();

        // Fill HTML with sample data
        SystemInvoiceData sampleData = createSampleInvoiceData();
        String filledHtml = fillHtmlWithInvoiceData(htmlContent, sampleData);

        // Generate PDF from HTML
        return generatePdfFromHtmlString(filledHtml);
    }

    /**
     * Generate a SystemInvoice PDF using provided data and the HTML template.
     */
    public byte[] generateInvoicePdfFromHtml(SystemInvoiceData data) throws Exception {
        String htmlContent = readHtmlTemplate();
        String filledHtml = fillHtmlWithInvoiceData(htmlContent, data);
        return generatePdfFromHtmlString(filledHtml);
    }

    public SystemInvoiceData createSampleInvoiceData() {
        SystemInvoiceData data = systemCompanyProfileService.createSystemInvoiceData();

        // Set sample data
        data.setInvoiceNumber("HHA-2021-007");
        data.setInvoiceDate("19.07.2021");
        data.setInvoiceText(
                "Gemäß unserem Nutzungsvertrag zu der Bestellnummer 45519389 berechnen wir Ihnen für den Monat Juli 2021 wie folgt:");

        data.setRecipientName("Hamburger Hochbahn AG");
        data.setRecipientDepartment("Kreditorenbuchhaltung");
        data.setRecipientStreet("Steinstraße 20");
        data.setRecipientCity("20095 Hamburg");

        List<SystemInvoiceItem> items = new ArrayList<>();
        items.add(new SystemInvoiceItem("1", "Mtl. Lizenzgebühr »ILLT«", "5.639,00 €", "5.639,00 €"));
        data.setInvoiceItems(items);

        data.setNetAmount("5.639,00 €");
        data.setVatAmount("1.071,41 €");
        data.setTotalAmount("6.710,41 €");

        return data;
    }

    private String readHtmlTemplate() throws Exception {
        // Read the HTML template file
        java.nio.file.Path path = java.nio.file.Paths.get("src/main/resources/templates/system_invoice.html");
        return java.nio.file.Files.readString(path);
    }

    private String fillHtmlWithInvoiceData(String html, SystemInvoiceData data) {
        // Replace placeholders in HTML with actual invoice data
        String filledHtml = html;

        // Replace invoice data placeholders
        filledHtml = filledHtml.replace("HHA-2021-007", data.getInvoiceNumber() != null ? data.getInvoiceNumber() : "");
        filledHtml = filledHtml.replace("19.07.2021", data.getInvoiceDate() != null ? data.getInvoiceDate() : "");
        filledHtml = filledHtml.replace(
                "Gemäß unserem Nutzungsvertrag zu der Bestellnummer 45519389 berechnen wir Ihnen für den Monat Juli 2021 wie folgt:",
                data.getInvoiceText() != null ? data.getInvoiceText() : "");

        // Replace recipient address
        filledHtml = filledHtml.replace("Hamburger Hochbahn AG",
                data.getRecipientName() != null ? data.getRecipientName() : "");
        filledHtml = filledHtml.replace("Kreditorenbuchhaltung",
                data.getRecipientDepartment() != null ? data.getRecipientDepartment() : "");
        filledHtml = filledHtml.replace("Steinstraße 20",
                data.getRecipientStreet() != null ? data.getRecipientStreet() : "");
        filledHtml = filledHtml.replace("20095 Hamburg",
                data.getRecipientCity() != null ? data.getRecipientCity() : "");

        // Replace invoice items
        if (data.getInvoiceItems() != null && !data.getInvoiceItems().isEmpty()) {
            SystemInvoiceItem item = data.getInvoiceItems().getFirst();
            filledHtml = filledHtml.replace("Mtl. Lizenzgebühr »ILLT«",
                    item.getDescription() != null ? item.getDescription() : "");
        }

        // Replace amounts
        filledHtml = filledHtml.replace("5.639,00 €", data.getNetAmount() != null ? data.getNetAmount() : "");
        filledHtml = filledHtml.replace("1.071,41 €", data.getVatAmount() != null ? data.getVatAmount() : "");
        filledHtml = filledHtml.replace("6.710,41 €", data.getTotalAmount() != null ? data.getTotalAmount() : "");

        return filledHtml;
    }

    private byte[] generatePdfFromHtmlString(String htmlContent) throws Exception {
        // Create PDF using iText library
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Convert HTML to PDF using iText 8 HtmlConverter
        HtmlConverter.convertToPdf(htmlContent, baos);

        return baos.toByteArray();
    }

}
