@page "/UserManagement"
<ConfirmDialog @ref="dialog" />
@using Common.Dtos.Exper
@using HushianWebApp.Components
@using HushianWebApp.Service
@using HushianWebApp.Services
@inject ILocalStorageService localStorageService;
@inject NavigationManager navigationManager;
@inject UserService userService;
<Modal @ref="modal" />

<Button Color="ButtonColor.Success" Style="margin-bottom:10px"
@onclick="async()=>{
        await modal.ShowAsync<ADDExperComponent>(title,parameters:parameters);
        }">
    کارشناس جدید
</Button>

<Grid @ref="grid" TItem="Read_ExperDto"
AllowSorting="true"
Class="table table-hover"
DataProvider="DataProvider"
HeaderRowCssClass="bg-primary text-white bg-opacity-75 border-bottom-0"
Responsive="true"
AllowPaging="true"
OnRowDoubleClick="OnRowClick"
AllowRowClick=true>

    <GridColumns>
        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_ExperDto" HeaderText="نام کاریری" SortKeySelector="item => item.UserName">
            @context.UserName
        </GridColumn>

        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_ExperDto" HeaderText="نام کامل" SortKeySelector="item => item.FullName">
            @context.FullName
        </GridColumn>



        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_ExperDto" HeaderText="وضعیت">
            <Switch Value="@context.Available" ValueExpression="() => context.Available" ValueChanged="async(v)=>await SwitchChanged(context,v)" />

        </GridColumn>
        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_ExperDto" HeaderText="عملیات">
            <Button Color="ButtonColor.Danger" Size="ButtonSize.ExtraSmall" @onclick="async()=>await DeleteExper(context.ID,context.FullName)"> حذف </Button>
            <Button Color="ButtonColor.Warning" Size="ButtonSize.ExtraSmall" @onclick="async()=>await showGroupsComponent(context.ID,context.FullName)"> گروه ها </Button>

        </GridColumn> 
    </GridColumns>

</Grid>

@code {
    private ConfirmDialog dialog = default!;

    Dictionary<string, object> parameters = new Dictionary<string, object>();
    Grid<Read_ExperDto> grid = default!;
    public List<Read_ExperDto> list = new();
    private Modal modal = default!;
    string title = "کارشناس جدید";
    protected override async Task OnInitializedAsync()
    {
        parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create(this, CallBack));

        if (await localStorageService.GetItem<string>("C/Role")!= "Company" )
            navigationManager.NavigateTo("/NotFound");
        await base.OnInitializedAsync();
    }
    private async Task<GridDataProviderResult<Read_ExperDto>> DataProvider(GridDataProviderRequest<Read_ExperDto> request)
    {
        if (list.Count <= 0)
            list = await userService.GetExpersCompany();

        int skip = (request.PageNumber - 1) * request.PageSize;

        return await Task.FromResult(request.ApplyTo(list != null ? list.Skip(skip).Take(request.PageSize).ToList() : new()));
    }
    async Task CallBack()
    {
        await modal.HideAsync();
        await grid.RefreshDataAsync();
    }
    private async Task OnRowClick(GridRowEventArgs<Read_ExperDto> args)
    {
        var editmodel = new Update_ExperDto()
            {
                FullName = args.Item.FullName
            };
        Dictionary<string, object> eparameters = new Dictionary<string, object>();
        eparameters.Add("model", editmodel);
        eparameters.Add("ExperID", args.Item.ID);
        eparameters.Add("OnMultipleOfThree", EventCallback.Factory.Create(this, CallBack));

        await modal.ShowAsync<UpdateExperComponent>($"ویرایش کارشناس {args.Item.FullName}", parameters: eparameters);

    }
    private async Task SwitchChanged(Read_ExperDto model, bool value)
    {
        if (model.Available != value)
        {
            if (await userService.ChangeAvailableExperFromManager(model.ID, value))
                model.Available = value;
        }


    }
    private async Task DeleteExper(int ExperID,string name)
    {
        var confirmation = await dialog.ShowAsync(
           title: $"مطمئنی می‌خوای {name} حذف کنی؟",
           message1: "پس از حذف، نمی‌توان آن را به حالت اولیه برگرداند.",
           message2: "می‌خوای ادامه بدی؟",new ConfirmDialogOptions()
           {
               YesButtonColor=ButtonColor.Danger,
               YesButtonText="بله",
               NoButtonText="نه !"
           });

        if (!confirmation) return;


        if (await userService.DeleteExperFromManager(ExperID))
            await grid.RefreshDataAsync();
    }
    private string GetImageSource(byte[]? img)
    {
        if (img != null)
        {
            return $"data:image/jpeg;base64,{Convert.ToBase64String(img)}";
        }
        return string.Empty;
    }
    async Task showGroupsComponent(int ExperID, string name)
    {
        Dictionary<string, object> eparameters = new Dictionary<string, object>();
        eparameters.Add("ExperID", ExperID);

        modal.Size = ModalSize.Small;
        await modal.ShowAsync<UserGroupsComponent>($"گروه های کارشناس {name}", parameters: eparameters);
    }
}