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

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

        public Item29Calculator(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 WET ROOMS & DOORS
            // ==========================================
            var rooms = collector.Where(e => e is Room).Cast<Room>().ToList();
            if (rooms.Count == 0)
            {
                rooms = new FilteredElementCollector(doc)
                    .OfCategory(BuiltInCategory.OST_Rooms)
                    .Cast<Room>()
                    .ToList();
            }

            var doors = collector
                .Where(e => e is FamilyInstance && e.Category != null && e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors)
                .Cast<FamilyInstance>().ToList();

            double tileHeight = 2.1; // 2.1m height for wall tiling

            foreach (var room in rooms)
            {
                string roomName = room.Name ?? "";
                string roomLower = roomName.ToLower();

                // INCLUDE ONLY: Wet rooms
                bool isWetRoom = roomLower.Contains("bath") ||
                                 roomLower.Contains("toilet") ||
                                 roomLower.Contains("wc") ||
                                 roomLower.Contains("kitchen") ||
                                 roomLower.Contains("powder");

                if (!isWetRoom) continue;

                double roomZ = room.Level != null ? UnitUtils.ConvertFromInternalUnits(room.Level.Elevation, UnitTypeId.Meters) : 0;
                var floor = activeFloors.FirstOrDefault(f => roomZ >= (f.BottomZ - 0.5) && roomZ <= (f.TopZ + 0.5)) ?? activeFloors.First();

                double area = UnitUtils.ConvertFromInternalUnits(room.Area, UnitTypeId.SquareMeters);
                if (area <= 0) continue;

                // Derive approximate Length (L) and Breadth (B) from room area
                double side = Math.Sqrt(area);
                double length = Math.Round(side * 1.1, 2);
                double breadth = Math.Round(area / length, 2);

                // 1. Length Sides Tiling (2 x L x 2.1)
                double qtyL = 2.0 * length * tileHeight;
                totalQty += qtyL;
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Wall Tiling (Length sides) in {roomName} ({floor.Name}) [ID: {room.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = length.ToString("F2"),
                    Width = "",
                    HeightDepth = tileHeight.ToString("F2"),
                    Qty = qtyL.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = $"Wall tiling: 2 x L ({length}m) x H ({tileHeight}m)."
                });

                // 2. Breadth Sides Tiling (2 x B x 2.1)
                double qtyB = 2.0 * breadth * tileHeight;
                totalQty += qtyB;
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Wall Tiling (Breadth sides) in {roomName} ({floor.Name}) [ID: {room.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "2",
                    Length = breadth.ToString("F2"),
                    Width = "",
                    HeightDepth = tileHeight.ToString("F2"),
                    Qty = qtyB.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = $"Wall tiling: 2 x B ({breadth}m) x H ({tileHeight}m)."
                });

                // 3. Deductions for doors connected to this wet room (With proper [ID: ...] for Smart Naming)
                foreach (var door in doors)
                {
                    if ((door.ToRoom != null && door.ToRoom.Id == room.Id) || (door.FromRoom != null && door.FromRoom.Id == room.Id))
                    {
                        double doorWidth = GetDimensionFromTypeOrInstance(door, "Width");
                        if (doorWidth == 0) doorWidth = 1.0;

                        double doorHeight = GetDimensionFromTypeOrInstance(door, "Height");
                        if (doorHeight == 0) doorHeight = 2.1;

                        double deductionArea = -1.0 * (doorWidth * Math.Min(doorHeight, tileHeight));
                        totalQty += deductionArea;

                        rows.Add(new EstimateRowModel
                        {
                            SNo = "",
                            ItemOfWork = $"   -> Deduct Wall Tiling for Door: {door.Name} [ID: {door.Id}]",
                            NosOfFlats = "",
                            NosOfInstance = "1",
                            Length = doorWidth.ToString("F2"),
                            Width = "",
                            HeightDepth = Math.Min(doorHeight, tileHeight).ToString("F2"),
                            Qty = deductionArea.ToString("F2"),
                            Unit = "Sqm",
                            Remarks = $"Tiling deduction for door opening ({doorWidth}m x {Math.Min(doorHeight, tileHeight)}m)."
                        });
                    }
                }
            }

            if (rows.Count == 0)
            {
                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = "   -> [No wet rooms found for Item 29 Wall Tiling]",
                    NosOfFlats = "-",
                    NosOfInstance = "0",
                    Length = "-",
                    Width = "-",
                    HeightDepth = "-",
                    Qty = "0.00",
                    Unit = "-",
                    Remarks = "No matching rooms detected."
                });
            }

            return rows;
        }

        private double GetDimensionFromTypeOrInstance(FamilyInstance inst, string paramName)
        {
            if (inst.Symbol != null) { Parameter typeParam = inst.Symbol.LookupParameter(paramName); if (typeParam != null && typeParam.HasValue) return UnitUtils.ConvertFromInternalUnits(typeParam.AsDouble(), UnitTypeId.Meters); }
            Parameter instParam = inst.LookupParameter(paramName);
            if (instParam != null && instParam.HasValue) return UnitUtils.ConvertFromInternalUnits(instParam.AsDouble(), UnitTypeId.Meters);
            return 0;
        }
    }
}