@model iyixiGames.Domain.DTOs.Games.CreateGameRequest

@{
    ViewData["Title"] = "创建新游戏";
}

<div class="container mt-4">
    <h1>创建新游戏</h1>
    <hr/>
    <div class="row">
        <div class="col-md-8">
            <form asp-action="Create">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="mb-3">
                    <button type="button" class="btn btn-primary" id="GenerateGameInfoFromPathAsync">生成Games</button>
                </div>
                <div class="mb-3">
                    <label asp-for="Name" class="form-label">游戏名称</label>
                    <input asp-for="Name" class="form-control" id="gameNameInput"/> @* Add ID for JS *@
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
                <div class="mb-3">
                    <label asp-for="Path" class="form-label">游戏文件夹名称</label>
                    <input asp-for="Path" class="form-control" id="gamePathInput" placeholder="例如: space-adventure"/>
                    <span asp-validation-for="Path" class="text-danger"></span>
                </div>

                <div class="mb-3">
                    <label asp-for="Description" class="form-label">游戏简介</label>
                    <div class="input-group">
                        <textarea asp-for="Description" class="form-control" rows="4" id="gameDescriptionTextarea"
                                  placeholder="AI将在这里生成简介，或手动输入..."></textarea>
                        <button type="button" class="btn btn-outline-secondary" id="generateDescriptionBtn">
                            <span class="spinner-border spinner-border-sm d-none" role="status"
                                  aria-hidden="true"></span>
                            生成简介
                        </button>
                    </div>
                    <span asp-validation-for="Description" class="text-danger"></span>
                    <small id="descriptionHelp"
                           class="form-text text-muted">点击“生成简介”将尝试使用AI根据游戏名称创建一段简介。</small>
                </div>

                <div class="mb-3">
                    <label asp-for="Category" class="form-label">类别 (逗号分隔)</label>
                    <input asp-for="Category" class="form-control" placeholder="例如: Action,Adventure" id="category"/>
                    <span asp-validation-for="Category" class="text-danger"></span>
                </div>
                <div class="mb-3">
                    <label asp-for="Popularity" class="form-label">流行度 (0-100)</label>
                    <input asp-for="Popularity" class="form-control" type="number" min="0" max="100" id="popularity"/>
                    <span asp-validation-for="Popularity" class="text-danger"></span>
                </div>
                <div class="mb-3">
                    <label asp-for="AvgRating" class="form-label">平均评分 (0.0-5.0)</label>
                    <input asp-for="AvgRating" class="form-control" type="number" step="0.1" min="0" max="5" id="avgRating"/>
                    <span asp-validation-for="AvgRating" class="text-danger"></span>
                </div>
                <div class="mb-3">
                    <label asp-for="ReleaseDate" class="form-label">发布日期</label>
                    <input asp-for="ReleaseDate" class="form-control" type="date" id="releaseDate"/>
                    <span asp-validation-for="ReleaseDate" class="text-danger"></span>
                </div>

                <div class="mb-3">
                    <button type="submit" class="btn btn-primary">创建</button>
                    <a asp-action="Index" class="btn btn-secondary ms-2">取消并返回</a>
                </div>
            </form>
        </div>
    </div>
</div>

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }

    <script>
        $(document).ready(function () {
            $('#generateDescriptionBtn').click(function () {
                var gameName = $('#gameNameInput').val();
                var $button = $(this);
                var $spinner = $button.find('.spinner-border');
                var $buttonText = $button.contents().filter(function () {
                    return this.nodeType === 3;
                }); // Get text node

                if (!gameName || gameName.trim() === '') {
                    alert('请先输入游戏名称！');
                    return;
                }

                $button.prop('disabled', true); // Disable button
                $spinner.removeClass('d-none'); // Show spinner
                $buttonText.replaceWith('生成中...'); // Change button text

                $.ajax({
                    url: '@Url.Action("GenerateDescription", "Games")',
                    type: 'POST',
                    data: {gameName: gameName},
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (response) {
                        if (response.success) {
                            $('#gameDescriptionTextarea').val(response.description);
                        } else {
                            alert(response.message || '生成简介失败。');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("AJAX Error:", status, error, xhr.responseText);
                        alert('生成简介时发生错误，请检查网络或稍后再试。');
                    },
                    complete: function () {
                        $button.prop('disabled', false); // Re-enable button
                        $spinner.addClass('d-none'); // Hide spinner
                        $buttonText.replaceWith('生成简介'); // Restore button text
                    }
                });
            });
            $('#GenerateGameInfoFromPathAsync').click(function () {
                var gamePath = $('#gamePathInput').val();
                console.log('gamePath:', gamePath)
                
                var $button = $(this);
                var $spinner = $button.find('.spinner-border');
                var $buttonText = $button.contents().filter(function () {
                    return this.nodeType === 3;
                }); // Get text node

                if (!gamePath || gamePath.trim() === '') {
                    alert('请先输入游戏 Path！');
                    return;
                }

                $button.prop('disabled', true); // Disable button
                $spinner.removeClass('d-none'); // Show spinner
                $buttonText.replaceWith('生成中...'); // Change button text

                $.ajax({
                    url: '@Url.Action("GenerateGameInfoFromPath", "Games")',
                    type: 'POST',
                    data: {gamePath: gamePath},
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (response) {
                        console.log(response);
                        if (response.success) {
                            $('#gameNameInput').val(response.description.name);
                            $('#gameDescriptionTextarea').val(response.description.description);
                            $('#category').val(response.description.category);
                            $('#popularity').val(response.description.popularity);
                            $('#avgRating').val(response.description.avgRating);
                            $('#releaseDate').val(response.description.releaseDate);
                        } else {
                            alert(response.message || '生成Game失败。');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("AJAX Error:", status, error, xhr.responseText);
                        alert('生成Game时发生错误，请检查网络或稍后再试。');
                    },
                    complete: function () {
                        $button.prop('disabled', false); // Re-enable button
                        $spinner.addClass('d-none'); // Hide spinner
                        $buttonText.replaceWith('生成简介'); // Restore button text
                    }
                });
            });
        });
    </script>
}