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

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

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

        private class FloorLevelInfo
        {
            public string Name { get; set; }
            public double BottomZ { get; set; }
            public double TopZ { get; set; }
        }

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

            // ==========================================
            // SETUP ACTIVE FLOORS FROM LEVEL WINDOW (Superstructure)
            // ==========================================
            var activeFloors = new List<FloorLevelInfo>();
            activeFloors.Add(new FloorLevelInfo { Name = "GF", BottomZ = _levels.TopOfPlinth, TopZ = _levels.SlabTop });
            double currentTop = _levels.SlabTop;

            if (_levels.FirstFloorSlabTop != -8888 && _levels.FirstFloorSlabTop != 0)
            {
                activeFloors.Add(new FloorLevelInfo { Name = "FF", BottomZ = currentTop, TopZ = _levels.FirstFloorSlabTop });
                currentTop = _levels.FirstFloorSlabTop;
            }
            if (_levels.SecondFloorSlabTop != -8888 && _levels.SecondFloorSlabTop != 0)
            {
                activeFloors.Add(new FloorLevelInfo { Name = "SF", BottomZ = currentTop, TopZ = _levels.SecondFloorSlabTop });
                currentTop = _levels.SecondFloorSlabTop;
            }
            if (_levels.ThirdFloorSlabTop != -8888 && _levels.ThirdFloorSlabTop != 0)
            {
                activeFloors.Add(new FloorLevelInfo { Name = "TF", BottomZ = currentTop, TopZ = _levels.ThirdFloorSlabTop });
                currentTop = _levels.ThirdFloorSlabTop;
            }
            if (_levels.TerraceRoofTop != -8888 && _levels.TerraceRoofTop != 0)
            {
                activeFloors.Add(new FloorLevelInfo { Name = "Terrace", BottomZ = currentTop, TopZ = _levels.TerraceRoofTop });
            }

            // ==========================================
            // COLLECT STRUCTURAL FRAMING (Superstructure Beams & Lintels)
            // ==========================================
            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);

                // Superstructure filter: Must be above plinth level (with small tolerance)
                if (beamZ < _levels.TopOfPlinth - 0.1) continue;

                var matchedFloor = activeFloors.FirstOrDefault(f => beamZ >= (f.BottomZ - 0.5) && beamZ <= (f.TopZ + 0.5)) ?? activeFloors.First();

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

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

                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 Superstructure Beam ({matchedFloor.Name}): {beamName} [ID: {beam.Id}] (Sides)",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = cutLength.ToString("F2"),
                    Width = "",
                    HeightDepth = bDepth.ToString("F2"),
                    Qty = qtyBeam1.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = $"Beam shuttering sides in {matchedFloor.Name} (Cut Length x 2h)."
                });

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

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

            if (rows.Count == 0)
            {
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = "   -> [No superstructure beams or lintels found for Item 49]",
                    NosOfFlats = "-",
                    NosOfInstance = "0",
                    Length = "-",
                    Width = "-",
                    HeightDepth = "-",
                    Qty = "0.00",
                    Unit = "Sqm",
                    Remarks = "No elements detected."
                });
            }

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