using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types;
using TeleBot.Models;
using TeleBot.Services;
using TeleBot.UI;

namespace TeleBot.Handlers
{
    public interface IMessageHandler
    {
        Task HandleMessageAsync(ITelegramBotClient bot, Message message);
    }
    
    public class MessageHandler : IMessageHandler
    {
        private readonly ISessionManager _sessionManager;
        private readonly ILogger<MessageHandler> _logger;
        private readonly ILittleShopService _shopService;
        
        public MessageHandler(
            ISessionManager sessionManager,
            ILogger<MessageHandler> logger,
            ILittleShopService shopService)
        {
            _sessionManager = sessionManager;
            _logger = logger;
            _shopService = shopService;
        }
        
        public async Task HandleMessageAsync(ITelegramBotClient bot, Message message)
        {
            if (message.From == null || string.IsNullOrEmpty(message.Text))
                return;
            
            var session = await _sessionManager.GetOrCreateSessionAsync(message.From.Id);
            
            try
            {
                // Handle checkout flow messages
                if (session.State == SessionState.CheckoutFlow && session.OrderFlow != null)
                {
                    await HandleCheckoutInput(bot, message, session);
                }
                // Handle customer support messages
                else if (session.State == SessionState.CustomerSupport)
                {
                    await HandleCustomerSupportMessage(bot, message, session);
                }
                else if (message.Text.StartsWith("/pgpkey "))
                {
                    // Handle PGP key input
                    var pgpKey = message.Text.Substring(8).Trim();
                    session.Privacy.PGPPublicKey = pgpKey;
                    session.Privacy.RequirePGP = true;
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "✅ *PGP key saved successfully*\n\nYour shipping information will be encrypted.",
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown,
                        replyMarkup: MenuBuilder.MainMenu()
                    );
                }
                else
                {
                    // Default response for non-command messages
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "Please use the menu buttons or commands to navigate.\n\nUse /help for available commands.",
                        replyMarkup: MenuBuilder.MainMenu()
                    );
                }
                
                await _sessionManager.UpdateSessionAsync(session);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error handling message");
                await bot.SendTextMessageAsync(
                    message.Chat.Id,
                    "An error occurred. Please try again or use /start to reset."
                );
            }
        }
        
        private async Task HandleCheckoutInput(ITelegramBotClient bot, Message message, UserSession session)
        {
            if (session.OrderFlow == null)
            {
                session.State = SessionState.MainMenu;
                return;
            }
            
            var input = message.Text?.Trim() ?? "";
            
            switch (session.OrderFlow.CurrentStep)
            {
                case OrderFlowStep.CollectingName:
                    if (string.IsNullOrWhiteSpace(input))
                    {
                        await bot.SendTextMessageAsync(
                            message.Chat.Id,
                            "❌ Name cannot be empty. Please enter your shipping name:"
                        );
                        return;
                    }
                    
                    session.OrderFlow.ShippingName = input;
                    session.OrderFlow.CurrentStep = OrderFlowStep.CollectingAddress;
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "📦 *Checkout - Step 2/5*\n\n" +
                        "Please enter your shipping address:\n\n" +
                        "_Reply with your street address_",
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown
                    );
                    break;
                    
                case OrderFlowStep.CollectingAddress:
                    if (string.IsNullOrWhiteSpace(input))
                    {
                        await bot.SendTextMessageAsync(
                            message.Chat.Id,
                            "❌ Address cannot be empty. Please enter your shipping address:"
                        );
                        return;
                    }
                    
                    session.OrderFlow.ShippingAddress = input;
                    session.OrderFlow.CurrentStep = OrderFlowStep.CollectingCity;
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "📦 *Checkout - Step 3/5*\n\n" +
                        "Please enter your city:\n\n" +
                        "_Reply with your city name_",
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown
                    );
                    break;
                    
                case OrderFlowStep.CollectingCity:
                    if (string.IsNullOrWhiteSpace(input))
                    {
                        await bot.SendTextMessageAsync(
                            message.Chat.Id,
                            "❌ City cannot be empty. Please enter your city:"
                        );
                        return;
                    }
                    
                    session.OrderFlow.ShippingCity = input;
                    session.OrderFlow.CurrentStep = OrderFlowStep.CollectingPostCode;
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "📦 *Checkout - Step 4/5*\n\n" +
                        "Please enter your postal/ZIP code:\n\n" +
                        "_Reply with your postal code_",
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown
                    );
                    break;
                    
                case OrderFlowStep.CollectingPostCode:
                    if (string.IsNullOrWhiteSpace(input))
                    {
                        await bot.SendTextMessageAsync(
                            message.Chat.Id,
                            "❌ Postal code cannot be empty. Please enter your postal code:"
                        );
                        return;
                    }
                    
                    session.OrderFlow.ShippingPostCode = input;
                    session.OrderFlow.CurrentStep = OrderFlowStep.CollectingCountry;
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "📦 *Checkout - Step 5/5*\n\n" +
                        "Please enter your country (or press Enter for United Kingdom):\n\n" +
                        "_Reply with your country name_",
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown
                    );
                    break;
                    
                case OrderFlowStep.CollectingCountry:
                    if (!string.IsNullOrWhiteSpace(input))
                    {
                        session.OrderFlow.ShippingCountry = input;
                    }
                    
                    session.OrderFlow.CurrentStep = OrderFlowStep.ReviewingOrder;
                    
                    // Show order summary
                    var summary = MessageFormatter.FormatOrderSummary(session.OrderFlow, session.Cart);
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        summary,
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown,
                        replyMarkup: MenuBuilder.CheckoutConfirmMenu()
                    );
                    break;
                    
                case OrderFlowStep.CollectingNotes:
                    session.OrderFlow.Notes = string.IsNullOrWhiteSpace(input) ? null : input;
                    session.OrderFlow.CurrentStep = OrderFlowStep.ReviewingOrder;
                    
                    // Show order summary
                    var summaryWithNotes = MessageFormatter.FormatOrderSummary(session.OrderFlow, session.Cart);
                    
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        summaryWithNotes,
                        parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown,
                        replyMarkup: MenuBuilder.CheckoutConfirmMenu()
                    );
                    break;
                    
                default:
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "Please use the menu to continue.",
                        replyMarkup: MenuBuilder.MainMenu()
                    );
                    session.State = SessionState.MainMenu;
                    break;
            }
        }
        
        private async Task HandleCustomerSupportMessage(ITelegramBotClient bot, Message message, UserSession session)
        {
            try
            {
                // Send the customer's message to the business
                var success = await _shopService.SendCustomerMessageAsync(
                    message.From!.Id,
                    message.From.Username ?? "",
                    $"{message.From.FirstName} {message.From.LastName}".Trim(),
                    message.From.FirstName ?? "",
                    message.From.LastName ?? "",
                    "Customer Message", // Simple subject
                    message.Text!
                );

                if (success)
                {
                    // Show updated conversation instead of going back to main menu
                    await RefreshCustomerConversation(bot, message, session);
                }
                else
                {
                    await bot.SendTextMessageAsync(
                        message.Chat.Id,
                        "❌ Sorry, there was an error sending your message. Please try again.",
                        replyMarkup: MenuBuilder.SupportMenu()
                    );
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error handling customer support message");
                await bot.SendTextMessageAsync(
                    message.Chat.Id,
                    "❌ An error occurred. Please try again or use /cancel to return to the menu.",
                    replyMarkup: MenuBuilder.SupportMenu()
                );
            }
        }
        
        private async Task RefreshCustomerConversation(ITelegramBotClient bot, Message message, UserSession session)
        {
            try
            {
                // Get updated conversation history
                var messages = await _shopService.GetCustomerConversationAsync(
                    message.From!.Id,
                    message.From.Username ?? "",
                    $"{message.From.FirstName} {message.From.LastName}".Trim(),
                    message.From.FirstName ?? "",
                    message.From.LastName ?? ""
                );

                var conversationText = "💬 *Your Messages*\n\n";
                
                if (messages?.Any() == true)
                {
                    conversationText += "Recent conversation:\n\n";
                    
                    foreach (var msg in messages.OrderBy(m => m.CreatedAt).TakeLast(8)) // Show last 8 messages
                    {
                        var isFromBusiness = msg.Direction == 0; // AdminToCustomer
                        var sender = isFromBusiness ? "🏪 Shop" : "👤 You";
                        var time = msg.CreatedAt.ToString("MMM dd, HH:mm");
                        
                        conversationText += $"*{sender}* _{time}_\n{msg.Content}\n\n";
                    }
                }
                
                conversationText += "_Type your next message or use buttons below._";

                await bot.SendTextMessageAsync(
                    message.Chat.Id,
                    conversationText,
                    parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown,
                    replyMarkup: MenuBuilder.ConversationMenu()
                );
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error refreshing customer conversation");
                await bot.SendTextMessageAsync(
                    message.Chat.Id,
                    "✅ Message sent! Continue chatting or use the buttons below.",
                    replyMarkup: MenuBuilder.ConversationMenu()
                );
            }
        }
    }
}