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 Item28Calculator : IItemCalculator
    {
        private ProjectLevels _levels;

        public Item28Calculator(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 (Bathroom, Toilet, Kitchen, Powder Room)
            // ==========================================
            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();
            }

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

                // INCLUDE ONLY: Bathrooms, Toilets, Kitchens, Powder Rooms, WC
                bool isWetRoom = roomLower.Contains("bath") ||
                                 roomLower.Contains("toilet") ||
                                 roomLower.Contains("wc") ||
                                 roomLower.Contains("kitchen") ||
                                 roomLower.Contains("powder");

                if (!isWetRoom) continue; // Skip non-wet rooms

                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;

                totalQty += area;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> Ceramic Glazed Floor Tiles in {roomName} ({floor.Name}) [ID: {room.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = area.ToString("F2"), // Area representation in Length column
                    Width = "",                   // Blank for Sqm format
                    HeightDepth = "",             // Thickness not considered
                    Qty = area.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = $"Floor area from wet room tag '{roomName}'."
                });
            }

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

            return rows;
        }
    }
}