@page "/admin/contracts"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@using TaxBaik.WasmClient.Components.Admin.Shared
@inject IContractBrowserClient ContractClient
@inject IClientBrowserClient ClientClient
@inject ISnackbar Snackbar
@inject IDialogService DialogService
@attribute [Authorize]

<PageTitle>계약 관리</PageTitle>

<AdminPageHeader Title="계약 관리" Eyebrow="CRM & 세무관리" Subtitle="고객 계약과 월 정기수익을 함께 관리합니다.">
    <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
        @if (mrr > 0)
        {
            <MudChip T="string" Size="Size.Small" Color="Color.Primary" Variant="Variant.Filled">월 정기수익 ₩@mrr.ToString("N0")</MudChip>
        }
        <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="PrepareCreate" StartIcon="@Icons.Material.Filled.Add" id="btn-add-contract">
            새 계약 추가
        </MudButton>
    </MudStack>
</AdminPageHeader>

<AdminEditorPanel Loading="@(contracts is null)" SkeletonContent="@ContractSkeleton">
@if (contracts is null)
{
}
else
{
    <MudGrid Spacing="2" Class="mt-2">
        <!-- Left: Dense Grid List -->
        <MudItem XS="12" MD="8">
            @if (contracts.Count == 0)
            {
                <MudAlert Severity="Severity.Info">
                    <MudIcon Icon="@Icons.Material.Filled.Description" Class="me-2" />
                    계약이 없습니다.
                </MudAlert>
            }
            else
            {
                <MudDataGrid T="Contract" Items="@contracts" Dense="true" Hover="true" Striped="true" Class="admin-grid mt-4">
                    <Columns>
                        <PropertyColumn Property="x => x.Id" Title="ID" Sortable="true" Class="admin-table-id-column" />
                        <TemplateColumn Title="고객" Sortable="true">
                            <CellTemplate>
                                @clientMap.GetValueOrDefault(context.Item.ClientId)
                            </CellTemplate>
                        </TemplateColumn>
                        <PropertyColumn Property="x => x.ContractNumber" Title="계약번호" Sortable="true" />
                        <PropertyColumn Property="x => x.ServiceType" Title="서비스 유형" Sortable="true" />
                        <PropertyColumn Property="x => x.MonthlyFee" Title="월 수수료" Sortable="true" Format="C" />
                        <TemplateColumn Title="계약기간" Sortable="true">
                            <CellTemplate>
                                @context.Item.StartDate.ToString("yyyy-MM-dd")
                                @if (context.Item.EndDate.HasValue)
                                {
                                    <span>~@context.Item.EndDate.Value.ToString("yyyy-MM-dd")</span>
                                }
                            </CellTemplate>
                        </TemplateColumn>
                        <TemplateColumn Title="상태" Sortable="true">
                            <CellTemplate>
                                @(context.Item.EndDate.HasValue && context.Item.EndDate.Value < DateTime.Today ? "만료" : "활성")
                            </CellTemplate>
                        </TemplateColumn>
                        <TemplateColumn Title="작업" CellStyleFunc="@(_ => "text-align: right;")">
                            <CellTemplate>
                                <MudButtonGroup Size="Size.Small" Variant="Variant.Text">
                                    <MudButton Color="Color.Primary" OnClick="@(() => OnRowSelected(context.Item))">선택</MudButton>
                                    <MudButton Color="Color.Error" OnClick="@(() => DeleteContract(context.Item.Id))">삭제</MudButton>
                                </MudButtonGroup>
                            </CellTemplate>
                        </TemplateColumn>
                    </Columns>
                </MudDataGrid>
            }
        </MudItem>

        <!-- Right: Detail Form Panel (Inline Editor) -->
        <MudItem XS="12" MD="4">
            <AdminEditorPanel Loading="false">
                <div class="d-flex align-center justify-space-between mb-4">
                    <MudText Typo="Typo.h6" Class="font-weight-bold">@(isEditMode ? "계약 상세 정보" : "새 계약 추가")</MudText>
                    @if (isEditMode)
                    {
                        <MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Secondary" OnClick="PrepareCreate">
                            새로 작성
                        </MudButton>
                    }
                </div>
                <MudForm @ref="form">
                    <div class="mb-3">
                        <label class="mud-input-label mud-input-label-animated mud-input-label-outlined mb-1">고객</label>
                        <select class="mud-input mud-input-outlined mud-input-root mud-input-root-adorned-start admin-native-select"
                                value="@(contractForm.ClientId?.ToString() ?? string.Empty)"
                                disabled="@isEditMode"
                                @onchange="e => contractForm.ClientId = int.TryParse(e.Value?.ToString(), out var clientId) ? clientId : null">
                            <option value="">고객을 선택하세요.</option>
                            @foreach (var client in clients)
                            {
                                <option value="@client.Id">@GetClientDisplayName(client)</option>
                            }
                        </select>
                    </div>
                    <MudTextField T="string" @bind-Value="contractForm.ContractNumber" Label="계약번호" Variant="Variant.Outlined" FullWidth="@true" Class="mb-3" Required="true" />
                    <CommonCodeSelect @bind-Value="contractForm.ServiceType" Group="CONTRACT_SERVICE_TYPE" Label="서비스 유형" Class="mb-3" Required="true" />
                    <MudTextField T="string" Label="계약 시작일" Variant="Variant.Outlined" FullWidth="@true" Class="mb-3" Required="true" Value="@(contractForm.StartDate?.ToString("yyyy-MM-dd") ?? string.Empty)" />
                    <MudNumericField T="decimal?" @bind-Value="contractForm.MonthlyFee" Label="월 수수료" Variant="Variant.Outlined" FullWidth="@true" Class="mb-4" />
                    
                    <div class="d-flex justify-end gap-2">
                        @if (isEditMode)
                        {
                            <MudButton Variant="Variant.Outlined" Color="Color.Error" OnClick="@(async () => await DeleteContract(selectedContract?.Id ?? 0))">삭제</MudButton>
                        }
                        else
                        {
                            <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="SaveContract" id="btn-save-contract">저장</MudButton>
                        }
                    </div>
                </MudForm>
            </AdminEditorPanel>
        </MudItem>
    </MudGrid>
}
</AdminEditorPanel>

@code {
    [CascadingParameter]
    private Task<AuthenticationState>? AuthStateTask { get; set; }

    private List<Contract>? contracts;
    private List<Client> clients = [];
    private Dictionary<int, string> clientMap = new();
    private decimal mrr = 0;
    private MudForm? form;
    private bool isEditMode;
    private Contract? selectedContract;
    private ContractFormModel contractForm = new();

    private RenderFragment ContractSkeleton => builder =>
    {
        builder.OpenComponent<AdminSkeletonRows>(0);
        builder.AddAttribute(1, "Rows", 6);
        builder.AddAttribute(2, "Columns", 4);
        builder.CloseComponent();
    };

    protected override async Task OnInitializedAsync()
    {
        if (AuthStateTask != null)
        {
            var authState = await AuthStateTask;
            if (authState.User.Identity?.IsAuthenticated == true)
            {
                await LoadData();
                PrepareCreate();
            }
            else
            {
                contracts = [];
            }
        }
        else
        {
            contracts = [];
        }
    }

    private async Task LoadData()
    {
        try
        {
            contracts = await ContractClient.GetAllAsync();
            var (clientItems, _) = await ClientClient.GetPagedAsync(pageSize: 1000);
            clients = clientItems.ToList();
            clientMap = clients.ToDictionary(c => c.Id, GetClientDisplayName);
            mrr = await ContractClient.GetMonthlyRecurringRevenueAsync();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"데이터 로드 실패: {ex.Message}", Severity.Error);
        }
    }

    private void PrepareCreate()
    {
        selectedContract = null;
        isEditMode = false;
        contractForm = new ContractFormModel
        {
            ClientId = clients.FirstOrDefault()?.Id,
            StartDate = DateTime.Today
        };
    }

    private void OnRowSelected(Contract contract)
    {
        if (contract == null) return;
        selectedContract = contract;
        isEditMode = true;
        contractForm = new ContractFormModel
        {
            ClientId = contract.ClientId,
            ContractNumber = contract.ContractNumber,
            ServiceType = contract.ServiceType,
            StartDate = contract.StartDate,
            MonthlyFee = contract.MonthlyFee
        };
    }

    private async Task SaveContract()
    {
        if (form != null)
        {
            await form.ValidateAsync();
            if (!form.IsValid)
            {
                Snackbar.Add("필수 항목을 입력해주세요.", Severity.Warning);
                return;
            }
        }

        try
        {
            if (contractForm.ClientId == null) return;
            var newId = await ContractClient.CreateAsync(
                contractForm.ClientId.Value,
                contractForm.ContractNumber,
                contractForm.ServiceType,
                contractForm.StartDate ?? DateTime.Now,
                contractForm.MonthlyFee);

            if (newId > 0)
            {
                Snackbar.Add("계약이 추가되었습니다.", Severity.Success);
                PrepareCreate();
                await LoadData();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"저장 실패: {ex.Message}", Severity.Error);
        }
    }

    private async Task DeleteContract(int id)
    {
        var parameters = new DialogParameters
        {
            { "Title", "삭제 확인" },
            { "Message", "이 계약을 삭제하시겠습니까?" }
        };

        var dialog = await DialogService.ShowAsync<ConfirmDialog>("", parameters);
        var result = await dialog.Result;

        if (result?.Canceled ?? true)
            return;

        try
        {
            await ContractClient.DeleteAsync(id);
            Snackbar.Add("계약이 삭제되었습니다.", Severity.Success);
            if (selectedContract?.Id == id)
            {
                PrepareCreate();
            }
            await LoadData();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"삭제 실패: {ex.Message}", Severity.Error);
        }
    }

    private static string GetClientDisplayName(Client client)
        => !string.IsNullOrWhiteSpace(client.CompanyName)
            ? client.CompanyName
            : !string.IsNullOrWhiteSpace(client.Name)
                ? client.Name
                : $"Client #{client.Id}";

}
