@using Indotalent.Features.Pipeline.Campaign.Cqrs
@using Indotalent.Features.Pipeline.Campaign.Components
@using MudBlazor
@using Indotalent.ConfigBackEnd.Extensions
@inject CampaignService CampaignService
@inject ISnackbar Snackbar

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
    <div class="d-flex align-center gap-4">
        <MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
        <div>
            <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "Campaign Details" : "Edit Campaign")</MudText>
            <MudText Typo="Typo.body2" Style="color: #64748b;">Manage campaign specifications and financial tracking.</MudText>
        </div>
    </div>
</MudPaper>

<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
    @if (_isDataLoading)
    {
        <div class="d-flex justify-center pa-10"><MudProgressCircular Color="Color.Primary" Indeterminate="true" /></div>
    }
    else
    {
        <MudForm @ref="_form" Model="_model">
            <MudGrid Spacing="3">
                <MudItem xs="12">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Campaign Title</MudText>
                    <MudTextField @bind-Value="_model.Title" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
                </MudItem>
                <MudItem xs="12" sm="6">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Sales Team</MudText>
                    <MudSelect T="string" @bind-Value="_model.SalesTeamId" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter" FullWidth="true">
                        @foreach (var item in _lookup.SalesTeams)
                        {
                            <MudSelectItem Value="@item.Id">@item.Name</MudSelectItem>
                        }
                    </MudSelect>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Status</MudText>
                    <MudSelect T="Indotalent.Data.Enums.CampaignStatus" @bind-Value="_model.Status" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter" FullWidth="true">
                        @foreach (var item in _lookup.Statuses)
                        {
                            <MudSelectItem Value="@((Indotalent.Data.Enums.CampaignStatus)item.Value)">@item.Name</MudSelectItem>
                        }
                    </MudSelect>
                </MudItem>

                <MudItem xs="12" sm="6">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Start Date</MudText>
                    <MudDatePicker @bind-Date="_model.CampaignDateStart" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
                </MudItem>

                <MudItem xs="12" sm="6">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Finish Date</MudText>
                    <MudDatePicker @bind-Date="_model.CampaignDateFinish" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
                </MudItem>

                <MudItem xs="12" sm="6">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Target Revenue</MudText>
                    <MudNumericField @bind-Value="_model.TargetRevenueAmount" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" T="decimal?" HideSpinButtons="true" />
                </MudItem>

                <MudItem xs="12">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
                    <MudTextField @bind-Value="_model.Description" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" Lines="3" FullWidth="true" />
                </MudItem>

                <MudItem xs="12" Class="mt-6">
                    <MudTabs Elevation="0" Outlined="true" Position="Position.Top" Rounded="false" Border="true" ApplyEffectsToContainer="true">
                        <MudTabPanel Text="Budgets">
                            <div class="pa-4">
                                <_BudgetDataTable CampaignId="@_model.Id" Items="_budgets" Lookup="_lookup" ReadOnly="ReadOnly" OnChanged="RefreshDetails" />
                            </div>
                        </MudTabPanel>
                        <MudTabPanel Text="Expenses">
                            <div class="pa-4">
                                <_ExpenseDataTable CampaignId="@_model.Id" Items="_expenses" Lookup="_lookup" ReadOnly="ReadOnly" OnChanged="RefreshDetails" />
                            </div>
                        </MudTabPanel>
                    </MudTabs>
                </MudItem>

                <MudItem xs="12" Class="mt-4"><MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Audit History</MudText><MudDivider Class="mt-2 mb-4" /></MudItem>
                <MudItem xs="12" sm="6"><MudText Typo="Typo.subtitle2">Created At</MudText><MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText></MudItem>
                <MudItem xs="12" sm="6"><MudText Typo="Typo.subtitle2">Created By</MudText><MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText></MudItem>
                <MudItem xs="12" sm="6"><MudText Typo="Typo.subtitle2">Last Updated At</MudText><MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.UpdatedAt)</MudText></MudItem>
                <MudItem xs="12" sm="6"><MudText Typo="Typo.subtitle2">Last Updated By</MudText><MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.UpdatedBy) ? _model.UpdatedBy : "System")</MudText></MudItem>
            </MudGrid>

            <div class="d-flex justify-end gap-2 mt-10">
                <MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">
                    @(ReadOnly ? "Back to List" : "Cancel")
                </MudButton>
                @if (!ReadOnly)
                {
                    <MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
                        @if (_processing)
                        {
                            <MudProgressCircular Size="Size.Small" Indeterminate="true" Class="ms-n1" />
                            <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Updating...</MudText>
                        }
                        else
                        {
                            <MudText>Save Changes</MudText>
                        }
                    </MudButton>
                }
            </div>
        </MudForm>
    }
</MudPaper>

@code {
    [Parameter] public UpdateCampaignRequest Data { get; set; } = new();
    [Parameter] public bool ReadOnly { get; set; } = false;
    [Parameter] public EventCallback OnCancel { get; set; }
    [Parameter] public EventCallback OnSuccess { get; set; }
    private MudForm _form = default!;
    private UpdateCampaignRequest _model = new();
    private CampaignLookupResponse _lookup = new();
    private List<CampaignBudgetResponse> _budgets = new();
    private List<CampaignExpenseResponse> _expenses = new();
    private bool _processing = false;
    private bool _isDataLoading = true;

    protected override async Task OnInitializedAsync()
    {
        _isDataLoading = true;
        try
        {
            var resLookup = await CampaignService.GetLookupDataAsync();
            if (resLookup != null && resLookup.IsSuccess)
            {
                _lookup = resLookup.Value!;
            }

            var resDetail = await CampaignService.GetCampaignByIdAsync(Data.Id!);
            if (resDetail != null && resDetail.IsSuccess)
            {
                var d = resDetail.Value!;
                _model = new UpdateCampaignRequest
                {
                    Id = d.Id,
                    Title = d.Title,
                    Description = d.Description,
                    TargetRevenueAmount = d.TargetRevenueAmount,
                    CampaignDateStart = d.CampaignDateStart,
                    CampaignDateFinish = d.CampaignDateFinish,
                    Status = d.Status,
                    SalesTeamId = d.SalesTeamId,
                    CreatedAt = d.CreatedAt,
                    CreatedBy = d.CreatedBy,
                    UpdatedAt = d.UpdatedAt,
                    UpdatedBy = d.UpdatedBy
                };
                
                _budgets = d.Budgets;
                _expenses = d.Expenses;
            }
        }
        finally
        {
            _isDataLoading = false;
        }
    }

    private async Task RefreshDetails()
    {
        var res = await CampaignService.GetCampaignByIdAsync(_model.Id!);
        if (res != null && res.IsSuccess)
        {
            _budgets = res.Value!.Budgets;
            _expenses = res.Value!.Expenses;
            
            _model.CreatedAt = res.Value.CreatedAt;
            _model.CreatedBy = res.Value.CreatedBy;
            _model.UpdatedAt = res.Value.UpdatedAt;
            _model.UpdatedBy = res.Value.UpdatedBy;
        }
    }

    private async Task Submit()
    {
        await _form.Validate();
        if (!_form.IsValid) return;

        _processing = true;
        try
        {
            var response = await CampaignService.UpdateCampaignAsync(_model);
            await Task.Delay(500);

            if (response != null && response.IsSuccess)
            {
                Snackbar.Add("Campaign updated successfully", Severity.Success);
                await OnSuccess.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Error: {ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }
}