using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using VideoStudy.Shared;
using System.Text.RegularExpressions;

namespace VideoStudy.Desktop.Services;

public class PdfStyles
{
    // Colors (from vcart.me.novo reference)
    public string PrimaryColor { get; set; } = "#007bff";
    public string SecondaryColor { get; set; } = "#0056b3";
    public string AccentPurple { get; set; } = "#764ba2";
    public string AccentBlue { get; set; } = "#667eea";
    public string TextColor { get; set; } = "#212529";
    public string LightBackground { get; set; } = "#f8f9fa";

    // Typography
    public string HeadingFont { get; set; } = "Helvetica";
    public string BodyFont { get; set; } = "Helvetica";
    public int HeadingSize { get; set; } = 24;
    public int SubheadingSize { get; set; } = 18;
    public int BodySize { get; set; } = 11;

    // Spacing
    public float ParagraphSpacing { get; set; } = 12;
    public float SectionSpacing { get; set; } = 24;
}

public class PdfGeneratorService
{
    private readonly PdfStyles _styles = new();

    public PdfGeneratorService()
    {
        QuestPDF.Settings.License = LicenseType.Community;
    }

    public string GeneratePdf(ProcessingResult data, VideoInfo videoInfo, string outputDirectory, string? analysisText = null)
    {
        var safeTitle = string.Join("_", videoInfo.Title.Split(Path.GetInvalidFileNameChars()));
        var fileName = $"{safeTitle}_StudyNotes.pdf";
        var outputPath = Path.Combine(outputDirectory, fileName);

        Document.Create(container =>
        {
            container.Page(page =>
            {
                page.Size(PageSizes.A4);
                page.Margin(2, Unit.Centimetre);
                page.PageColor(Colors.White);
                page.DefaultTextStyle(x => x.FontFamily(_styles.BodyFont).FontSize(_styles.BodySize).FontColor(_styles.TextColor));

                page.Header().Element(header => ComposeHeader(header, videoInfo));
                page.Content().Element(content => ComposeContent(content, data, analysisText));
                page.Footer().Element(ComposeFooter);
            });
        })
        .GeneratePdf(outputPath);

        return outputPath;
    }

    private void ComposeHeader(IContainer container, VideoInfo info)
    {
        container.Row(row =>
        {
            row.RelativeItem().Column(column =>
            {
                column.Item().Text($"{info.Title}").FontSize(_styles.HeadingSize).SemiBold().FontColor(_styles.PrimaryColor);
                column.Item().Text($"Author: {info.Author} | Duration: {info.Duration}").FontSize(_styles.BodySize).FontColor(Colors.Grey.Medium);
                column.Item().Text($"Generated on: {DateTime.Now:D}").FontSize(_styles.BodySize).FontColor(Colors.Grey.Medium);
            });

            row.ConstantItem(50).Height(50).Placeholder();
        });
    }

    private void ComposeContent(IContainer container, ProcessingResult data, string? analysisText)
    {
        container.Column(column =>
        {
            column.Spacing(_styles.SectionSpacing);

            // Table of Contents
            column.Item().Text("Table of Contents").FontSize(_styles.SubheadingSize).Bold().FontColor(_styles.SecondaryColor);
            column.Item().Text("1. AI Study Guide");
            column.Item().Text("2. Key Moments & Screenshots");
            column.Item().Text("3. Full Transcription");

            // Section 1: AI-generated study guide with inline images
            if (!string.IsNullOrEmpty(analysisText))
            {
                column.Item().PageBreak();
                column.Item().Text("1. AI Study Guide").FontSize(_styles.SubheadingSize).Bold().FontColor(_styles.SecondaryColor);
                column.Item().PaddingTop(_styles.ParagraphSpacing);

                RenderAnalysisWithImages(column, analysisText, data.ScreenshotPaths);
            }

            // Section 2: Key Moments with screenshots
            column.Item().PageBreak();
            column.Item().Text("2. Key Moments & Screenshots").FontSize(_styles.SubheadingSize).Bold().FontColor(_styles.SecondaryColor);

            for (int i = 0; i < data.KeyMoments.Count; i++)
            {
                var moment = data.KeyMoments[i];

                column.Item().PaddingTop(_styles.SectionSpacing);

                column.Item().Row(row =>
                {
                    row.AutoItem().Text($"[{moment.Timestamp}] ").Bold().FontColor(_styles.AccentBlue);
                    row.RelativeItem().Text(moment.Description).Bold();
                });

                // Screenshot by index
                if (i < data.ScreenshotPaths.Count)
                {
                    var screenshotPath = data.ScreenshotPaths[i];
                    if (!string.IsNullOrEmpty(screenshotPath) && File.Exists(screenshotPath))
                    {
                        column.Item().PaddingTop(_styles.ParagraphSpacing).Image(screenshotPath).FitArea();
                    }
                }

                // Explanation from AI
                if (!string.IsNullOrEmpty(moment.Explanation))
                {
                    column.Item().PaddingTop(5)
                        .Text(moment.Explanation)
                        .Italic().FontColor(Colors.Grey.Darken2);
                }

                column.Item().PaddingTop(_styles.ParagraphSpacing).LineHorizontal(1).LineColor(Colors.Grey.Lighten2);
            }

            // Section 3: Full Transcription
            column.Item().PageBreak();
            column.Item().Text("3. Full Transcription").FontSize(_styles.SubheadingSize).Bold().FontColor(_styles.SecondaryColor);
            column.Item().PaddingTop(_styles.ParagraphSpacing);

            if (!string.IsNullOrEmpty(data.Transcription.FullText))
            {
                column.Item().Text(data.Transcription.FullText);
            }
            else
            {
                column.Item().Text("No transcription available.");
            }
        });
    }

    private void RenderAnalysisWithImages(ColumnDescriptor column, string analysisText, List<string> screenshotPaths)
    {
        // Split by [IMG:N] markers and render text + images inline
        var pattern = @"\[IMG:(\d+)\]";
        var parts = Regex.Split(analysisText, pattern);

        // parts alternates: text, index, text, index, text...
        for (int i = 0; i < parts.Length; i++)
        {
            if (i % 2 == 0)
            {
                // Text part
                var text = parts[i].Trim();
                if (!string.IsNullOrEmpty(text))
                {
                    RenderMarkdownText(column, text);
                }
            }
            else
            {
                // Image index
                if (int.TryParse(parts[i], out int imgIndex) && imgIndex >= 0 && imgIndex < screenshotPaths.Count)
                {
                    var path = screenshotPaths[imgIndex];
                    if (!string.IsNullOrEmpty(path) && File.Exists(path))
                    {
                        column.Item().PaddingVertical(8).Image(path).FitArea();
                    }
                }
            }
        }
    }

    private void RenderMarkdownText(ColumnDescriptor column, string text)
    {
        // Simple markdown rendering: split by lines and handle ## headers
        var lines = text.Split('\n');
        foreach (var line in lines)
        {
            var trimmed = line.Trim();
            if (string.IsNullOrEmpty(trimmed)) continue;

            if (trimmed.StartsWith("## "))
            {
                column.Item().PaddingTop(_styles.SectionSpacing)
                    .Text(trimmed[3..])
                    .FontSize(14).Bold().FontColor(_styles.AccentPurple);
            }
            else if (trimmed.StartsWith("# "))
            {
                column.Item().PaddingTop(_styles.SectionSpacing)
                    .Text(trimmed[2..])
                    .FontSize(16).Bold().FontColor(_styles.SecondaryColor);
            }
            else if (trimmed.StartsWith("### "))
            {
                column.Item().PaddingTop(_styles.ParagraphSpacing)
                    .Text(trimmed[4..])
                    .FontSize(12).Bold().FontColor(_styles.AccentBlue);
            }
            else
            {
                column.Item().Text(trimmed);
            }
        }
    }

    private void ComposeFooter(IContainer container)
    {
        container.Row(row =>
        {
            row.RelativeItem().Text("Generated by VideoStudy.app").FontSize(10).FontColor(Colors.Grey.Medium);
            row.RelativeItem().AlignRight().Text(x =>
            {
                x.Span("Page ");
                x.CurrentPageNumber();
                x.Span(" of ");
                x.TotalPages();
            });
        });
    }
}
