@using Common.Dtos.Company
@using Common.Dtos.Conversation
@using Common.Dtos.Group
@using HushianWebApp.Components.UserPanel
@using HushianWebApp.Service
@using HushianWebApp.Services
@inject IJSRuntime JSRuntime
@inject CompanyService companyService
@inject GroupService groupService
@inject ILocalStorageService localStorageService;
@inject AuthService authService;
@inject BaseController baseController;
@inject ConversationService conversationService
@layout UserPanelLayout
@page "/ZUserPanel/{CompanyID:int}"
@page "/ZUserPanel/{CompanyID:int}/{ConversationID:int?}"

<div class="card shadow chat-box-expanded">
    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
        <span>
            <strong>@CompanyName / @groups.FirstOrDefault(f => f.ID == SelectedGroup)?.Name / @SelectedConversation?.ExperFullName</strong><br />
            <Badge Color="BadgeColor.Danger"
            Position="Position.Absolute"
            Placement="BadgePlacement.TopRight"
            IndicatorType="BadgeIndicatorType.RoundedPill"
            VisuallyHiddenText="status"></Badge>
            <small>پاسخگویی سوالات شما هستیم</small>
        </span>
        @if (ConversationID.HasValue)
        {
            <button class="btn-close btn-close-white" @onclick="CloseChat"></button>
        }
    </div>
    <div class="card-body" style="max-height: 500px; overflow-y: auto; background-color: #f9f9f9;">
        @if (!IsFisrLoding)
        {
            @if (!IsLogin)
            {
                <LoginComponent OnMultipleOfThree="EventCallback.Factory.Create(this, Login)" />
            }
            @if (IsLogin)
            {
                @if (SelectedConversation == null)
                {
                    <button class="btn btn-outline-secondary btn-sm mt-2"
                    @onclick="()=> {SelectedGroup=0; StateHasChanged();}" style="margin-left:5px;margin-bottom:5px">
                        شرکت  @CompanyName (@CountQueueCompany)
                    </button>
                    @GCContent

                    @if (Conversations.Count > 0)
                    {
                        @ConversationsContent
                    }


                }
                else
                {
                    <ChatBoxComponent SelectedConversationItems="SelectedConversationItems" />
                }



            }

        }
        else
        {
            <div class="d-flex justify-content-center">
                <Spinner Class="me-3" Type="SpinnerType.Dots" Color="SpinnerColor.Primary" Visible="@IsFisrLoding" />

            </div>

        }
    </div>
    @if (IsLogin && (@* Conversations.Count == 0 && *@ SelectedConversation == null) || (@* Conversations.Count > 0 &&  *@ SelectedConversation != null && (SelectedConversation.status != Common.Enums.ConversationStatus.Finished)))
    {
        <div class="card-header text-white d-flex justify-content-between align-items-center">
            <input type="text" class="form-control" @bind-value="InputMessage" placeholder="پیام خود را بنویسید..." style="margin-left:10px" />

            <Button Color="ButtonColor.Dark" Outline="true"><Icon Name="IconName.AppIndicator" @onclick="OnClickSendMssage" /> </Button>


        </div>
    }

</div>
<style>
    .chat-box-expanded {
    position: fixed;
    bottom: 50%;
    right: 50%;
    transform: translate(50%, 50%);
    width: 90vw;
    height: 80%;
    z-index: 1051;
    transition: all 0.3s ease;
    }

</style>
@code {
    #region Parameter
    [Parameter] public int CompanyID { get; set; }
    [Parameter] public int? ConversationID { get; set; }
    #endregion
    #region Fild
    public Read_ConversationDto? SelectedConversation { get; set; } = null;
    public List<Read_ConversationDto> Conversations { get; set; } = new();
    public List<Read_ConversationResponseDto>? SelectedConversationItems { get; set; } = null;
    public RenderFragment GCContent { get; set; }
    public RenderFragment ConversationsContent { get; set; }
    List<Read_GroupDto> groups = new List<Read_GroupDto>();
    public ReadANDUpdate_CompanyDto company { get; set; } = new();
    int CountQueueCompany = 0;
    public string CompanyName { get; set; } = "هوشیان";
    public bool IsLogin { get; set; } = false;
    public bool IsFisrLoding { get; set; } = true;
    public int? SelectedGroup { get; set; }
    public string InputMessage { get; set; }
    public bool Sending { get; set; } = false;


    #endregion
}
@functions {

    protected override async Task OnParametersSetAsync()
    {
        // if (ConversationID.HasValue && ConversationID > 0 && Conversations.Count > 0)
        //     await SelectedConv(ConversationID.Value);

        await base.OnParametersSetAsync();
    }
    protected override async Task OnInitializedAsync()
    {
        IsFisrLoding = true;
        await CheckOnline();
        IsFisrLoding = false;
        await base.OnInitializedAsync();
    }
    async Task CheckOnline()
    {
        var token = await localStorageService.GetItem<string>("U/key");
        if (string.IsNullOrEmpty(token))
        {
            IsLogin = false;
        }
        else
        {
            await baseController.RemoveToken();
            await baseController.SetToken(token);
            if (!await authService.IsOnline())
            {
                await baseController.RemoveToken();
                IsLogin = false;
            }
            else
            {
                IsLogin = true;
                await Login();
            }

        }

    }
    async Task CallBackSelectedGroup(int ID)
    {
        SelectedGroup = ID;
        StateHasChanged();
    }
    async Task Login()
    {
        // اینجا منطق ورود کاربر را پیاده‌سازی کنید
        IsLogin = true;
        var _company = await companyService.GetCompany(CompanyID);
        if (_company == null)
        {
            // not Founf Company
        }
        else
        {
            if (!_company.Available)
            {
                // not Available Company
            }
            else
            {
                CompanyName = _company.FullName;
                company = _company;

                var _groups = await groupService.GetGroupsCompany(CompanyID);
                if (_groups != null)
                {
                    CountQueueCompany = await conversationService.GetCountQueueCompany(CompanyID);
                    groups = _groups;
                    GCContent =@<GCComponent groups="groups"
             CompanyID=CompanyID
             OnMultipleOfThree="EventCallback.Factory.Create<int>(this, CallBackSelectedGroup)" />
    ;

                }
                else
                {
                    // ex Groups Company
                }
                Conversations = await conversationService.MyConversationUserSide(CompanyID);
                if (Conversations.Count > 0)
                    ConversationsContent =@<ConversionHistoryComponent Conversations="Conversations"
                            OnMultipleOfThree="EventCallback.Factory.Create<int>(this, SelectedConv)" />
    ;

                if (ConversationID.HasValue && ConversationID > 0 && Conversations.Count > 0)
                    await SelectedConv(ConversationID.Value);
            }

        }
        StateHasChanged();
    }
    async Task SelectedConv(int ID)
    {

        if (Conversations.Any(f => f.ID == ID))
        {
            SelectedConversation = Conversations.FirstOrDefault(f => f.ID == ID);
            SelectedConversationItems = await conversationService.GetConversationItems(ID);
            SelectedGroup = SelectedConversation.GroupID;
            ConversationID = ID;
            StateHasChanged();
        }

    }
    private void CloseChat()
    {
        // می‌توان اینجا حالت مخفی‌سازی کامپوننت را تنظیم کرد
        SelectedConversation = null;
        SelectedConversationItems = null;
        SelectedGroup = null;
        ConversationID = null;
        StateHasChanged();
    }
    private void GoBack()
    {
        // برگشت به منوی قبلی یا وضعیت قبلی
    }
    async Task OnClickSendMssage()
    {

        if (string.IsNullOrEmpty(InputMessage)) return;
        Sending = true;
        if (SelectedConversation != null)
        {
            var item = new ADD_ConversationResponseDto()
                {
                    ConversationID = SelectedConversation.ID,
                    Text = InputMessage
                };
            var inputconv= await conversationService.ADDConversationItem(SelectedConversation.ID, InputMessage, Common.Enums.ConversationType.UE);
            if (inputconv!=null) SelectedConversationItems.Add(inputconv);

        }
        else
        {
            var Item = new ADD_ConversationDto()
                {
                    CompanyID = CompanyID,
                    GroupID = SelectedGroup,
                    Question = InputMessage
                };
            var convNEW= await conversationService.NewConversationFromCurrentUser(Item);
            if (convNEW !=null)
            {
                Conversations.Add(convNEW);
                await SelectedConv(convNEW.ID);
            }

        }
        InputMessage = string.Empty;
        Sending = false;
    }
}



