package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.component.UI;
import de.assecutor.votianlt.model.Invoice;
import jakarta.annotation.security.RolesAllowed;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.time.LocalDate;
import java.util.List;

import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.server.StreamRegistration;

@PageTitle("Rechnungen")
@Route(value = "invoices", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class InvoicesView extends VerticalLayout {

    private final Grid<Invoice> invoiceGrid;

    public InvoicesView() {
        setSizeFull();
        setPadding(true);
        setSpacing(true);
        setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);

        H2 title = new H2("Rechnungen");
        add(title);

        invoiceGrid = new Grid<>(Invoice.class, false);
        invoiceGrid.addColumn(Invoice::getId).setHeader("Rechnungsnummer").setAutoWidth(true);
        invoiceGrid.addColumn(Invoice::getKunde).setHeader("Kunde").setAutoWidth(true);
        invoiceGrid.addColumn(Invoice::getDatum).setHeader("Datum").setAutoWidth(true);
        invoiceGrid.addColumn(Invoice::getBetrag).setHeader("Betrag").setAutoWidth(true);
        invoiceGrid.addColumn(Invoice::getBeschreibung).setHeader("Beschreibung").setAutoWidth(true);
        invoiceGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
        invoiceGrid.getStyle().set("cursor", "pointer");

        // Testdaten
        List<Invoice> testInvoices = List.of(
                new Invoice("R-2024-001", "Max Mustermann", LocalDate.now().minusDays(2), 199.99,
                        "Transport Hamburg-Berlin"),
                new Invoice("R-2024-002", "Erika Musterfrau", LocalDate.now().minusDays(1), 299.49,
                        "Express München-Köln"),
                new Invoice("R-2024-003", "Hans Beispiel", LocalDate.now(), 149.00, "Standard Leipzig-Dresden"));
        invoiceGrid.setItems(testInvoices);

        invoiceGrid.addItemClickListener(event -> {
            Invoice invoice = event.getItem();
            if (invoice != null) {
                downloadInvoicePdf(invoice);
            }
        });

        add(invoiceGrid);
    }

    private void downloadInvoicePdf(Invoice invoice) {
        try {
            // PDF generieren
            byte[] pdfBytes = generatePdf(invoice);
            StreamResource resource = new StreamResource(invoice.getId() + ".pdf",
                    () -> new ByteArrayInputStream(pdfBytes));
            resource.setContentType("application/pdf");
            resource.setCacheTime(0);

            // Direkter Download über UI
            StreamRegistration registration = UI.getCurrent().getSession().getResourceRegistry()
                    .registerResource(resource);
            UI.getCurrent().getPage().open(registration.getResourceUri().toString());

        } catch (Exception e) {
            Notification.show("Fehler beim Erstellen der PDF: " + e.getMessage(), 5000, Notification.Position.MIDDLE);
        }
    }

    private byte[] generatePdf(Invoice invoice) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            // Einfache PDF mit iText (oder OpenPDF, falls iText nicht verfügbar)
            com.lowagie.text.Document document = new com.lowagie.text.Document();
            com.lowagie.text.pdf.PdfWriter.getInstance(document, out);
            document.open();
            document.add(new com.lowagie.text.Paragraph("Rechnung: " + invoice.getId()));
            document.add(new com.lowagie.text.Paragraph("Kunde: " + invoice.getKunde()));
            document.add(new com.lowagie.text.Paragraph("Datum: " + invoice.getDatum()));
            document.add(new com.lowagie.text.Paragraph("Betrag: " + invoice.getBetrag() + " EUR"));
            document.add(new com.lowagie.text.Paragraph("Beschreibung: " + invoice.getBeschreibung()));
            document.close();
            return out.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("PDF-Generierung fehlgeschlagen: " + e.getMessage(), e);
        }
    }
}
