using System.Text.Json;
using BackOffice.Pages.Content.Components.SettingsModels;
using BackOffice.Services.Content;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using MudBlazor;

namespace BackOffice.Pages.Content.Components;

public partial class PageSettingsEditDialog
{
    [CascadingParameter] IMudDialogInstance DialogInstance { get; set; } = default!;
    [Inject] public ISitePageSettingsService PageSettingsService { get; set; } = default!;

    [Parameter] public SavePageSettingsDto Model { get; set; } = new();
    [Parameter] public string? ExistingHeroImagePath { get; set; }
    [Parameter] public string PageTitle { get; set; } = string.Empty;

    private MudForm? _form;
    private bool _isValid = true;
    private bool _loading;

    private IBrowserFile? _imageFile;
    private byte[]? _imageBuffer;
    private string? _imagePreview;
    private readonly long _maxAllowedSize = (1024 * 1024) * 5;

    // ── Typed settings models ──
    private LandingSettingsModel _landingSettings = new();
    private AboutSettingsModel _aboutSettings = new();
    private ContactSettingsModel _contactSettings = new();
    private LicensesSettingsModel _licensesSettings = new();

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNameCaseInsensitive = true,
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    protected override void OnParametersSet()
    {
        DeserializeSettings();
    }

    /// <summary>
    /// Parse existing SettingsJson into the typed model based on PageKey
    /// </summary>
    private void DeserializeSettings()
    {
        if (string.IsNullOrWhiteSpace(Model.SettingsJson)) return;

        try
        {
            switch (Model.PageKey)
            {
                case "landing":
                    _landingSettings = JsonSerializer.Deserialize<LandingSettingsModel>(Model.SettingsJson, JsonOptions) ?? new();
                    break;
                case "about":
                    _aboutSettings = JsonSerializer.Deserialize<AboutSettingsModel>(Model.SettingsJson, JsonOptions) ?? new();
                    break;
                case "contact":
                    _contactSettings = JsonSerializer.Deserialize<ContactSettingsModel>(Model.SettingsJson, JsonOptions) ?? new();
                    break;
                case "licenses":
                    _licensesSettings = JsonSerializer.Deserialize<LicensesSettingsModel>(Model.SettingsJson, JsonOptions) ?? new();
                    break;
            }
        }
        catch
        {
            // If JSON is malformed, start with empty model
        }
    }

    /// <summary>
    /// Serialize the typed model back to JSON before saving
    /// </summary>
    private void SerializeSettings()
    {
        Model.SettingsJson = Model.PageKey switch
        {
            "landing" => JsonSerializer.Serialize(_landingSettings, JsonOptions),
            "about" => JsonSerializer.Serialize(_aboutSettings, JsonOptions),
            "contact" => JsonSerializer.Serialize(_contactSettings, JsonOptions),
            "licenses" => JsonSerializer.Serialize(_licensesSettings, JsonOptions),
            _ => Model.SettingsJson // keep raw JSON for unknown pages
        };
    }

    private async Task OnImageSelected(IBrowserFile? file)
    {
        _imageFile = file;
        if (file != null)
        {
            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _imageBuffer = ms.ToArray();
            _imagePreview = $"data:{file.ContentType};base64," + Convert.ToBase64String(_imageBuffer);
            StateHasChanged();
        }
    }

    private async Task SubmitAsync()
    {
        if (_form != null)
        {
            await _form.Validate();
            if (!_isValid) return;
        }

        _loading = true;

        // Serialize typed model → JSON before saving
        SerializeSettings();

        if (_imageFile != null && _imageBuffer != null)
        {
            Model.ImageFile = _imageBuffer;
            Model.ImageMime = _imageFile.ContentType;
            Model.ImageFileName = Path.GetFileNameWithoutExtension(_imageFile.Name);
        }

        try
        {
            var result = await PageSettingsService.SaveSettingsAsync(Model);
            if (result.Success)
            {
                DialogInstance.Close(DialogResult.Ok(true));
            }
            else
            {
                Snackbar.Add("خطا در ذخیره تنظیمات", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private void Cancel()
    {
        DialogInstance.Cancel();
    }
}
