@using OrchardCore.Forms.Models
@model ShapeViewModel<SelectPart>
@{
    var formElementPart = Model.Value.ContentItem.As<FormElementPart>();
    var formInputElementPart = Model.Value.ContentItem.As<FormInputElementPart>();
    var elementId = formElementPart.Id;
    var fieldName = formInputElementPart.Name;
    var fieldId = !string.IsNullOrEmpty(elementId) ? elementId : !string.IsNullOrEmpty(fieldName) ?
    Html.GenerateIdFromName(fieldName) : default(string);
    var fieldValue = Model.Value.DefaultValue;
    var validationClass = "";

    if (ViewData.ModelState.TryGetValue(fieldName, out var fieldEntry))
    {
        fieldValue = fieldEntry.AttemptedValue;
        if (fieldEntry.Errors.Count > 0)
        {
            validationClass += " input-validation-error is-invalid"; // TODO: use validation classes from tailwind!
        }
    }
}

@if (Model.Value.Editor == SelectEditorOption.Checkbox || Model.Value.Editor == SelectEditorOption.Radio)
{
    int i = 0;
    var htmlType = Model.Value.Editor == SelectEditorOption.Checkbox ? "checkbox" : "radio";
    <div class="mt-2 space-y-2">
        @foreach (var option in Model.Value.Options)
        {
            <div class="flex items-center gap-x-3">
                <input type="@htmlType" id="@(fieldId + "_" + i)" name="@fieldName"
                    class="@validationClass h-4 w-4 border-gray-300 text-indigo-600 focus:ring-indigo-600"
                    value="@option.Value" @(option.Value == fieldValue ? "checked='checked'" : "") />
                <label class="block text-sm font-medium text-gray-900" for="@(fieldId + "_" + i)">@option.Text</label>
            </div>
            i++;
        }
    </div>
}
else
{
    <div class="mt-2">
        <select id="@fieldId" name="@fieldName"
            class="@validationClass block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:max-w-xs sm:text-sm sm:leading-6">
            @foreach (var option in Model.Value.Options)
            {
                var optionValue = !string.IsNullOrWhiteSpace(option.Value) ? option.Value : option.Text;
                var isOptionSelected = optionValue == fieldValue;
                <option value="@optionValue" selected="@isOptionSelected">@option.Text</option>
            }
        </select>
    </div>
}
