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

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

        public Item05Calculator(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 foundations = collector.Where(e => e.Category != null && e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralFoundation).ToList();

            foreach (var elem in foundations)
            {
                string fName = elem.Name;
                GetElementDimensions(elem, out double lengthMeters, out double widthMeters, out double thicknessMeters);

                double depthVal = Math.Abs(_levels.TopOfFoundation - _levels.BottomOfFoundation);
                if (depthVal <= 0) depthVal = thicknessMeters > 0 ? thicknessMeters : 0.4;

                // Row 1: Length x Depth (Nos = 2)
                double qty1 = 2 * lengthMeters * depthVal;
                totalQty += qty1;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Formwork for Foundation: {fName} [ID: {elem.Id}] (Row 1)",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = lengthMeters.ToString("F2"),
                    Width = "",
                    HeightDepth = depthVal.ToString("F2"),
                    Qty = qty1.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = "Centering & shuttering for foundation (Length x Height)."
                });

                // Row 2: Width x Depth (Nos = 2)
                double qty2 = 2 * widthMeters * depthVal;
                totalQty += qty2;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Formwork for Foundation: {fName} [ID: {elem.Id}] (Row 2)",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = "",
                    Width = widthMeters.ToString("F2"),
                    HeightDepth = depthVal.ToString("F2"),
                    Qty = qty2.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = "Centering & shuttering for foundation (Width x Height)."
                });
            }

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

            return rows;
        }

        private void GetElementDimensions(Element elem, out double lengthMeters, out double widthMeters, out double thicknessMeters)
        {
            lengthMeters = 1.5; widthMeters = 1.5; thicknessMeters = 0.4;
            Parameter lenParam = elem.LookupParameter("Length") ?? elem.LookupParameter("Foundation Length");
            Parameter widthParam = elem.LookupParameter("Width") ?? elem.LookupParameter("Foundation Width");
            Parameter thickParam = elem.LookupParameter("Thickness") ?? elem.LookupParameter("Foundation Thickness") ?? elem.LookupParameter("Depth");

            if (lenParam != null) lengthMeters = UnitUtils.ConvertFromInternalUnits(lenParam.AsDouble(), UnitTypeId.Meters);
            if (widthParam != null) widthMeters = UnitUtils.ConvertFromInternalUnits(widthParam.AsDouble(), UnitTypeId.Meters);
            if (thickParam != null) thicknessMeters = UnitUtils.ConvertFromInternalUnits(thickParam.AsDouble(), UnitTypeId.Meters);
        }
    }
}