using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using MTWorkHR.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevExpress.CodeParser;
using iText.Kernel.Events;
using Event = iText.Kernel.Events.Event;
using MTWorkHR.Core.Global;
using MTWorkHR.Infrastructure.Entities;
using Microsoft.Extensions.Options;

namespace MTWorkHR.Infrastructure.Reports
{
    public class ContractPdfGenerator 
    {
        public async Task<byte[]> GenerateContractPdf(string outputPath, ContractDetail contractData)
        {
            try { 
            // Use MemoryStream to generate the PDF in memory
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (PdfWriter writer = new PdfWriter(memoryStream))
                using (PdfDocument pdf = new PdfDocument(writer))
                using (Document document = new Document(pdf))
                {
                    PdfFont boldFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA_BOLD);
                    PdfFont regularFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);

                    // Timestamp and Title
                    document.Add(new Paragraph($"{DateTime.UtcNow:dd/MM/yyyy HH:mm:ss} .")
                        .SetFont(regularFont)
                        .SetFontSize(10));
                    document.Add(new Paragraph("Employee Contract")
                        .SetFont(boldFont)
                        .SetFontSize(20)
                        .SetMarginBottom(20)
                        .SetTextAlignment(TextAlignment.CENTER));

                        // Header
                        //        document.Add(new Paragraph("Contract Agreement")
                        //            .SetFont(boldFont)
                        //            .SetFontSize(20)
                        //            .SetTextAlignment(TextAlignment.CENTER));

                        // Company Information
                        document.Add(new Paragraph("Company Information:")
                            .SetFont(boldFont)
                            .SetFontSize(12));
                        Table companyTable = new Table(new float[] { 1, 3, 1, 1 }).UseAllAvailableWidth();
                        companyTable.AddCell(CreateCell("Name:", boldFont));
                        companyTable.AddCell(CreateCell(contractData.CompanyName, regularFont));
                        companyTable.AddCell(CreateCell("CR:", boldFont));
                        companyTable.AddCell(CreateCell(contractData.CompanyCR, regularFont));
                        companyTable.AddCell(CreateCell("Email:", boldFont));
                        companyTable.AddCell(CreateCell(contractData.CompanyEmail, regularFont));
                        companyTable.AddCell(CreateCell("Phone:", boldFont));
                        companyTable.AddCell(CreateCell(contractData.CompanyPhone, regularFont));
                        companyTable.AddCell(CreateCell("Address:", boldFont));
                        companyTable.AddCell(CreateCell(contractData.CompanyAddress, regularFont, 3));
                        document.Add(companyTable);

                        // Company Representative
                        document.Add(new Paragraph("Company Representative:")
                        .SetFont(boldFont)
                        .SetFontSize(12)
                        .SetMarginTop(10));

                        //Representative Table
                    Table repTable = new Table(new float[] { 1, 3 }).UseAllAvailableWidth();

                        // Row 1: Name
                        repTable.AddCell(CreateCell("Name:", boldFont));
                        repTable.AddCell(CreateCell(contractData.CompanyRepresentativeName, regularFont));

                        // Row 2: Passport
                        repTable.AddCell(CreateCell("Passport:", boldFont));
                        repTable.AddCell(CreateCell(contractData.CompanyRepresentativePassport, regularFont));

                        // Row 3: Phone
                        repTable.AddCell(CreateCell("Phone:", boldFont));
                        repTable.AddCell(CreateCell(contractData.CompanyRepresentativePhone, regularFont));

                        // Row 4: Email
                        repTable.AddCell(CreateCell("Email:", boldFont));
                        repTable.AddCell(CreateCell(contractData.CompanyRepresentativeEmail, regularFont));

                        // Row 5: Position
                        repTable.AddCell(CreateCell("Position:", boldFont));
                        repTable.AddCell(CreateCell(contractData.CompanyRepresentativePosition, regularFont));

                        document.Add(repTable);


                        //Employee Information
                        document.Add(new Paragraph("Employee Information:")
                            .SetFont(boldFont)
                            .SetFontSize(12)
                            .SetMarginTop(10));
                        document.Add(new Paragraph($"Name: \t {contractData.EmployeeName}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Passport: \t {contractData.EmployeePassport}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Date Of Birth: \t {contractData.EmployeeDateOfBirth:dd/MM/yyyy}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Phone: \t {contractData.EmployeePhone}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"University: \t {contractData.EmployeeUniversity}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Work Country: \t {contractData.WorkCountry}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Job: \t {contractData.JobTitleName}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Job Number: \t {contractData.JobNumber}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Job Description: \t {contractData.JobDescription}")
                            .SetFont(regularFont));

                        //Contract Details
                        document.Add(new Paragraph("Contract")
                            .SetFont(boldFont)
                            .SetFontSize(12)
                            .SetMarginTop(10));
                        Table contractTable = new Table(new float[] { 1, 3, 1, 3 }).UseAllAvailableWidth();
                        contractTable.AddCell(CreateCell("Start Date:", boldFont));
                        contractTable.AddCell(CreateCell($"{contractData.StartDate:dd/MM/yyyy}", regularFont));
                        contractTable.AddCell(CreateCell("End Date:", boldFont));
                        contractTable.AddCell(CreateCell($"{contractData.EndDate:dd/MM/yyyy}", regularFont));
                        contractTable.AddCell(CreateCell("Duration:", boldFont));
                        contractTable.AddCell(CreateCell($"{contractData.ContractDuration}", regularFont));
                        contractTable.AddCell(CreateCell("Contract Type:", boldFont));
                        contractTable.AddCell(CreateCell((ContractTypeEnum)contractData.ContractTypeId + "", regularFont));
                        contractTable.AddCell(CreateCell("Vacation Days:", boldFont));
                        contractTable.AddCell(CreateCell($"{contractData.VacationDays}", regularFont));
                        contractTable.AddCell(CreateCell("Trial Period:", boldFont));
                        contractTable.AddCell(CreateCell($"{contractData.TrialPeriod}", regularFont));
                        contractTable.AddCell(CreateCell("Termination Notice Period:", boldFont));
                        contractTable.AddCell(CreateCell($"{contractData.NoticePeriodBeforeTermination}", regularFont));
                        document.Add(contractTable);

                        // Work Time
                        document.Add(new Paragraph("Work Time")
                            .SetFont(boldFont)
                            .SetFontSize(12)
                            .SetMarginTop(10));
                        document.Add(new Paragraph($"Working Days: \t {contractData.WorkingDays}")
                            .SetFont(regularFont));
                        document.Add(new Paragraph($"Working Hours: \t {contractData.WorkingHours}")
                            .SetFont(regularFont));

                        // Salary
                        document.Add(new Paragraph("Salary")
                            .SetFont(boldFont)
                            .SetFontSize(12)
                            .SetMarginTop(10));
                        document.Add(new Paragraph($"Amount: \t {contractData.Salary:F2} {contractData.Currency}")
                            .SetFont(regularFont));

                      
                        
                        if (contractData.FixedAllowances != null && contractData.FixedAllowances.Count > 0)
                        {
                            // Allowances
                            document.Add(new Paragraph("Allowances")
                                .SetFont(boldFont)
                                .SetFontSize(12)
                                .SetMarginTop(10));

                            Table allowanceTable = new Table(new float[] { 2, 1, 2, 1 }).UseAllAvailableWidth();
                            allowanceTable.AddHeaderCell(CreateCell("Type", boldFont));
                            allowanceTable.AddHeaderCell(CreateCell("Rate", boldFont));
                            allowanceTable.AddHeaderCell(CreateCell("Amount", boldFont));
                            allowanceTable.AddHeaderCell(CreateCell("Frequency", boldFont));
                            foreach (var allowance in contractData.FixedAllowances)
                            {
                                allowanceTable.AddCell(CreateCell(allowance.AllowanceType + "", regularFont));
                                allowanceTable.AddCell(CreateCell($"{allowance.PaymentType:F2}", regularFont));
                                allowanceTable.AddCell(CreateCell($"{allowance.EntitlementAmount:F2}", regularFont));
                                allowanceTable.AddCell(CreateCell($"{allowance.EntitlementPercent}", regularFont));
                            }
                            document.Add(allowanceTable);
                        }
                        //ProjectStages
                        if (contractData.ProjectStages != null && contractData.ProjectStages.Count >0)
                        {
                            // Allowances
                            document.Add(new Paragraph("Project Stages")
                                .SetFont(boldFont)
                                .SetFontSize(12)
                                .SetMarginTop(10));
                            Table ProjectStagesTable = new Table(new float[] { 1, 3 }).UseAllAvailableWidth();
                            ProjectStagesTable.AddHeaderCell(CreateCell("Title", boldFont));
                            ProjectStagesTable.AddHeaderCell(CreateCell("Scope of work", boldFont));
                            foreach (var allowance in contractData.ProjectStages)
                            {
                                ProjectStagesTable.AddCell(CreateCell(allowance.Title + "", regularFont));
                                ProjectStagesTable.AddCell(CreateCell($"{allowance.ScopeOfWork:F2}", regularFont));
                            }
                            document.Add(ProjectStagesTable);
                        }
                        //ContractTasks
                       
                        if (contractData.ContractTasks != null && contractData.ContractTasks.Count > 0)
                        {
                            // Allowances
                            document.Add(new Paragraph("Contract Tasks")
                                .SetFont(boldFont)
                                .SetFontSize(12)
                                .SetMarginTop(10));
                            Table ContractTasksTable = new Table(new float[] { 1, 3, 1, 3 }).UseAllAvailableWidth();
                            ContractTasksTable.AddHeaderCell(CreateCell("Title", boldFont));
                            ContractTasksTable.AddHeaderCell(CreateCell("Scope of work", boldFont));
                            ContractTasksTable.AddHeaderCell(CreateCell("StartDate", boldFont));
                            ContractTasksTable.AddHeaderCell(CreateCell("Amount", boldFont));
                            foreach (var allowance in contractData.ContractTasks)
                            {
                                ContractTasksTable.AddCell(CreateCell(allowance.Title + "", regularFont));
                                ContractTasksTable.AddCell(CreateCell($"{allowance.ScopeOfWork:F2}", regularFont));
                                ContractTasksTable.AddCell(CreateCell($"{allowance.StartDate:dd/MM/yyyy}", regularFont));
                                ContractTasksTable.AddCell(CreateCell($"{allowance.Amount:F2}", regularFont));
                            }
                            document.Add(ContractTasksTable);
                        }
                        // Page Numbers
                    pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new PageNumberEventHandler(document));
                }
                byte[] pdfBytes = memoryStream.ToArray();

                // If you still want to save to file, you can do it here
                //if (!string.IsNullOrEmpty(outputPath))
                //{
                //    await File.WriteAllBytesAsync(outputPath, pdfBytes);
                //}

                return pdfBytes;


                    //return UploadToAzureBlob(pdfBytes, blobName);

                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public   byte[] GeneratePdf()
        {
            //_logger.LogInformation("Generating PDF...");
            try
            {
                using (var stream = new MemoryStream())
                {
                    PdfWriter writer = new PdfWriter(stream);
                    PdfDocument pdf = new PdfDocument(writer);
                    Document document = new Document(pdf);
                    document.Add(new Paragraph("Hello, Azure App Service!"));
                    document.Close();
                    //  _logger.LogInformation("PDF generated successfully.");
                    return stream.ToArray();
                }
            }
            catch (Exception ex)
            {
               // _logger.LogError(ex, "Failed to generate PDF.");
                throw;
            }
        }
        //private string UploadToAzureBlob(byte[] pdfBytes, string blobName)
        //{
        //    // Create a BlobServiceClient
        //    BlobServiceClient blobServiceClient = new BlobServiceClient(_storageSettings.ConnectionString);

        //    // Get a reference to the container
        //    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageSettings.ContainerName);

        //    // Create the container if it doesn’t exist
        //    containerClient.CreateIfNotExists();

        //    // Get a reference to the blob
        //    BlobClient blobClient = containerClient.GetBlobClient(blobName);

        //    // Upload the PDF bytes
        //    using (MemoryStream uploadStream = new MemoryStream(pdfBytes))
        //    {
        //        blobClient.Upload(uploadStream, overwrite: true);
        //    }

        //    // Return the Blob URL
        //    return blobClient.Uri.ToString();
        //}
        private Cell CreateCell(string text, PdfFont font, int colspan = 1)
        {
            return new Cell(1, colspan).Add(new Paragraph(text).SetFont(font).SetFontSize(10));
        }

        private class PageNumberEventHandler : IEventHandler
        {
            private readonly Document _document;

            public PageNumberEventHandler(Document document)
            {
                _document = document;
            }

            public void HandleEvent(Event @event)
            {
                PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
                PdfDocument pdf = docEvent.GetDocument();
                PdfPage page = docEvent.GetPage();
                int pageNumber = pdf.GetPageNumber(page);
                PdfFont font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);

                _document.ShowTextAligned(
                    new Paragraph($"Page {pageNumber}").SetFont(font).SetFontSize(10),
                    550, 20, pageNumber, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
            }
        }
    }
}
//public class ContractPdfGenerator 
//    {
//public void GenerateContractPdf(string outputPath, Contract contractData)
//{
//    using (PdfWriter writer = new PdfWriter(outputPath))
//    using (PdfDocument pdf = new PdfDocument(writer))
//    using (Document document = new Document(pdf))
//    {
//        PdfFont boldFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA_BOLD);
//        PdfFont regularFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);

//        // Header
//        document.Add(new Paragraph("Contract Agreement")
//            .SetFont(boldFont)
//            .SetFontSize(20)
//            .SetTextAlignment(TextAlignment.CENTER));

//        // Parties
//        document.Add(new Paragraph($"\nThis contract is made on {DateTime.UtcNow:MMMM dd, yyyy}, between:")
//            .SetFont(regularFont));
//        document.Add(new Paragraph()
//            .Add(new Text("Party A: ").SetFont(boldFont))
//            .Add(new Text($"{contractData.CompanyId}\n").SetFont(regularFont))
//            .Add(new Text("Party B: ").SetFont(boldFont))
//            .Add(new Text($"{contractData.JobTitleName}").SetFont(regularFont)));

//        // Terms Table
//        Table table = new Table(UnitValue.CreatePercentArray(new float[] { 1, 3 })).UseAllAvailableWidth();
//        table.AddHeaderCell(new Cell().Add(new Paragraph("Clause").SetFont(boldFont)).SetBackgroundColor(ColorConstants.LIGHT_GRAY));
//        table.AddHeaderCell(new Cell().Add(new Paragraph("Description").SetFont(boldFont)).SetBackgroundColor(ColorConstants.LIGHT_GRAY));
//        foreach (var term in contractData.ProjectStages)
//        {
//            table.AddCell(new Cell().Add(new Paragraph(term.Title).SetFont(regularFont)));
//            table.AddCell(new Cell().Add(new Paragraph(term.ScopeOfWork).SetFont(regularFont)));
//        }
//        document.Add(table);

//        // Signatures
//        document.Add(new Paragraph("\nSignatures:").SetFont(boldFont).SetFontSize(14));
//        document.Add(new Paragraph("___________________________\nParty A Representative").SetFont(regularFont));
//        document.Add(new Paragraph("___________________________\nParty B Representative").SetFont(regularFont));

//        // Page numbers (via event handler if needed)
//        pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new PageNumberEventHandler(document));
//    }
//}

//private class PageNumberEventHandler : IEventHandler
//{
//    private readonly Document _document;
//    public PageNumberEventHandler(Document document) => _document = document;

//    public void HandleEvent(iText.Kernel.Events.Event @event)
//    {
//        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
//        PdfDocument pdf = docEvent.GetDocument();
//        PdfPage page = docEvent.GetPage();
//        int pageNumber = pdf.GetPageNumber(page);
//        PdfFont font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);

//        _document.ShowTextAligned(
//            new Paragraph($"Page {pageNumber}").SetFont(font).SetFontSize(10),
//            550, 20, pageNumber, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
//    }
//}
//  }
//}

