@inherits ViewModelTemplate<UserEditViewModel>
@using Dynamicweb.Rendering
@using Dynamicweb.Frontend
@using Dynamicweb.Users.Frontend.UserEdit

@{    
    string currentCountry = !string.IsNullOrEmpty(Model.User.CountryCode) ? Model.User.CountryCode : (Pageview.Area.EcomCountryCode ?? string.Empty);
    var regions = Dynamicweb.Ecommerce.Services.Countries.GetRegions(currentCountry);
    var countries = Dynamicweb.Ecommerce.Services.Countries.GetCountries();

    string countrySelectorColumnSize = regions.Count > 1 ? "g-col-12 g-col-lg-3" : "g-col-12 g-col-lg-6";
}

<header class="mb-4">
    <h1 class="h4 mb-0">@Translate("Edit profile")</h1>
</header>

<div class="card mb-4">
	<div class="card-body hstack gap-4 align-items-start p-4">
        <form enctype="multipart/form-data" id="UserManagementEditForm" data-swift-avatar-upload
            hx-trigger="change"
            hx-post
            hx-swap="outerHTML"
            hx-target="[data-swift-avatar-upload]"
            hx-select="[data-swift-avatar-upload]"
        >
            <input type="hidden" name="ID" value="@Pageview.ID">
            <input type="hidden" name="CMD" value="UpdateUser">

            <label for="ProfileImage" role="button" class="d-flex position-relative" title="@Translate("Upload your profile picture") (@Translate("Format"): Png, Jpg or Gif. @Translate("Filesize max.") 2mb)")" data-bs-toggle="tooltip" data-bs-placement="top">
                <input type="file" name="ProfileImage" id="ProfileImage" class="visually-hidden" 
                    accept="image/x-png,image/gif,image/jpeg,image"
                    data-swift-max-bytes="2097152"
                    hx-on:change="
                        const f = this.files[0];
                        const max = this.dataset.swiftMaxBytes;
                        this.setCustomValidity('');           // reset
                        this.classList.remove('is-invalid');
                        if (f && f.size > max) {
                            this.setCustomValidity(`@Translate("Max file size is 2 MB.")`);
                            this.reportValidity();             
                            this.classList.add('is-invalid');   
                            this.value = '';                    
                            return false;                       
                    }" 
                >
                @if(Model.User.TryGetImageFile(out ImageFileViewModel? image))
                {
                    <div class="align-self-auto hstack justify-content-center p-0" style="height:6rem; aspect-ratio:1">
                        <img src="@image.ToGetImage(new(){ Width = 500, Ratio = "1/1" })" alt="@Translate("Avatar image")" class="img-thumbnail rounded-circle" itemprop="image"/>
                    </div>
                } else {
                    <div class="btn btn-primary rounded-circle align-self-auto hstack justify-content-center p-0 disabled opacity-100" data-dw-button style="height:6rem; aspect-ratio:1; --bs-btn-disabled-bg: var(--dw-color-button-primary)" title="@Translate("Upload your profile picture")">
                        <div class="d-flex dw-h4 lh-1 m-0">
                            @(Model.User.GetTwoLetterInitials())
                        </div>
                    </div>
                }
                <div class="btn btn-secondary rounded-circle icon-2 p-2 position-absolute bottom-0 end-0" data-dw-button>
                    @ReadFile("/Files/Images/Icons/upload.svg")
                </div>
                <div class="icon-2 position-absolute m-auto w-100 h-100" >
                    <span class="htmx-indicator spinner-border spinner-border-sm" aria-hidden="true"></span>
                </div>
            </label>
        </form>

        <div class="flex-fill align-self-center">
            @if (!string.IsNullOrEmpty(Model.User.Name)) {
                <h4 class="mb-1">@Model.User.Name</h4>
            }
            <div class="text-muted fs-7">
                <span>@string.Join(" - ", new[]{ Model.User.Title, Model.User.Company }.Where(s => !string.IsNullOrWhiteSpace(s)))</span>
            </div>
            <div class="text-muted fs-8">
                <span>@string.Join(", ", new[]{ Model.User.City, Model.User.Country }.Where(s => !string.IsNullOrWhiteSpace(s)))</span>
            </div>
        </div>
    </div>
</div>

@if (Model.Result == UserEditResultType.Success)
{
    <div class="alert alert-success mb-4">@Translate("Your changes have been saved successfully!")</div>
} 
else if (Model.Result == UserEditResultType.InvalidEmail)
{
    <div class="alert alert-danger mb-4">@Translate("The email is invalid")</div>
} 
else if (Model.Result != UserEditResultType.None)
{
    <div class="alert alert-danger mb-4">@Translate(Model.Result.ToString())</div>
}

<form method="post" id="UserManagementEditForm">
    <div class="grid">
        <input type="hidden" name="ID" value="@Pageview.ID">

        <div class="g-col-12">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Name")" name="UserManagement_Form_Name" id="UserManagement_Form_Name" value="@Model.User.Name">
                <label for="Name" class="form-label">@Translate("Name")</label>
            </div>
        </div>
        <div class="g-col-12">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Company") (@Translate("optional"))" name="UserManagement_Form_Company" id="UserManagement_Form_Company" value="@Model.User.Company">
                <label for="Company" class="form-label">@Translate("Company") (@Translate("optional"))</label>
            </div>
        </div>
        <div class="g-col-12">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Street & number")" name="UserManagement_Form_Address" id="UserManagement_Form_Address" value="@Model.User.Address" />
                <label for="Address" class="form-label">@Translate("Street & number")</label>
            </div>
        </div>
        <div class="g-col-12">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Additional address")" name="UserManagement_Form_Address2" id="UserManagement_Form_Address2" value="@Model.User.Address2" />
                <label for="Address2" class="form-label">@Translate("Additional address")</label>
            </div>
        </div>
        <div class="g-col-12 g-col-lg-3">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Zip")" name="UserManagement_Form_Zip" id="UserManagement_Form_Zip" value="@Model.User.Zip" />
                <label for="Zip" class="form-label">@Translate("Zip")</label>
            </div>
        </div>

        <div class="@countrySelectorColumnSize">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Town / City")" name="UserManagement_Form_City" id="UserManagement_Form_City" value="@Model.User.City" />
                <label for="City" class="form-label">@Translate("Town / City")</label>
            </div>
        </div>

        @if (regions.Count > 1)
        {
            var regionLabel = currentCountry switch
    	    {
                "US" or "IN" or "AU" or "BR" or "DE" => Translate("State"),
                "CA" or "CN" or "PH" or "ZA" => Translate("Province"),
                _ => Translate("Region") // Default case
            };

            <div class="g-col-3">
                <div class="form-floating">
                    <select class="form-select" name="UserManagement_Form_State" id="UserManagement_Form_State">
                        @foreach (var region in regions)
                        {
                            string selected = region.RegionCode == Model.User.State ? "selected" : "";
                            <option value="@region.RegionCode" @selected>@region.GetName(Dynamicweb.Ecommerce.Common.Context.LanguageID)</option>
                        }
                    </select>
                    <label for="UserManagement_Form_State">@regionLabel</label>
                </div>
            </div>
        } else { 
            <input type="hidden" name="UserManagement_Form_State" id="UserManagement_Form_State" value=""></input>
        }

        <div class="g-col-12 g-col-lg-3">
            <div class="form-floating">
                <select class="form-select" id="UserManagement_Form_CountryCode" name="UserManagement_Form_CountryCode">
                    @foreach (var country in countries)
                    {
                        string selected = country.Code2 == currentCountry ? "selected" : "";
                        <option value="@country.Code2" @selected>@country.GetName(Pageview.Area.EcomLanguageId)</option>
                    }
                </select>
                <label for="UserManagement_Form_CountryCode" class="form-label">@Translate("Country")</label>
            </div>
        </div>

        <div class="g-col-12 g-col-lg-6">
            <div class="form-floating">
                <input type="email" class="form-control" placeholder="@Translate("Email")" name="UserManagement_Form_Email" id="UserManagement_Form_Email" value="@Model.User.Email" required />
                <label for="Email" class="form-label">@Translate("Email")</label>
            </div>
        </div>
        <div class="g-col-12 g-col-lg-6">
            <div class="form-floating">
                <input type="text" class="form-control" placeholder="@Translate("Phone")" name="UserManagement_Form_Phone" id="UserManagement_Form_Phone" value="@Model.User.Phone">
                <label for="Phone" class="form-label">@Translate("Phone")</label>
            </div>
        </div>

        <div class="g-col-12">
            <button type="submit" class="btn btn-primary me-2" name="cmd" value="UpdateUser" data-dw-button id="SaveUserButton">@Translate("Save")</button>
            @if (!string.IsNullOrEmpty(Dynamicweb.Context.Current?.Request.QueryString.Get("GoBackToPage")))
			{
				<a href="/Default.aspx?ID=@(Dynamicweb.Context.Current?.Request.QueryString.Get("GoBackToPage"))" class="btn btn-secondary" data-dw-button="secondary" id="BackToCheckoutButtonButton">@Translate("Go back to checkout")</a>
			}
        </div>
    </div>
</form>


@if (Pageview.AreaSettings.TryGetString("Google_APIKey", out string apiKey))
{
	<script defer src="https://maps.googleapis.com/maps/api/js?key=@(apiKey)&libraries=places"></script>

	<script type="module">
		var mapSettings = { currentCountry: "@currentCountry" };
		swift.Places.init(mapSettings);
	</script>
}
