using FluentValidation;
using FrontOffice.Main.Utilities;
using MudBlazor;
using Severity = MudBlazor.Severity;

namespace FrontOffice.Main.Pages;

public partial class Contact
{
    private ContactForm _contactForm = new();
    private MudForm? _form;
    private bool _isSubmitting;
    private readonly ContactFormValidator _contactFormValidator = new();

    // Dynamic CMS data (new simplified system)
    private PageSettingsDto? _page;
    private ContactSettings? _settings;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _page = await PageSettingsService.GetPageAsync("contact");

            if (_page != null)
            {
                _settings = _page.GetSettings<ContactSettings>();
            }
        }
        catch
        {
            // Fallback: all values remain null → hardcoded defaults will render
        }
    }

    private async Task SubmitContactForm()
    {
        if (_form is null) return;

        await _form.Validate();
        if (!_form.IsValid) return;

        if (!_contactForm.AcceptTerms)
        {
            Snackbar.Add("لطفاً شرایط و قوانین را بپذیرید.", MudBlazor.Severity.Warning);
            return;
        }

        _isSubmitting = true;

        try
        {
            // TODO: Send contact form to API
            await Task.Delay(2000); // Simulate API call

            Snackbar.Add("پیام شما با موفقیت ارسال شد. به زودی با شما تماس خواهیم گرفت.", Severity.Success);

            // Reset form
            _contactForm = new ContactForm();
            await _form.ResetAsync();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در ارسال پیام: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSubmitting = false;
            await InvokeAsync(StateHasChanged);
        }
    }

    private void StartChat()
    {
        // TODO: Open chat widget or redirect to chat page
        Snackbar.Add("چت آنلاین به زودی فعال خواهد شد.", Severity.Info);
    }

    private void CallSupport()
    {
        Snackbar.Add($"شماره تماس: {_settings?.Phone ?? "026-34233563"}", Severity.Info);
    }

    private void SendEmail()
    {
        Snackbar.Add($"ایمیل: {_settings?.Email ?? "info@kbs1.co"}", Severity.Info);
    }

    public class ContactForm
    {
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? Email { get; set; }
        public string? Phone { get; set; }
        public string? Subject { get; set; }
        public string? Message { get; set; }
        public bool AcceptTerms { get; set; }
    }

    public class ContactFormValidator : FluentValidation.AbstractValidator<ContactForm>
    {
        public ContactFormValidator()
        {
            RuleFor(x => x.FirstName).NotEmpty().WithMessage("نام الزامی است");
            RuleFor(x => x.LastName).NotEmpty().WithMessage("نام خانوادگی الزامی است");
            RuleFor(x => x.Email).NotEmpty().EmailAddress().WithMessage("ایمیل معتبر نیست");
            RuleFor(x => x.Subject).NotEmpty().WithMessage("انتخاب موضوع الزامی است");
            RuleFor(x => x.Message).NotEmpty().MinimumLength(10).WithMessage("پیام باید حداقل ۱۰ کاراکتر باشد");
        }
    }

    // DTO class for SettingsJson deserialization
    private class ContactSettings
    {
        public string? Address { get; set; }
        public string? Phone { get; set; }
        public string? Email { get; set; }
        public string? WorkingHours { get; set; }
        public string? TelegramUrl { get; set; }
        public string? InstagramUrl { get; set; }
        public string? LinkedinUrl { get; set; }
        public string? WhatsappUrl { get; set; }
    }
}