@inherits LayoutComponentBase
@using Common.Dtos.Exper
@using HushianWebApp.Components
@using HushianWebApp.Pages
@using HushianWebApp.Pages.Manage
@using HushianWebApp.Service
@using HushianWebApp.Services
@inject NavigationManager NavigationManager
@inject ILocalStorageService localStorageService;
@inject AuthService authService;
@inject BaseController baseController;
@inject UserService userService;
<Modal @ref="modal" />
<Toasts class="p-3" AutoHide="true" Delay="4000" Placement="ToastsPlacement.TopRight" />
<div class="bb-page">
    <Sidebar @ref="sidebar"
    Href="/"
    IconName="IconName.BootstrapFill"
    Title="هوشــیان"
    BadgeText="v1.3.1"
    ImageSrc="/before/assets/images/logofilehushian.png"
    DataProvider="SidebarDataProvider"
    Width="200"
    WidthUnit="Unit.Px" />
    <main>
        <div class="d-flex align-items-center justify-content-end">
            <NavLink class="ms-4 text-end" href="@{
            hrefuserpanel
}">لینک گفتگو کاربر با شما</NavLink>
            <NavLink class="ms-4 text-end" href="@{
            hrefai
}">لینک گفتگو کاربر با دستیار هوش مصنوعی</NavLink>
<p class="mb-0 ms-4 text-end">شناسه شرکت : @CompanyID</p>
            <div class="text-white text-end d-flex flex-column justify-content-center align-items-end mx-2">
                <div style="color: black;" class="fw-bold">@Fullname</div>
                <h6 style="color: black;">@TitleRole</h6>
            </div>
            @if (img != null && img.Length > 0)
            {
                <Image Src=@GetImageSource() Class="rounded" Alt="placeholder" @onclick="EditCurrentUser"
                Style="height: 30px;cursor:pointer;margin-left:10px" />

            }
            else
            {
                <Icon Name="IconName.People" Size="IconSize.x3" Style="height: 30px;cursor:pointer;margin-left:10px" @onclick="EditCurrentUser" />
            }


            <Button Color="ButtonColor.Danger" Size="ButtonSize.Small"
            @onclick=OnCliclLogout Style="margin-left:10px">
                <Icon Name="IconName.DoorOpen" /> خروج
            </Button>



        </div>

        <article class="content px-4">
            <div class="py-2">
                @if (isonline)
                {
                    @if (isAuthorizedCompanyUser)
                    {
                        @Body
                    }
                    else
                    {
                        <p>دسترسی به شرکت برای شما یافت نشد</p>
                    }
                }

            </div>
        </article>
    </main>

</div>

@code {
    public string hrefuserpanel { get { return $"UserCP/{CompanyID}"; } }
    public string hrefai { get { return $"aichat/{CompanyID}"; } }
    private Modal modal = default!;
    public string Info { get; set; } = "";
    private string SelectedMenu = "page2";
    public string Username { get; set; }
    public string Fullname { get; set; }
    public int CompanyID { get; set; } = 0;
    public byte[]? img { get; set; }
    public string Role { get; set; }
    bool isonline = false;
    bool isAuthorizedCompanyUser = false;
    public string TitleRole { get; set; } = "";
    protected override async Task OnInitializedAsync()
    {
        Role = await localStorageService.GetItem<string>("C/Role");
        await CheckOnline();
        if (isonline)
        {
            //Roles = await localStorageService.GetItem<List<string>>("Role");
            Username = await localStorageService.GetItem<string>("C/Username");
            Fullname = await localStorageService.GetItem<string>("C/Fullname");
            CompanyID = await localStorageService.GetItem<int>("C/CompanyId");
            string UserID = await localStorageService.GetItem<string>("C/UserID");
            img = await localStorageService.GetItem<byte[]?>("C/img");
        }


        TitleRole = Role == "Company" ? "مدیر" : "کارشناس";

        isAuthorizedCompanyUser = Role == "Company" || Role == "Exper" && await userService.CheckAvailableExperInCompany();

        string route = NavigationManager.Uri.Replace(NavigationManager.BaseUri, "").ToLower();
        if (route.Length > 0)
        {
            SelectedMenu = route switch
            {
                "conversation" => "page2",
                "usermanagement" => "page3",
                "groupmanagement" => "page4",
                "settings" => "page5",
                _ => "page1"
            };

        }
        else SelectedMenu = "page1";


        await base.OnInitializedAsync();
    }
    async Task OnCliclLogout()
    {
        await authService.Logout();
        NavigationManager.NavigateTo("/login");
    }
    private async Task Settings()
    {
        var parameters = new Dictionary<string, object>();
        await modal.ShowAsync<Settings>(title: "تنظیمات شرکت", parameters: parameters);

    }
    private async Task EditCurrentUser()
    {
        if (Role == "Exper")
        {
            var parameters = new Dictionary<string, object>();
            parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<Update_ExperDto>(this, CallBack));

            await modal.ShowAsync<EditUserYourselfComponent>(title: $"ویرایش کاربر {Username}", parameters: parameters);
        }


    }
    async Task CallBack(Update_ExperDto edit)
    {
        await modal.HideAsync();
        // await localStorageService.RemoveItem("img");
        // await localStorageService.SetItem("img", img);

        Fullname = edit.FullName;
        await localStorageService.RemoveItem("C/Fullname");
        await localStorageService.SetItem("C/Fullname", Fullname);

    }
    private void SetActiveMenu(string menu)
    {
        SelectedMenu = menu;

        if (menu == "page1") NavigationManager.NavigateTo("/");

        else if (menu == "page2") NavigationManager.NavigateTo("/Conversation");

        else if (menu == "page3") NavigationManager.NavigateTo("/UserManagement");

        else if (menu == "page4") NavigationManager.NavigateTo("/GroupManagement");

        else if (menu == "page5") NavigationManager.NavigateTo("/Settings");

    }

    async Task CheckOnline()
    {
        var token = await localStorageService.GetItem<string>("C/key");
        if (string.IsNullOrEmpty(token))
        {
            isonline = false;
            NavigationManager.NavigateTo("/login");
        }
        else
        {
            await baseController.RemoveToken();
            await baseController.SetToken(token);
            if (!await authService.IsOnline())
            {
                await baseController.RemoveToken();
                isonline = false;
                NavigationManager.NavigateTo("/login");
            }
            else
            {
                Role = await localStorageService.GetItem<string>("C/Role");
                if (Role == "User")
                {
                    isonline = false;
                    NavigationManager.NavigateTo("/NotFound");
                }
                else
                    isonline = true;

            }
        }

    }
    private string GetImageSource()
    {
        if (img != null && img.Length > 0)
        {
            return $"data:image/jpeg;base64,{Convert.ToBase64String(img)}";
        }
        return "/defprofile.jpg";
    }
}

@code {
    Sidebar sidebar = default!;
    IEnumerable<NavItem>? navItems;

    private async Task<SidebarDataProviderResult> SidebarDataProvider(SidebarDataProviderRequest request)
    {
        if (navItems is null)
            navItems = GetNavItems();

        return await Task.FromResult(request.ApplyTo(navItems));
    }

    private IEnumerable<NavItem> GetNavItems()
    {
        if (Role == "Exper")
            navItems = new List<NavItem>
            {
            new NavItem { Href = "/", IconName = IconName.ChatText, Text = "  گفتگو ها"},
            new NavItem { Href = "/Settings", IconName = IconName.Hammer, Text = " تنظیمات"},
            };

        else if (Role == "Company")
            navItems = new List<NavItem>{
            new NavItem { Href = "/", IconName = IconName.ChatText, Text = "  گفتگو ها"},
            new NavItem { Href = "/UserManagement", IconName = IconName.PersonBoundingBox, Text = " مدیریت کاربران"},
            new NavItem { Href = "/GroupManagement", IconName = IconName.Grid1X2, Text = " مدیریت گروه ها"},
            new NavItem { Href = "/Settings", IconName = IconName.Hammer, Text = " تنظیمات"},
            };

        else navItems = new List<NavItem>();


        return navItems;
    }

    private void ToggleSidebar() => sidebar.ToggleSidebar();
}