using ClosedXML.Excel;
using Microsoft.EntityFrameworkCore;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Forms.Services;
using SolutionErp.Application.Reports.Services;
using SolutionErp.Domain.Contracts;

namespace SolutionErp.Infrastructure.Reports;

public class ContractExcelExporter(IApplicationDbContext db, IDateTime dateTime) : IContractExcelExporter
{
    private static readonly Dictionary<ContractPhase, string> PhaseLabel = new()
    {
        [ContractPhase.DangChon] = "Đang chọn NCC",
        [ContractPhase.DangSoanThao] = "Nháp",
        [ContractPhase.DangGopY] = "Đang góp ý",
        [ContractPhase.DangDamPhan] = "Đang đàm phán",
        [ContractPhase.DangInKy] = "Đang in ký",
        [ContractPhase.DangKiemTraCCM] = "CCM kiểm tra",
        [ContractPhase.DangTrinhKy] = "Đang trình ký",
        [ContractPhase.DangDongDau] = "Đang đóng dấu",
        [ContractPhase.DaPhatHanh] = "Đã phát hành",
        [ContractPhase.ChoDuyet] = "Đã gửi duyệt",
        [ContractPhase.TraLai] = "Trả lại",
        [ContractPhase.TuChoi] = "Từ chối",
    };

    private static readonly Dictionary<ContractType, string> TypeLabel = new()
    {
        [ContractType.HopDongThauPhu] = "HĐ Thầu phụ",
        [ContractType.HopDongGiaoKhoan] = "HĐ Giao khoán",
        [ContractType.HopDongNhaCungCap] = "HĐ NCC",
        [ContractType.HopDongDichVu] = "HĐ Dịch vụ",
        [ContractType.HopDongMuaBan] = "HĐ Mua bán",
        [ContractType.HopDongNguyenTacNCC] = "HĐ Nguyên tắc NCC",
        [ContractType.HopDongNguyenTacDichVu] = "HĐ Nguyên tắc DV",
    };

    public async Task<RenderResult> ExportAsync(
        ContractPhase? phase, Guid? supplierId, Guid? projectId,
        DateTime? fromDate, DateTime? toDate, CancellationToken ct = default)
    {
        var q = from c in db.Contracts.AsNoTracking()
                join s in db.Suppliers.AsNoTracking() on c.SupplierId equals s.Id
                join p in db.Projects.AsNoTracking() on c.ProjectId equals p.Id
                select new { c, s, p };

        if (phase is not null) q = q.Where(x => x.c.Phase == phase);
        if (supplierId is not null) q = q.Where(x => x.c.SupplierId == supplierId);
        if (projectId is not null) q = q.Where(x => x.c.ProjectId == projectId);
        if (fromDate is not null) q = q.Where(x => x.c.CreatedAt >= fromDate);
        if (toDate is not null) q = q.Where(x => x.c.CreatedAt < toDate);

        var rows = await q.OrderByDescending(x => x.c.CreatedAt).ToListAsync(ct);

        using var wb = new XLWorkbook();
        var ws = wb.Worksheets.Add("Contracts");

        // Header
        var headers = new[] { "STT", "Mã HĐ", "Tên HĐ", "Loại", "Phase", "NCC", "Dự án", "Giá trị (VND)", "SLA", "Ngày tạo" };
        for (int i = 0; i < headers.Length; i++)
            ws.Cell(1, i + 1).Value = headers[i];

        var headerRange = ws.Range(1, 1, 1, headers.Length);
        headerRange.Style.Font.Bold = true;
        headerRange.Style.Fill.BackgroundColor = XLColor.LightBlue;
        headerRange.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

        // Data
        for (int i = 0; i < rows.Count; i++)
        {
            var r = rows[i];
            var rowIdx = i + 2;
            ws.Cell(rowIdx, 1).Value = i + 1;
            ws.Cell(rowIdx, 2).Value = r.c.MaHopDong ?? "—";
            ws.Cell(rowIdx, 3).Value = r.c.TenHopDong ?? "—";
            ws.Cell(rowIdx, 4).Value = TypeLabel.GetValueOrDefault(r.c.Type, "?");
            ws.Cell(rowIdx, 5).Value = PhaseLabel.GetValueOrDefault(r.c.Phase, "?");
            ws.Cell(rowIdx, 6).Value = r.s.Name;
            ws.Cell(rowIdx, 7).Value = r.p.Name;
            ws.Cell(rowIdx, 8).Value = r.c.GiaTri;
            ws.Cell(rowIdx, 8).Style.NumberFormat.Format = "#,##0";
            ws.Cell(rowIdx, 9).Value = r.c.SlaDeadline?.ToString("yyyy-MM-dd HH:mm") ?? "—";
            ws.Cell(rowIdx, 10).Value = r.c.CreatedAt.ToString("yyyy-MM-dd HH:mm");
        }

        // Auto-fit
        ws.Columns().AdjustToContents();
        ws.SheetView.FreezeRows(1);

        // Footer summary
        if (rows.Count > 0)
        {
            var sumRow = rows.Count + 3;
            ws.Cell(sumRow, 7).Value = "TỔNG:";
            ws.Cell(sumRow, 7).Style.Font.Bold = true;
            ws.Cell(sumRow, 7).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
            ws.Cell(sumRow, 8).FormulaA1 = $"=SUM(H2:H{rows.Count + 1})";
            ws.Cell(sumRow, 8).Style.NumberFormat.Format = "#,##0";
            ws.Cell(sumRow, 8).Style.Font.Bold = true;
        }

        using var ms = new MemoryStream();
        wb.SaveAs(ms);
        var fileName = $"Contracts_{dateTime.UtcNow:yyyyMMdd_HHmmss}.xlsx";
        return new RenderResult(
            ms.ToArray(),
            fileName,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }
}
