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

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

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

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

            // ==========================================
            // 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 FLOORS / ROOFS (Superstructure)
            // ==========================================
            var floors = collector
                .Where(e => e.Category != null && e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Floors)
                .Cast<Floor>()
                .ToList();

            foreach (var floor in floors)
            {
                BoundingBoxXYZ box = floor.get_BoundingBox(null);
                if (box == null) continue;

                double floorZ = UnitUtils.ConvertFromInternalUnits((box.Min.Z + box.Max.Z) / 2.0, UnitTypeId.Meters);

                // Match with active superstructure floors
                var matchedFloor = activeFloors.FirstOrDefault(f => floorZ >= (f.BottomZ - 0.5) && floorZ <= (f.TopZ + 0.5));
                if (matchedFloor == null && floorZ < _levels.TopOfPlinth) continue; // Skip sub-structure floors

                string floorNameTag = matchedFloor != null ? matchedFloor.Name : "Superstructure";

                // Extract Area of the floor/roof slab
                Parameter areaParam = floor.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED) ?? floor.LookupParameter("Area");
                double area = areaParam != null && areaParam.HasValue ? UnitUtils.ConvertFromInternalUnits(areaParam.AsDouble(), UnitTypeId.SquareMeters) : 0.0;

                if (area <= 0) continue;

                totalQty += area;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Centering for Suspended Slab/Roof ({floorNameTag}): {floor.Name} [ID: {floor.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = area.ToString("F2"),      // Area representation or effective span
                    Width = "",                         // Blank for Sqm format
                    HeightDepth = "",                   // Thickness not considered for shuttering area
                    Qty = area.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = $"Suspended floor/roof centering area in {floorNameTag} level."
                });
            }

            if (rows.Count == 0)
            {
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = "   -> [No suspended floors/roofs found for Item 48]",
                    NosOfFlats = "-",
                    NosOfInstance = "0",
                    Length = "-",
                    Width = "-",
                    HeightDepth = "-",
                    Qty = "0.00",
                    Unit = "Sqm",
                    Remarks = "No elements detected."
                });
            }

            return rows;
        }
    }
}