using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using RevitEstimate.Models;

namespace RevitEstimate.Calculators
{
    public class Item06Calculator : IItemCalculator
    {
        private ProjectLevels _levels;

        public Item06Calculator(ProjectLevels levels = null)
        {
            _levels = levels ?? new ProjectLevels();
        }

        public List<EstimateRowModel> Calculate(List<Element> collector, out double totalQty)
        {
            totalQty = 0.0;
            var rows = new List<EstimateRowModel>();

            var columns = collector.Where(e => e.Category != null && e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns).ToList();

            foreach (var col in columns)
            {
                string colName = col.Name;

                double cWidth = GetParameterValueByName(col, "b") ?? GetParameterValueByName(col, "Width") ?? 0.3;
                double cDepth = GetParameterValueByName(col, "h") ?? GetParameterValueByName(col, "Depth") ?? 0.4;

                double colHeight = Math.Abs(_levels.TopOfPlinth - _levels.TopOfFoundation);
                if (colHeight <= 0) colHeight = 1.5;

                // Row 1: Length = colHeight, Width = b, Height = blank
                double qtyCol1 = 2 * colHeight * cWidth;
                totalQty += qtyCol1;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Formwork for Column: {colName} [ID: {col.Id}] (Row 1)",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = colHeight.ToString("F2"),
                    Width = cWidth.ToString("F2"),
                    HeightDepth = "",
                    Qty = qtyCol1.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = "Centering & shuttering for column (Height x b)."
                });

                // Row 2: Length = colHeight, Width = blank, Height = h
                double qtyCol2 = 2 * colHeight * cDepth;
                totalQty += qtyCol2;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Formwork for Column: {colName} [ID: {col.Id}] (Row 2)",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = colHeight.ToString("F2"),
                    Width = "",
                    HeightDepth = cDepth.ToString("F2"),
                    Qty = qtyCol2.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = "Centering & shuttering for column (Height x h)."
                });
            }

            if (rows.Count == 0)
            {
                rows.Add(new EstimateRowModel { SNo = "", ItemOfWork = "   -> [No columns found]", NosOfFlats = "-", NosOfInstance = "0", Length = "-", Width = "-", HeightDepth = "-", Qty = "0.00", Unit = "-", Remarks = "No elements." });
            }

            return rows;
        }

        private double? GetParameterValueByName(Element elem, string paramName)
        {
            Parameter param = elem.LookupParameter(paramName);
            if (param == null && elem.Document.GetElement(elem.GetTypeId()) is ElementType elemType)
            {
                param = elemType.LookupParameter(paramName);
            }
            if (param != null && param.HasValue)
            {
                return UnitUtils.ConvertFromInternalUnits(param.AsDouble(), UnitTypeId.Meters);
            }
            return null;
        }
    }
}