@page "/"
@inject NavigationManager NavigationManager
@inject IRestWrapper RestWrapper
@inject ISnackbar Snackbar
@inject ILocalStorageService LocalStorage
@inject IUserUtility UserUtility

<style>
    .mud-input-label {
        background-color: #FFFBE6;
    }

    /*     .secondary-border>.mud-input-control-input-container>.mud-input.mud-input-outlined>input:focus~.mud-input-outlined-border {
                                border-color: #FD5523;
                                color: white;
                            } */
</style>
<div class="flex h-screen w-screen flex-col">
    <div class="w-full basis-2/4 overflow-hidden">

        <MudCarousel class="h-full w-full" ShowArrows="false" ShowBullets="false" EnableSwipeGesture="true"
                     AutoCycle="true" TData="object">
            <MudCarouselItem>
                <div class="mx-5 flex h-full flex-col">
                    <div class="my-auto">
                        <div class="-mt-8">
                            <dotlottie-player src="https://lottie.host/752358b3-21b0-4448-b8f4-0f2a2acc998b/DZAZuyYyol.json"
                                              background="transparent" speed="1" class="m-auto h-60 w-60" loop autoplay />
                        </div>
                        <p class="font-iranyekan mx-auto text-center text-lg font-extrabold">
                            شرح حال نویسی بیمار راحت تر
                            از
                            همیشه
                        </p>
                        <p class="font-iranyekan mx-auto text-center text-xs">
                            نرم افزار داکیومد با امکانات بسیار زیاد
                            خود
                            مثل شرح حال نویسی همراه و همیار همیشگی پزشکان محترم
                        </p>
                    </div>
                </div>
            </MudCarouselItem>
            <MudCarouselItem>
                <div class="mx-5 flex h-full flex-col">
                    <div class="my-auto">
                        <div class="-mb-3 -mt-8">
                            <dotlottie-player src="https://lottie.host/9ca6089d-388f-4eef-8050-8181c1d945a1/B7oM9NN9O4.json"
                                              background="transparent" speed="1" class="m-auto h-60 w-60" loop autoplay />
                        </div>
                        <p class="font-iranyekan mx-auto text-center text-lg font-extrabold">
                            اوردر های شما همه در یک
                            اپلیکیشن
                        </p>
                        <p class="font-iranyekan mx-auto text-center text-xs">
                            نرم افزار داکیومد با امکانات بسیار زیاد
                            خود
                            مثل شرح حال نویسی همیار همیشگی پزشکان محترم
                        </p>
                    </div>
                </div>
            </MudCarouselItem>
            <MudCarouselItem>
                <div class="mx-5 flex h-full flex-col">
                    <div class="my-auto">
                        <div class="-mb-10 -mt-8">
                            <dotlottie-player src="https://lottie.host/87dfb50f-e91f-45c6-b8dc-d3a2436c533c/5DPvXG0W1t.json"
                                              background="transparent" speed="1" class="m-auto h-72 w-72" loop autoplay />
                        </div>
                        <p class="font-iranyekan mx-auto text-center text-lg font-extrabold">
                            نرم افزار جامع داکیـــــومد
                        </p>
                        <p class="font-iranyekan mx-auto text-center text-xs">
                            نرم افزار داکیومد با امکانات بسیار زیاد
                            خود
                            مثل تهیه پیشنویس شرح حال همراه همیشگی پزشکان محترم
                        </p>
                    </div>
                </div>
            </MudCarouselItem>
        </MudCarousel>
    </div>
    <MudPaper Elevation="10" class="w-full basis-2/4 rounded-t-2xl bg-[#FFFBE6]">
        <MudCarousel class="h-full w-full overflow-x-hidden overflow-y-scroll" @ref="_carousel" ShowArrows="false"
                     ShowBullets="false" EnableSwipeGesture="false" AutoCycle="false" TData="object">
            <MudCarouselItem>
                <div class="font-iranyekan flex h-full flex-col p-5">
                    <MudStack class="my-auto">
                        <p class="font-iranyekan text-lg font-extrabold">ورود | ثبت نام</p>
                        <p class="text-justify text-xs">
                            برای ورود یا ثبت نام به اپلیکیشن داکیومد باید شماره تلفن همراه خود را
                            وارد کنید
                        </p>

                        <MudForm @ref="_confirmPhoneNumberForm">
                            <MudTextField Required="true" RequiredError="لطفا شماره تلفن را وارد کنید"
                            @bind-Value="@_phoneNumber" InputType="InputType.Telephone" T="string" Label="شماره تلفن همراه"
                                          Variant="Variant.Outlined" />
                        </MudForm>
                        <BaseButtonUi IsProcessing="_isProcessing" OnClickCallback="ConfirmPhoneNumber" Content="ثبت شماره تلفن"
                                      Icon="@Icons.Material.TwoTone.Phone" Color="Color.Secondary" Variant="Variant.Filled">
                        </BaseButtonUi>
                        <p class="mx-3 text-justify">
                            با تایید شماره تلفن همراه با همه شرایط <a class="text-blue-500">
                                حریم
                                خصوصی
                            </a> اپلیکیشن داکیومد موافقت می کنم
                        </p>
                    </MudStack>
                </div>
            </MudCarouselItem>
            <MudCarouselItem>
                <div class="flex h-full flex-col">

                    <MudStack class="font-iranyekan my-auto p-5">
                        <p class="font-iranyekan text-lg font-extrabold">ورود | ثبت نام</p>
                        <p class="text-justify text-xs">
                            برای ورود یا ثبت نام به اپلیکیشن داکیومد باید شماره تلفن همراه خود را
                            وارد کنید
                        </p>

                        <MudTextField class="text-sm" T="string" InputType="InputType.Telephone" @bind-Value="@_verifyCode" Label="کد ارسال شده را وارد کنید"
                                      Variant="Variant.Outlined" />

                        <BaseButtonUi IsProcessing="_isProcessing" OnClickCallback="ConfirmVerifyCode" Content="تایید کد"
                                      Icon="@Icons.Material.TwoTone.Verified" Color="Color.Secondary" Variant="Variant.Filled">
                        </BaseButtonUi>

                        <div class="mr-5 flex flex-row">
                            <MudStack class="my-auto">
                                <p class="text-lg font-extrabold">02:00</p>
                                <a class="-mt-5 font-bold text-blue-600">ارسال مجدد پیامک</a>
                            </MudStack>
                            <MudButton class="mr-auto rounded-full" EndIcon="@Icons.Material.Filled.ChevronLeft"
                                       Variant="Variant.Outlined" @onclick="PhoneNumberRollBack" Color="Color.Primary"
                                       Size="Size.Medium">
                                بازگشت
                            </MudButton>

                        </div>
                    </MudStack>
                </div>
            </MudCarouselItem>
            <MudCarouselItem>
                <div class="flex h-full flex-col">
                    <MudStack class="font-iranyekan my-auto w-screen p-5">
                        <p class="font-iranyekan text-lg font-extrabold">ثبت نام</p>
                        <p class="text-justify text-xs">
                            برای ثبت نام به اپلیکیشن داکیومد باید اطلاعات کامل خود را وارد
                            کنید
                        </p>

                        <MudForm @ref="_confirmSignUpForm">
                            <MudFocusTrap>
                                <MudTextField Required="true" RequiredError="نام خود را وارد کنید" @bind-Value="@_signUpRequest.FirstName" class="my-5 text-sm" T="string" Label="نام" Variant="Variant.Outlined" />
                                <MudTextField Required="true" RequiredError="نام خانوادگی خود را وارد کنید" @bind-Value="@_signUpRequest.LastName" class="my-5 text-sm" T="string" Label="نام خانوادگی" Variant="Variant.Outlined" />
                                <MudTextField class="my-5 text-sm" T="string" @bind-Value="@_phoneNumber" Label="شماره تلفن همراه"
                                              Variant="Variant.Outlined" />

                                <MudAutocomplete Required="true" ToStringFunc="dto => dto.Name" class="my-5" @bind-Value="@_selectedCity"
                                                 SearchFunc="SearchCity"
                                                 T="CitySDto"
                                                 Label="شهر شما"
                                                 Variant="Variant.Outlined">
                                    <ProgressIndicatorInPopoverTemplate>
                                        <MudList Clickable="false">
                                            <MudListItem>
                                                <div class="mx-auto flex w-full flex-row">
                                                    <MudProgressCircular class="my-auto -ml-4 mr-1" Size="Size.Small" Indeterminate="true" />
                                                    <p class="text-md mx-auto my-1 font-bold">منتظر بمانید</p>
                                                </div>
                                            </MudListItem>
                                        </MudList>
                                    </ProgressIndicatorInPopoverTemplate>
                                    <ItemTemplate Context="e">
                                        <p>@e.Name</p>
                                    </ItemTemplate>
                                </MudAutocomplete>

                                <MudAutocomplete Required="true" ToStringFunc="dto => dto.Name" class="my-5" @bind-Value="@_selectedUni" SearchFunc="SearchUniversity" T="UniversitySDto" Label="دانشگاه" Variant="Variant.Outlined">
                                    <ProgressIndicatorInPopoverTemplate>
                                        <MudList Clickable="false">
                                            <MudListItem>
                                                <div class="mx-auto flex w-full flex-row">
                                                    <MudProgressCircular class="my-auto -ml-4 mr-1" Size="Size.Small" Indeterminate="true" />
                                                    <p class="text-md mx-auto my-1 font-bold">منتظر بمانید</p>
                                                </div>
                                            </MudListItem>
                                        </MudList>
                                    </ProgressIndicatorInPopoverTemplate>
                                    <ItemTemplate Context="e">
                                        <p>@e.Name</p>
                                    </ItemTemplate>
                                </MudAutocomplete>
                            </MudFocusTrap>
                        </MudForm>

                        <BaseButtonUi IsProcessing="_isProcessing" OnClickCallback="ConfirmSignUp" Content="تکمیل ثبت نام"
                                      Icon="@Icons.Material.TwoTone.Login" Color="Color.Primary" Variant="Variant.Filled">
                        </BaseButtonUi>
                    </MudStack>
                </div>
            </MudCarouselItem>
        </MudCarousel>
    </MudPaper>
</div>

@code
{
    private List<CitySDto> _cities = new List<CitySDto>();
    private List<UniversitySDto> _universities = new List<UniversitySDto>();
    private SignUpRequestDto _signUpRequest = new SignUpRequestDto();
    private MudCarousel<object>? _carousel;
    private int _currentSignOnStep = 0;
    private MudForm? _confirmPhoneNumberForm;
    private MudForm? _confirmSignUpForm;
    private CitySDto? _selectedCity;
    private UniversitySDto? _selectedUni;
    private string _phoneNumber = string.Empty;
    private string _verifyCode = string.Empty;
    private bool _isProcessing = false;
    private SignUpStatus _signUpStatus;

    protected override async Task OnInitializedAsync()
    {
        var token = await UserUtility.GetBearerTokenAsync();
        if (!token.IsNullOrEmpty())
        {
            var user = await UserUtility.GetUserAsync();
            if (user.SignUpStatus == SignUpStatus.SignUpCompleted)
                NavigationManager.NavigateTo("HomePage");
            if (user.SignUpStatus == SignUpStatus.PhoneNumberVerified)
            {
                _phoneNumber = user.PhoneNumber;
                _currentSignOnStep = 2;
                _carousel?.MoveTo(_currentSignOnStep);
            }
        }
        await base.OnInitializedAsync();
    }

    private async Task ConfirmPhoneNumber()
    {
        try
        {
            _confirmPhoneNumberForm?.Validate();
            if (_confirmPhoneNumberForm is { IsValid: true })
            {
                _isProcessing = true;
                _signUpStatus = await RestWrapper.AuthRestApi.GetVerifyCodeAsync(_phoneNumber);
                _carousel?.MoveTo(++_currentSignOnStep);
            }
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                Snackbar.Add(exe.Message, Severity.Error);
            Snackbar.Add(ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            Snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {
            _isProcessing = false;
        }
    }
    private async Task ConfirmVerifyCode()
    {
        try
        {
            _isProcessing = true;
            var rest = await RestWrapper.AuthRestApi.LoginWithVerifyCodeAsync(new LoginRequestDto { UserName = _phoneNumber, VerifyCode = _verifyCode });
            await UserUtility.SetBearerTokenAsync(rest.BearerToken);
            await UserUtility.SetUserAsync(rest.User);
            if (_signUpStatus == SignUpStatus.SignUpCompleted)
                NavigationManager.NavigateTo("HomePage");
            else
                _carousel?.MoveTo(++_currentSignOnStep);
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                Snackbar.Add(exe.Message, Severity.Error);
            Snackbar.Add(ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            Snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {
            _isProcessing = false;
        }
    }

    private void PhoneNumberRollBack()
    {
        _carousel?.MoveTo(--_currentSignOnStep);
    }
    private async Task ConfirmSignUp()
    {
        try
        {

            _confirmSignUpForm?.Validate();
            if (_confirmSignUpForm is { IsValid: true })
            {
                _isProcessing = true;
                _signUpRequest.CityId = _selectedCity.Id;
                _signUpRequest.UniversityId = _selectedUni.Id;

                var token = await UserUtility.GetBearerTokenAsync();
                var rest = await RestWrapper.AuthRestApi.CompleteSignUpAsync(_signUpRequest, token);
                await UserUtility.SetBearerTokenAsync(rest.BearerToken);
                await UserUtility.SetUserAsync(rest.User);
                NavigationManager.NavigateTo("HomePage");
            }
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                Snackbar.Add(exe.Message, Severity.Error);
            Snackbar.Add(ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            Snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {
            _isProcessing = false;
        }
    }

    private async Task<IEnumerable<CitySDto>> SearchCity(string city)
    {
        try
        {
            if (_cities.Count == 0)
            {
                var token = await UserUtility.GetBearerTokenAsync();
                _cities = await RestWrapper.CrudDtoApiRest<City, CitySDto, Guid>(Address.CityController).ReadAll(0, token);
            }
            if (city.IsNullOrEmpty())
                return _cities;
            return _cities.Where(c => c.Name.Contains(city));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                Snackbar.Add(exe.Message, Severity.Error);
            Snackbar.Add(ex.Content, Severity.Error);
            return _cities;
        }
        catch (Exception e)
        {
            Snackbar.Add(e.Message, Severity.Error);
            return _cities;
        }
    }
    private async Task<IEnumerable<UniversitySDto>> SearchUniversity(string uni)
    {
        try
        {
            uni = uni == null ? string.Empty : uni;
            if (_selectedCity == null)
            {
                await _confirmSignUpForm!.Validate();
                return _universities;
            }
            var token = await UserUtility.GetBearerTokenAsync();
            _universities = await RestWrapper.CityRestApi.GetUniversitiesAsync(_selectedCity.Id, token);
            return _universities.Where(c => c.Name.Contains(uni));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                Snackbar.Add(exe.Message, Severity.Error);
            Snackbar.Add(ex.Content, Severity.Error);
            return _universities;
        }
        catch (Exception e)
        {
            Snackbar.Add(e.Message, Severity.Error);
            return _universities;
        }
    }
}