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

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

        public Item04Calculator(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>();

            Document doc = collector.FirstOrDefault()?.Document;
            if (doc == null) return rows;

            // ==========================================
            // PART A: RCC in Foundations (Actual Dimensions)
            // ==========================================
            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;

                double qty = lengthMeters * widthMeters * depthVal;
                totalQty += qty;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> RCC in Foundation: {fName} [ID: {elem.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = lengthMeters.ToString("F2"),
                    Width = widthMeters.ToString("F2"),
                    HeightDepth = depthVal.ToString("F2"),
                    Qty = qty.ToString("F2"),
                    Unit = "Cum",
                    Remarks = $"RCC M20 grade work in foundation with actual dimensions (L={lengthMeters:F2}m, W={widthMeters:F2}m, Depth={depthVal:F2}m)."
                });
            }

            // ==========================================
            // PART B: RCC in Plinth Beams (Cut Lengths & 'b', 'h' Properties)
            // ==========================================
            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);

                // Fetching b and h strictly from beam's own properties
                double bWid = GetParameterValueByName(beam, "b") ?? GetParameterValueByName(beam, "Width") ?? GetParamVal(beam, BuiltInParameter.STRUCTURAL_SECTION_COMMON_WIDTH);
                if (bWid <= 0) bWid = 0.3;

                double bDepth = GetParameterValueByName(beam, "h") ?? GetParameterValueByName(beam, "Depth") ?? GetParameterValueByName(beam, "Height") ?? GetParamVal(beam, BuiltInParameter.STRUCTURAL_SECTION_COMMON_HEIGHT);
                if (bDepth <= 0) bDepth = 0.4;

                if (cutLength <= 0) cutLength = 3.0;

                double qty = cutLength * bWid * bDepth;
                totalQty += qty;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> RCC in Plinth Beam: {beamName} [ID: {beam.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = cutLength.ToString("F2"),
                    Width = bWid.ToString("F2"),
                    HeightDepth = bDepth.ToString("F2"),
                    Qty = qty.ToString("F2"),
                    Unit = "Cum",
                    Remarks = $"RCC M20 in plinth beam using cut length ({cutLength:F2}m) and beam properties (b={bWid:F2}m, h={bDepth:F2}m)."
                });
            }

            // ==========================================
            // PART C: RCC in Columns (Top of Foundation to Plinth Level)
            // ==========================================
            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") ?? GetParamVal(col, BuiltInParameter.STRUCTURAL_SECTION_COMMON_WIDTH);
                if (cWidth <= 0) cWidth = 0.4;

                double cDepth = GetParameterValueByName(col, "h") ?? GetParameterValueByName(col, "Depth") ?? GetParameterValueByName(col, "Height") ?? GetParamVal(col, BuiltInParameter.STRUCTURAL_SECTION_COMMON_HEIGHT);
                if (cDepth <= 0) cDepth = 0.4;

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

                double qty = cWidth * cDepth * colHeight;
                totalQty += qty;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> RCC in Column (Substructure): {colName} [ID: {col.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = cWidth.ToString("F2"),
                    Width = cDepth.ToString("F2"),
                    HeightDepth = colHeight.ToString("F2"),
                    Qty = qty.ToString("F2"),
                    Unit = "Cum",
                    Remarks = $"RCC M20 in column below plinth (Top of Foundation to Plinth Level height = {colHeight:F2}m)."
                });
            }

            if (rows.Count == 0)
            {
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> [No matching substructure elements found for Item 4]",
                    NosOfFlats = "-",
                    NosOfInstance = "0",
                    Length = "-",
                    Width = "-",
                    HeightDepth = "-",
                    Qty = "0.00",
                    Unit = "-",
                    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;
        }

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

        private double GetParamVal(Element e, BuiltInParameter param)
        {
            Parameter p = e.get_Parameter(param);
            if (p != null && p.HasValue) return UnitUtils.ConvertFromInternalUnits(p.AsDouble(), UnitTypeId.Meters);
            return 0.0;
        }
    }
}