using System;
using System.Collections.Generic;
using System.Windows;
using Autodesk.Revit.DB;
using RevitEstimate.Estimation;
using RevitEstimate.Export;
using RevitEstimate.Models;

namespace RevitEstimate
{
    public partial class EstimateWindow : Window
    {
        private Document _doc;
        private ProjectLevels _levels;
        private List<EstimateRowModel> _estimateRows; // Store rows for export

        public EstimateWindow(params object[] args)
        {
            InitializeComponent();

            if (args != null && args.Length > 0)
            {
                foreach (var arg in args)
                {
                    if (arg is Document doc)
                    {
                        _doc = doc;
                    }
                    else if (arg is ProjectLevels levels)
                    {
                        _levels = levels;
                    }
                }
            }

            if (_levels == null)
            {
                _levels = new ProjectLevels(); // Fallback if levels not passed
            }

            if (_doc != null)
            {
                LoadDataFromEngine();
            }
        }

        private void LoadDataFromEngine()
        {
            // Call the unified EstimateEngine to generate the full report
            _estimateRows = EstimateEngine.GenerateEstimateReport(_doc, _levels);

            // Bind to WPF DataGrid (Matching your DataGrid name: DataGridEstimate)
            if (DataGridEstimate != null)
            {
                DataGridEstimate.ItemsSource = _estimateRows;
            }
        }

        private void BtnExport_Click(object sender, RoutedEventArgs e)
        {
            if (_estimateRows == null || _estimateRows.Count == 0)
            {
                MessageBox.Show("No data available to export.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // Call ExcelExporter which prompts user for save file path via SaveFileDialog
            bool success = ExcelExporter.ExportToExcel(_estimateRows);

            if (success)
            {
                MessageBox.Show("All items and remarks exported successfully!", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}