using Blazor.Models;
using Blazor.Pages.Admins;
using Blazor.Services;
using Blazor.ViewClasses;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System;
using static Blazor.Pages.Questions.AddQuestion;
using static System.Net.WebRequestMethods;

namespace Blazor.Pages.Questions
{
    public partial class EditQuestion
    {

        [Parameter]
        public int Id { get; set; }

        private QuestionModel questionModel = new();

        [Inject]
        public IStringLocalizer<EditQuestion> Localizer { get; set; }
        public List<Chapter> chapters = new();

        private List<Answer> answers = new();

        public List<Checkbox> checkboxs = new();

        public Question question = new();

        public List<Question> questions = new();

        [Inject]
        public required IDataService DataService { get; set; }

        [Inject]
        public required HttpClient Http { get; set; }

        [Inject]
        public required NavigationManager NavigationManager { get; set; }

        [Inject]
        public required IWebHostEnvironment WebHostEnvironment { get; set; }

        [Inject]
        public required ILogger<EditQuestion> Logger { get; set; }

        private string OldQuestionContent { get; set; }
        private int OldQuestionIdChapter { get; set; }
        private int OldIdAnswerGood { get; set; }

        public int IdAgood { get; set; }

        protected override async Task OnInitializedAsync()
        {
            var response = Http.GetFromJsonAsync<Chapter[]>(API.API_URL + "all/chapters/" + API.TOKEN + "/1").Result;
            if (response == null) chapters = new List<Chapter>();
            else chapters = new List<Chapter>(response);

            answers = new();
            checkboxs = new();
            var resp = Http.GetFromJsonAsync<Question[]>(API.API_URL + "questions/" + Id + "/" + API.TOKEN).Result;
            questions = new List<Question>(resp);

            question = questions.Find(q => q.Id == Id);

            foreach (var q in questions)
            {
                answers.Add(new Answer(q.A_id, q.A_content, q.Id));
                checkboxs.Add(new Checkbox(q.A_id,false));
            }

            
            foreach (var checkbox in checkboxs)
            {
                if (question.IdAnswerGood == checkbox.Id)
                {
                    checkbox.IsCorrect = true;
                }
            }
            OldQuestionContent = question.Content;
            OldQuestionIdChapter = question.IdChapter;
            OldIdAnswerGood = question.IdAnswerGood;
        }

        private void SetCorrectAnswer(int checkboxId)
        {
            Console.WriteLine($"SetCorrectAnswer called with checkboxId: {checkboxId}");
            question.IdAnswerGood = checkboxId;
        }


        private async Task HandleValidSubmit()
        {

            var formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("content", question.Content));
            formData.Add(new KeyValuePair<string, string>("idchapter", question.IdChapter.ToString()));
            foreach(var index in Enumerable.Range(0, answers.Count))
            {
                var answer = answers[index];
                var answercontent = $"answerContent{index + 1}";
                formData.Add(new KeyValuePair<string, string>(answercontent, answer.Content));
            }

            formData.Add(new KeyValuePair<string, string>("idanswergood", question.IdAnswerGood.ToString()));

            var formContent = new FormUrlEncodedContent(formData);

            string apiUri = API.API_URL+"/update/question/" + question.Id + "/" + API.TOKEN;

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.PostAsync(apiUri, formContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var errorResponse = await response.Content.ReadAsStringAsync();
                }
            }

            Logger.LogInformation("Question '{OldQuestionContent}', Chapter '{OldchapterId}' and the correct answer '{OldIdAnswerGood}' edited in '{NewQuestionContent}' for Chapter '{NewchapterId}' with 4 answers : '{IdAnswer1}':'{NewAnswerContent1}', '{IdAnswer2}':'{NewAnswerContent2}', '{IdAnswer3}':'{NewAnswerContent3}', '{IdAnswer4}':'{NewAnswerContent4}' the correct '{IdAnswerGood}'", OldQuestionContent, OldQuestionIdChapter,OldIdAnswerGood, question.Content, question.IdChapter, answers[0].Id, answers[0].Content, answers[1].Id, answers[1].Content, answers[2].Id, answers[2].Content, answers[3].Id, answers[3].Content,IdAgood);

            NavigationManager.NavigateTo("questions");

        }
    }
}
