using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using Microsoft.Win32;
using RevitEstimate.Models;

namespace RevitEstimate.Export
{
    public static class ExcelExporter
    {
        public static bool ExportToExcel(List<EstimateRowModel> rows)
        {
            try
            {
                // Open Save File Dialog to ask user for saving path and filename
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Title = "Export Estimate Report to Excel (CSV)",
                    Filter = "CSV File (*.csv)|*.csv|All Files (*.*)|*.*",
                    FileName = "Estimate_Report_" + DateTime.Now.ToString("yyyyMMdd_HHmmss")
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    string filePath = saveFileDialog.FileName;
                    var csvContent = new StringBuilder();

                    // CSV Headers
                    csvContent.AppendLine("S.No,Item of Work,Nos of Flats,Nos of Instance,Length,Width,Height/Depth,Qty,Unit,Remarks / Logic");

                    // CSV Data Rows
                    foreach (var row in rows)
                    {
                        string sNo = EscapeCsv(row.SNo);
                        string itemOfWork = EscapeCsv(row.ItemOfWork);
                        string nosFlats = EscapeCsv(row.NosOfFlats);
                        string nosInstance = EscapeCsv(row.NosOfInstance);
                        string length = EscapeCsv(row.Length);
                        string width = EscapeCsv(row.Width);
                        string heightDepth = EscapeCsv(row.HeightDepth);
                        string qty = EscapeCsv(row.Qty);
                        string unit = EscapeCsv(row.Unit);
                        string remarks = EscapeCsv(row.Remarks);

                        csvContent.AppendLine($"{sNo},{itemOfWork},{nosFlats},{nosInstance},{length},{width},{heightDepth},{qty},{unit},{remarks}");
                    }

                    // Save file with UTF-8 encoding so special symbols work properly in Excel
                    File.WriteAllText(filePath, csvContent.ToString(), Encoding.UTF8);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error exporting file: " + ex.Message, "Export Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        private static string EscapeCsv(string input)
        {
            if (string.IsNullOrEmpty(input)) return "";
            if (input.Contains(",") || input.Contains("\"") || input.Contains("\n"))
            {
                return "\"" + input.Replace("\"", "\"\"") + "\"";
            }
            return input;
        }
    }
}