using DiunaBI.Application.DTOModels;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using System.Reflection;

namespace DiunaBI.UI.Shared.Pages;

public partial class LayerDetailPage : ComponentBase
{
    [Parameter]
    public Guid Id { get; set; }

    [Inject]
    private ISnackbar Snackbar { get; set; } = null!;

    private LayerDto? layer;
    private List<RecordDto> records = new();
    private List<string> displayedColumns = new();
    private double valueSum = 0;
    private bool isLoading = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadLayer();
    }

    protected override async Task OnParametersSetAsync()
    {
        await LoadLayer();
    }

    private async Task LoadLayer()
    {
        isLoading = true;
        StateHasChanged();

        try
        {
            layer = await LayerService.GetLayerByIdAsync(Id);

            if (layer != null && layer.Records != null)
            {
                records = layer.Records;
                CalculateDisplayedColumns();
                CalculateValueSum();
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Error loading layer: {ex.Message}");
            Snackbar.Add("Error loading layer", Severity.Error);
        }
        finally
        {
            isLoading = false;
            StateHasChanged();
        }
    }

    private void CalculateDisplayedColumns()
    {
        displayedColumns.Clear();

        // Check which Value columns have data
        for (int i = 1; i <= 32; i++)
        {
            var columnName = $"Value{i}";
            var hasData = records.Any(r => GetRecordValueByName(r, columnName) != null);

            if (hasData)
            {
                displayedColumns.Add(columnName);
            }
        }

        // Check if Desc1 has data
        if (records.Any(r => !string.IsNullOrEmpty(r.Desc1)))
        {
            displayedColumns.Add("Description1");
        }
    }

    private void CalculateValueSum()
    {
        valueSum = records
            .Where(r => r.Value1.HasValue)
            .Sum(r => r.Value1!.Value);
    }

    private string GetRecordValue(RecordDto record, string columnName)
    {
        if (columnName == "Description1")
        {
            return record.Desc1 ?? string.Empty;
        }

        var value = GetRecordValueByName(record, columnName);
        return value.HasValue ? value.Value.ToString("N2") : string.Empty;
    }

    private double? GetRecordValueByName(RecordDto record, string columnName)
    {
        var property = typeof(RecordDto).GetProperty(columnName, BindingFlags.Public | BindingFlags.Instance);
        if (property != null && property.PropertyType == typeof(double?))
        {
            return property.GetValue(record) as double?;
        }
        return null;
    }

    private void Export()
    {
        // TODO: Implement export functionality
        Snackbar.Add("Export functionality coming soon", Severity.Error);
    }

    private void ProcessLayer()
    {
        // TODO: Implement process layer functionality
        Snackbar.Add("Process layer functionality coming soon", Severity.Error);
    }
}
