@page "/admin/inquiries/{InquiryId:int}"
@attribute [Authorize]
@using TaxBaik.Web.Services
@inject IInquiryBrowserClient InquiryClient
@inject NavigationManager Navigation
@inject ISnackbar Snackbar

<PageTitle>문의 상세</PageTitle>

<section class="admin-page-hero">
    <div>
        <MudText Typo="Typo.caption" Class="admin-eyebrow">Inquiry Details</MudText>
        <MudText Typo="Typo.h4" Class="admin-page-title">문의 상세</MudText>
        <MudText Typo="Typo.body2" Class="admin-page-subtitle">문의 정보를 확인하고 처리 상태를 관리합니다.</MudText>
    </div>
</section>

@if (inquiry != null)
{
    <MudButton Variant="Variant.Outlined"
               Color="Color.Primary"
               StartIcon="@Icons.Material.Filled.ArrowBack"
               @onclick="@(() => Navigation.NavigateTo("/taxbaik/admin/inquiries"))">
        문의 목록으로
    </MudButton>

    <MudGrid Class="mt-4">
        <MudItem xs="12" md="8">
            <AdminDetailSection Title="문의 정보">
                <MudGrid>
                    <MudItem xs="12" sm="6">
                        <MudText Typo="Typo.subtitle2" Color="Color.Secondary">이름</MudText>
                        <MudText>@inquiry.Name</MudText>
                    </MudItem>
                    <MudItem xs="12" sm="6">
                        <MudText Typo="Typo.subtitle2" Color="Color.Secondary">연락처</MudText>
                        <MudText>@inquiry.Phone</MudText>
                    </MudItem>
                    <MudItem xs="12" sm="6">
                        <MudText Typo="Typo.subtitle2" Color="Color.Secondary">이메일</MudText>
                        <MudText>@(inquiry.Email ?? "-")</MudText>
                    </MudItem>
                    <MudItem xs="12" sm="6">
                        <MudText Typo="Typo.subtitle2" Color="Color.Secondary">분야</MudText>
                        <MudText>@inquiry.ServiceType</MudText>
                    </MudItem>
                    <MudItem xs="12">
                        <MudText Typo="Typo.subtitle2" Color="Color.Secondary">문의 내용</MudText>
                        <MudPaper Class="pa-3 mt-1" Outlined="true">
                            <MudText Style="white-space: pre-wrap;">@inquiry.Message</MudText>
                        </MudPaper>
                    </MudItem>
                    <MudItem xs="12">
                        <MudText Typo="Typo.subtitle2" Color="Color.Secondary">접수일시</MudText>
                        <MudText>@inquiry.CreatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm")</MudText>
                    </MudItem>
                </MudGrid>
            </AdminDetailSection>

            <AdminDetailSection Title="담당자 메모" CssClass="pa-4 mt-4">
                <MudTextField T="string" @bind-Value="adminMemo" Label="내부 메모 (고객에게 미노출)"
                              Lines="4" Variant="Variant.Outlined" />
                <MudButton Class="mt-2" Variant="Variant.Filled" Color="Color.Primary"
                           OnClick="SaveMemo">메모 저장</MudButton>
            </AdminDetailSection>
        </MudItem>

        <MudItem xs="12" md="4">
            <AdminDetailSection Title="처리 상태">
                <MudStack Spacing="2">
                    @foreach (var (key, label) in InquiryStatusMapper.Labels)
                    {
                        <MudButton Variant="@(inquiry.Status == key ? Variant.Filled : Variant.Outlined)"
                                   Color="@StatusColor(key)"
                                   FullWidth="true"
                                   OnClick="@(() => OnStatusChanged(key))">
                            @label
                        </MudButton>
                    }
                </MudStack>
            </AdminDetailSection>

            @if (inquiry.ClientId == null)
            {
                <AdminDetailSection Title="고객 카드 생성" CssClass="pa-4 mt-4">
                    <MudText Typo="Typo.body2" Class="mb-3">이 문의를 고객 카드로 등록합니다.</MudText>
                    <MudButton Variant="Variant.Filled" Color="Color.Success" FullWidth="true"
                               OnClick="ConvertToClient">
                        고객으로 등록
                    </MudButton>
                </AdminDetailSection>
            }
            else
            {
                <AdminDetailSection Title="연결된 고객" CssClass="pa-4 mt-4">
                    <MudButton Variant="Variant.Outlined" Color="Color.Primary" FullWidth="true"
                               Href="@($"/taxbaik/admin/clients/{inquiry.ClientId}")">
                        고객 카드 보기
                    </MudButton>
                </AdminDetailSection>
            }
        </MudItem>
    </MudGrid>
}
else
{
    <MudText>문의를 찾을 수 없습니다.</MudText>
}

@code {
    [Parameter]
    public int InquiryId { get; set; }

    private Domain.Entities.Inquiry? inquiry;
    private string adminMemo = "";

    protected override async Task OnInitializedAsync()
    {
        inquiry = await InquiryClient.GetByIdAsync(InquiryId);
        adminMemo = inquiry?.AdminMemo ?? "";
    }

    private async Task OnStatusChanged(string status)
    {
        if (inquiry == null) return;
        try
        {
            var success = await InquiryClient.UpdateStatusAsync(inquiry.Id, status);
            if (success)
            {
                inquiry.Status = status;
                Snackbar.Add("상태가 변경되었습니다.", Severity.Success);
            }
            else
            {
                Snackbar.Add("상태 변경에 실패했습니다.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
        }
    }

    private async Task SaveMemo()
    {
        if (inquiry == null) return;
        try
        {
            var success = await InquiryClient.UpdateAdminMemoAsync(inquiry.Id, adminMemo);
            if (success)
            {
                inquiry.AdminMemo = adminMemo;
                Snackbar.Add("메모가 저장되었습니다.", Severity.Success);
            }
            else
            {
                Snackbar.Add("메모 저장에 실패했습니다.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
        }
    }

    private async Task ConvertToClient()
    {
        if (inquiry == null) return;
        try
        {
            var clientId = await InquiryClient.ConvertToClientAsync(
                inquiry.Id,
                inquiry.Name,
                inquiry.Phone,
                inquiry.ServiceType);

            if (clientId > 0)
            {
                inquiry.ClientId = clientId;
                inquiry.Status = "consulting";
                Snackbar.Add("고객 카드가 생성되었습니다.", Severity.Success);
            }
            else
            {
                Snackbar.Add("고객 카드 생성에 실패했습니다.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
        }
    }

    private Color StatusColor(string status) => status switch
    {
        "new"        => Color.Default,
        "consulting" => Color.Info,
        "contracted" => Color.Success,
        "rejected"   => Color.Error,
        "closed"     => Color.Dark,
        _            => Color.Default
    };
}
