@page "/admin/settings"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@attribute [Authorize]
@using System.Collections.Generic
@using TaxBaik.Domain.Interfaces
@inject IApiClient ApiClient
@inject ISnackbar Snackbar

<PageTitle>설정</PageTitle>

<AdminPageHeader Title="설정" Eyebrow="System" Subtitle="공개 사이트 연락처와 관리자 계정 보안을 관리합니다." />

<MudGrid Class="mb-3" Spacing="2">
    <MudItem xs="12" md="4">
        <MudPaper Class="admin-surface" Elevation="0" Outlined="true">
            <MudText Typo="Typo.overline">공개 정보</MudText>
            <MudText Typo="Typo.h6" Class="font-weight-bold">@form.Phone</MudText>
            <MudText Typo="Typo.body2">@form.Email</MudText>
        </MudPaper>
    </MudItem>
    <MudItem xs="12" md="4">
        <MudPaper Class="admin-surface" Elevation="0" Outlined="true">
            <MudText Typo="Typo.overline">소셜 채널</MudText>
            <MudText Typo="Typo.body2">카카오채널과 인스타그램 링크를 함께 관리합니다.</MudText>
        </MudPaper>
    </MudItem>
    <MudItem xs="12" md="4">
        <MudPaper Class="admin-surface" Elevation="0" Outlined="true">
            <MudText Typo="Typo.overline">보안 기준</MudText>
            <MudText Typo="Typo.body2">비밀번호는 12자 이상, 변경 전 확인을 요구합니다.</MudText>
        </MudPaper>
    </MudItem>
</MudGrid>

<MudGrid>
    <MudItem xs="12" md="7">
        <AdminEditorPanel Loading="@isLoadingSettings">
            <MudStack Row="true" AlignItems="AlignItems.Start" Justify="Justify.SpaceBetween" Class="admin-section-header compact">
                <div>
                    <MudText Typo="Typo.h6">사이트 정보</MudText>
                    <MudText Typo="Typo.body2">홈페이지와 문의 알림에 노출되는 기본 정보입니다.</MudText>
                </div>
            </MudStack>
            <MudForm>
                <MudTextField @bind-Value="form.Phone" Label="전화번호"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudTextField @bind-Value="form.Email" Label="이메일"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudTextField @bind-Value="form.KakaoUrl" Label="카카오채널 URL"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudTextField @bind-Value="form.InstagramUrl" Label="인스타그램"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudButton Variant="Variant.Filled" Color="Color.Primary"
                    StartIcon="@Icons.Material.Filled.Save"
                    @onclick="SaveSettings">사이트 정보 저장</MudButton>
            </MudForm>
        </AdminEditorPanel>
    </MudItem>

    <MudItem xs="12" md="5">
        <AdminEditorPanel Loading="@isLoadingSettings">
            <MudStack Row="true" AlignItems="AlignItems.Start" Justify="Justify.SpaceBetween" Class="admin-section-header compact">
                <div>
                    <MudText Typo="Typo.h6">계정 관리</MudText>
                    <MudText Typo="Typo.body2">비밀번호는 12자 이상으로 관리합니다.</MudText>
                </div>
            </MudStack>

            <MudForm>
                <MudTextField @bind-Value="passwordForm.CurrentPassword" Label="현재 비밀번호" InputType="InputType.Password"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudTextField @bind-Value="passwordForm.NewPassword" Label="새 비밀번호" InputType="InputType.Password"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudTextField @bind-Value="passwordForm.ConfirmNewPassword" Label="새 비밀번호 확인" InputType="InputType.Password"
                    Variant="Variant.Outlined" Class="mb-4" />

                <MudButton Variant="Variant.Filled" Color="Color.Primary"
                    Disabled="@isChangingPassword"
                    StartIcon="@Icons.Material.Filled.LockReset"
                    @onclick="ChangePassword">
                    @(isChangingPassword ? "변경 중..." : "비밀번호 변경")
                </MudButton>
            </MudForm>
        </AdminEditorPanel>
    </MudItem>
</MudGrid>

@code {
    private bool isChangingPassword;
    private bool isLoadingSettings;
    private SiteSettingsFormModel form = new()
    {
        Phone = "010-4122-8268",
        Email = "taxbaik5668@gmail.com",
        KakaoUrl = "http://pf.kakao.com/_xoxchTX",
        InstagramUrl = "https://www.instagram.com/taxtory5668/"
    };
    private PasswordChangeFormModel passwordForm = new();

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

    private async Task LoadSettingsAsync()
    {
        isLoadingSettings = true;

        try
        {
            var settings = await ApiClient.GetAsync<Dictionary<string, string>>("site-settings");
            if (settings is null || settings.Count == 0)
                return;

            if (settings.TryGetValue("PhoneNumber", out var loadedPhone) && !string.IsNullOrWhiteSpace(loadedPhone))
                form.Phone = loadedPhone;

            if (settings.TryGetValue("EmailAddress", out var loadedEmail) && !string.IsNullOrWhiteSpace(loadedEmail))
                form.Email = loadedEmail;

            if (settings.TryGetValue("KakaoChannelUrl", out var loadedKakao) && !string.IsNullOrWhiteSpace(loadedKakao))
                form.KakaoUrl = loadedKakao;

            if (settings.TryGetValue("InstagramUrl", out var loadedInstagram) && !string.IsNullOrWhiteSpace(loadedInstagram))
                form.InstagramUrl = loadedInstagram;
        }
        catch
        {
            Snackbar.Add("사이트 설정을 불러오지 못했습니다.", Severity.Warning);
        }
        finally
        {
            isLoadingSettings = false;
        }
    }

    private async Task SaveSettings()
    {
        if (isLoadingSettings)
            return;

        var response = await ApiClient.PutAsync<SaveSettingsResponse>("site-settings", new
        {
            Phone = form.Phone,
            Email = form.Email,
            KakaoUrl = form.KakaoUrl,
            InstagramUrl = form.InstagramUrl
        });

        if (response?.Message is null)
        {
            Snackbar.Add("설정 저장에 실패했습니다.", Severity.Error);
            return;
        }

        Snackbar.Add(response.Message, Severity.Success);
    }

    private async Task ChangePassword()
    {
        if (isChangingPassword)
            return;

        if (string.IsNullOrWhiteSpace(passwordForm.CurrentPassword) || string.IsNullOrWhiteSpace(passwordForm.NewPassword))
        {
            Snackbar.Add("현재 비밀번호와 새 비밀번호를 입력하세요.", Severity.Warning);
            return;
        }

        if (passwordForm.NewPassword != passwordForm.ConfirmNewPassword)
        {
            Snackbar.Add("새 비밀번호 확인이 일치하지 않습니다.", Severity.Warning);
            return;
        }

        isChangingPassword = true;

        try
        {
            var response = await ApiClient.PostAsync<ChangePasswordResponse>("auth/change-password", new
            {
                CurrentPassword = passwordForm.CurrentPassword,
                NewPassword = passwordForm.NewPassword
            });

            if (response?.Message == null)
            {
                Snackbar.Add("비밀번호 변경에 실패했습니다.", Severity.Error);
                return;
            }

            Snackbar.Add(response.Message, Severity.Success);
            passwordForm = new PasswordChangeFormModel();
        }
        catch
        {
            Snackbar.Add("비밀번호 변경 중 오류가 발생했습니다.", Severity.Error);
        }
        finally
        {
            isChangingPassword = false;
        }
    }

    private class ChangePasswordResponse
    {
        public string Message { get; set; } = "";
    }

    private class SaveSettingsResponse
    {
        public string Message { get; set; } = "";
    }
}
