using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Exceptions;

namespace TeleBot
{
    using Telegram.Bot.Types.Enums;
    using Telegram.Bot.Types.ReplyMarkups;

    public class TelgramBotService
    {
        private readonly string BotToken = "7880403661:AAGma1wAyoHsmG45iO6VvHCqzimhJX1pp14";

        public BotScript Master { get; set; }
        public Dictionary<long, BotScript> Chats { get; set; } = new Dictionary<long, BotScript>();

        public async Task Startup()
        {

            if (Master == null)
            {
                Master = BotScript.CreateBotScript("Anonymous Feedback Survey for The Sweetshop \r\n\r\nWe’d love to hear your thoughts so we can improve your experience and keep the shop evolving in the best way possible.");
                Master.AddScaledQuestion("How would you rate communication at the shop (including updates, clarity, and friendliness)?\r\n(1 = Poor | 10 = Excellent)");
                Master.AddScaledQuestion("How would you rate the quality of the products?\r\n(1 = Poor | 10 = Excellent)");
            }

            var botClient = new TelegramBotClient(BotToken);

            using var cts = new CancellationTokenSource();
            var receiverOptions = new ReceiverOptions
            {
                AllowedUpdates = Array.Empty<UpdateType>() // Receive all updates
            };

            botClient.StartReceiving(
                HandleUpdateAsync,
                HandleErrorAsync,
                receiverOptions,
                cancellationToken: cts.Token
            );

            var me = await botClient.GetMeAsync();
            Console.WriteLine($"Bot started: {me.Username}");
            Console.ReadLine();
            cts.Cancel();
        }

        private async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
        {
            if (update.Message is { } message)
            {

                var chatId = message.Chat.Id;
                if (!Chats.ContainsKey(chatId))
                {
                    var s = Master;
                    Chats.Add(chatId, s);
                }

                //if (message.Text == "/start")
                //{
                await ProcessMessage(botClient, chatId, cancellationToken);
                //var responseText = $"Hello, {message.From?.FirstName}! You said: {message.Text}";
                //await botClient.SendMessage(chatId, responseText, cancellationToken: cancellationToken);
            }
            else if (update.CallbackQuery is { } callbackQuery)
            {
                var data = callbackQuery.Data?.Split(':');
                var chatId = callbackQuery.Message.Chat.Id;
                var aID = Guid.Parse(data[0]);
                Chats[chatId].Answers.Add(aID, data[1]);

                var response = $"Thank for choosing: {data[1]} in response to '{Chats[chatId].Questions.First(x => x.Key == aID).Value.Text}'";
                await botClient.SendTextMessageAsync(callbackQuery.Message.Chat.Id, response, cancellationToken: cancellationToken);
                Chats[chatId].Stage++;
                if (Chats[chatId].Stage > Chats[chatId].Questions.Count)
                {
                    await botClient.SendTextMessageAsync(chatId, "Thank you for completing our questions, we appreciete your feedback!", cancellationToken: cancellationToken);
                }
                else
                {
                    await ProcessMessage(botClient, chatId, cancellationToken);
                }
            }
        }

        private async Task ProcessMessage(ITelegramBotClient botClient, long chatId, CancellationToken cancellationToken)
        {
            if (Chats[chatId].Stage > Chats[chatId].Questions.Count)
            {
                await botClient.SendTextMessageAsync(chatId, "You have already completed the questionaire.  Thank you for your feedback.", cancellationToken: cancellationToken);
            }
            else
            {
                switch (Chats[chatId].Stage)
                {
                    case 0:
                        await botClient.SendTextMessageAsync(chatId, Chats[chatId].WelcomeText, cancellationToken: cancellationToken);
                        Chats[chatId].Stage++;
                        break;
                    default:
                        var q = Chats[chatId].Questions.OrderBy(x => x.Value.Order).Skip(Chats[chatId].Stage - 1).Take(1).FirstOrDefault();
                        var opts = new InlineKeyboardMarkup(new[]
                        {
                            q.Value.Options.Take(5).Select(x => InlineKeyboardButton.WithCallbackData(x, $"{q.Key}:{x}")),
                            q.Value.Options.Skip(5).Select(x => InlineKeyboardButton.WithCallbackData(x, $"{q.Key}:{x}"))
                        });
                        await botClient.SendTextMessageAsync(chatId, q.Value.Text, replyMarkup: opts, cancellationToken: cancellationToken);

                        opts = new InlineKeyboardMarkup(q.Value.Options.Skip(5).Select(x => InlineKeyboardButton.WithCallbackData(x, $"{q.Key}:{x}")));
                        await botClient.SendTextMessageAsync(chatId, "", replyMarkup: opts, cancellationToken: cancellationToken);

                        break;
                }
            }
        }

        private Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            Console.WriteLine($"Error: {exception.Message}");
            return Task.CompletedTask;
        }
    }
}
