package com.MedInsuranceV2.Version20.Claim;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.UnitValue;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class PdfGeneratorService {

    public byte[] generateClaimPdf(List<Claim> claims) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = new PdfWriter(baos);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);

        document.add(new Paragraph("Claim Details").setFontSize(20).setBold());
        document.add(new Paragraph(" ")); // Spacer

        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 2}));
        table.setWidth(UnitValue.createPercentValue(100));

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

        for (Claim claim : claims) {
            addTableRow(table, "Claim ID:", String.valueOf(claim.getId()));
            addTableRow(table, "Claim Number:", claim.getClaimNumber());
            addTableRow(table, "Insurance Name:", claim.getInsuranceName());
            addTableRow(table, "Admin Notes:", claim.getAdminNotes());
            addTableRow(table, "Customer Email:", claim.getCustomerEmail());
            addTableRow(table, "Customer Name:", claim.getCustomerName());
            addTableRow(table, "Customer Phone:", claim.getCustomerPhone());
            addTableRow(table, "Filing Date:", claim.getFilingDate() != null 
                    ? LocalDateTime.ofInstant(claim.getFilingDate().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter) 
                    : "N/A");
                addTableRow(table, "Incident Date:", claim.getIncidentDate() != null 
                    ? LocalDateTime.ofInstant(claim.getIncidentDate().toInstant(), ZoneId.systemDefault()).format(dateFormatter) 
                    : "N/A");
            addTableRow(table, "Reason:", claim.getReason());
            addTableRow(table, "Status:", claim.isApproved() ? "Approved" : "Not Approved");
        }

        document.add(table);
        document.close();
        return baos.toByteArray();
    }

    private void addTableRow(Table table, String header, String value) {
        table.addCell(new Paragraph(header).setBold());
        table.addCell(new Paragraph(value));
    }
}
