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

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

        public Item33Calculator(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
            // ==========================================
            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 DOORS & WINDOWS
            // ==========================================
            var openings = collector
                .Where(e => e is FamilyInstance && e.Category != null &&
                           (e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors ||
                            e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows))
                .Cast<FamilyInstance>().ToList();

            foreach (var opening in openings)
            {
                BoundingBoxXYZ box = opening.get_BoundingBox(null);
                if (box == null) continue;

                double openingZ = UnitUtils.ConvertFromInternalUnits((box.Min.Z + box.Max.Z) / 2.0, UnitTypeId.Meters);
                var floor = activeFloors.FirstOrDefault(f => openingZ >= (f.BottomZ - 0.5) && openingZ <= (f.TopZ + 0.5)) ?? activeFloors.First();

                double qty = 4.0; // 4 Hold fasts per frame instance
                totalQty += qty;

                string categoryName = opening.Category.Name;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Hold Fast for {categoryName} ({floor.Name}): {opening.Name} [ID: {opening.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "4",
                    Length = "-",
                    Width = "-",
                    HeightDepth = "-",
                    Qty = qty.ToString("F2"),
                    Unit = "Nos",
                    Remarks = $"4 hold fast lugs per {categoryName.ToLower()} frame."
                });
            }

            if (rows.Count == 0)
            {
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = "   -> [No Doors or Windows found for Item 33 Hold Fast]",
                    NosOfFlats = "-",
                    NosOfInstance = "0",
                    Length = "-",
                    Width = "-",
                    HeightDepth = "-",
                    Qty = "0.00",
                    Unit = "Nos",
                    Remarks = "No elements detected."
                });
            }

            return rows;
        }
    }
}