using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using WPFBeginner.Models;
using WPFBeginner.Services;

namespace WPFBeginner.ViewModels;

public partial class RegistViewModel : ObservableObject
{
    private readonly ISettingsService _settingsService;

    [ObservableProperty]
    private string _name = string.Empty;

    [ObservableProperty]
    private string _call = string.Empty;

    [ObservableProperty]
    private string _eMail = string.Empty;

    [ObservableProperty]
    private string _no = string.Empty;

    [ObservableProperty]
    private string _errorMessage = string.Empty;

    [ObservableProperty]
    private bool _hasError;

    public event EventHandler<Member>? MemberAdded;

    public RegistViewModel(ISettingsService settingsService)
    {
        _settingsService = settingsService;
    }

    [RelayCommand]
    private void Register(Window window)
    {
        // Validate required fields
        if (string.IsNullOrWhiteSpace(Name))
        {
            HasError = true;
            ErrorMessage = _settingsService.CurrentLanguage == "en-US"
                ? "Name is required"
                : "이름은 필수입니다";
            return;
        }

        if (string.IsNullOrWhiteSpace(EMail))
        {
            HasError = true;
            ErrorMessage = _settingsService.CurrentLanguage == "en-US"
                ? "Email is required"
                : "이메일은 필수입니다";
            return;
        }

        HasError = false;
        ErrorMessage = string.Empty;

        var member = new Member(Name, Call, EMail, No);
        MemberAdded?.Invoke(this, member);
        window.Close();
    }

    [RelayCommand]
    private void Cancel(Window window)
    {
        window.Close();
    }

    [RelayCommand]
    private void Minimize(Window window)
    {
        window.WindowState = WindowState.Minimized;
    }

    [RelayCommand]
    private void Maximize(Window window)
    {
        window.WindowState = window.WindowState == WindowState.Maximized
            ? WindowState.Normal
            : WindowState.Maximized;
    }

    [RelayCommand]
    private void Close(Window window)
    {
        window.Close();
    }
}
