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

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

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

            foreach (var beam in structuralFraming)
            {
                double beamZ = GetElementZCoordinate(beam);
                if (beamZ > _levels.TopOfPlinth + 0.1) continue;

                string beamName = beam.Name;
                double cutLength = GetBeamCutLength(beam);

                double bWid = GetParameterValueByName(beam, "b") ?? GetParameterValueByName(beam, "Width") ?? 0.3;
                double bDepth = GetParameterValueByName(beam, "h") ?? GetParameterValueByName(beam, "Depth") ?? 0.4;

                if (cutLength <= 0) cutLength = 3.0;

                // Row 1: CutLength x h (Sides, Nos = 2)
                double qtyBeam1 = 2 * cutLength * bDepth;
                totalQty += qtyBeam1;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Formwork for Plinth Beam: {beamName} [ID: {beam.Id}] (Row 1)",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = cutLength.ToString("F2"),
                    Width = "",
                    HeightDepth = bDepth.ToString("F2"),
                    Qty = qtyBeam1.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = "Plinth beam shuttering sides (Cut Length x h)."
                });

                // Row 2: CutLength x b (Bottom, Nos = 1)
                double qtyBeam2 = 1 * cutLength * bWid;
                totalQty += qtyBeam2;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Formwork for Plinth Beam: {beamName} [ID: {beam.Id}] (Row 2)",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = cutLength.ToString("F2"),
                    Width = bWid.ToString("F2"),
                    HeightDepth = "",
                    Qty = qtyBeam2.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = "Plinth beam bottom shuttering (Cut Length x b)."
                });
            }

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

            return rows;
        }

        private double GetBeamCutLength(Element beam)
        {
            Parameter cutLenParam = beam.LookupParameter("Cut Length") ?? beam.get_Parameter(BuiltInParameter.INSTANCE_LENGTH_PARAM);
            if (cutLenParam != null && cutLenParam.HasValue)
            {
                return UnitUtils.ConvertFromInternalUnits(cutLenParam.AsDouble(), UnitTypeId.Meters);
            }

            if (beam.Location is LocationCurve locCurve && locCurve.Curve != null)
            {
                return UnitUtils.ConvertFromInternalUnits(locCurve.Curve.Length, UnitTypeId.Meters);
            }

            Parameter lenParam = beam.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH) ?? beam.LookupParameter("Length");
            if (lenParam != null && lenParam.HasValue)
            {
                return UnitUtils.ConvertFromInternalUnits(lenParam.AsDouble(), UnitTypeId.Meters);
            }

            return 3.0;
        }

        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;
        }

        private double GetElementZCoordinate(Element elem)
        {
            BoundingBoxXYZ box = elem.get_BoundingBox(null);
            if (box != null)
            {
                return UnitUtils.ConvertFromInternalUnits((box.Min.Z + box.Max.Z) / 2.0, UnitTypeId.Meters);
            }
            return 0.0;
        }
    }
}