using System;
using System.Collections.Generic;
using System.Linq;
using LittleShop.Client.Models;
using Telegram.Bot.Types.ReplyMarkups;
using TeleBot.Models;

namespace TeleBot.UI
{
    public static class MenuBuilder
    {
        public static InlineKeyboardMarkup MainMenu()
        {
            return new InlineKeyboardMarkup(new[]
            {
                new[] { InlineKeyboardButton.WithCallbackData("🛍️ Browse Categories", "browse") },
                new[] { InlineKeyboardButton.WithCallbackData("🖼️ View Products with Images", "products") },
                new[] { InlineKeyboardButton.WithCallbackData("🛒 View Cart", "cart") },
                new[] { InlineKeyboardButton.WithCallbackData("📦 My Orders", "orders") },
                new[] { InlineKeyboardButton.WithCallbackData("💬 Messages", "support") },
                //new[] { InlineKeyboardButton.WithCallbackData("🔒 Privacy Settings", "privacy") },
                new[] { InlineKeyboardButton.WithCallbackData("❓ Help", "help") }
            });
        }
        
        public static InlineKeyboardMarkup CategoryMenu(List<Category> categories)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            foreach (var category in categories)
            {
                // Add description to category button text
                var categoryText = GetCategoryDisplayText(category.Name, category.Description);
                buttons.Add(new[] { 
                    InlineKeyboardButton.WithCallbackData(
                        categoryText, 
                        $"category:{category.Id}"
                    ) 
                });
            }
            
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("⬅️ Back to Menu", "menu") });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        public static InlineKeyboardMarkup ProductListMenu(PagedResult<Product> products, Guid? categoryId, int currentPage)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            // Product buttons
            foreach (var product in products.Items)
            {
                var price = $"${product.Price:F2}";
                buttons.Add(new[] { 
                    InlineKeyboardButton.WithCallbackData(
                        $"{product.Name} - {price}", 
                        $"product:{product.Id}"
                    ) 
                });
            }
            
            // Pagination
            var paginationButtons = new List<InlineKeyboardButton>();
            
            if (products.HasPreviousPage)
            {
                var prevData = categoryId.HasValue 
                    ? $"products:{categoryId}:{currentPage - 1}"
                    : $"products:all:{currentPage - 1}";
                paginationButtons.Add(InlineKeyboardButton.WithCallbackData("⬅️ Previous", prevData));
            }
            
            if (products.HasNextPage)
            {
                var nextData = categoryId.HasValue 
                    ? $"products:{categoryId}:{currentPage + 1}"
                    : $"products:all:{currentPage + 1}";
                paginationButtons.Add(InlineKeyboardButton.WithCallbackData("Next ➡️", nextData));
            }
            
            if (paginationButtons.Any())
            {
                buttons.Add(paginationButtons.ToArray());
            }
            
            // Navigation
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("🛒 View Cart", "cart") });
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("⬅️ Back", "browse") });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        public static InlineKeyboardMarkup ProductDetailMenu(Product product, int quantity = 1)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            // Quantity selector
            var quantityButtons = new List<InlineKeyboardButton>();
            if (quantity > 1)
                quantityButtons.Add(InlineKeyboardButton.WithCallbackData("➖", $"qty:{product.Id}:{quantity - 1}"));
            quantityButtons.Add(InlineKeyboardButton.WithCallbackData($"Qty: {quantity}", "noop"));
            if (quantity < 10)
                quantityButtons.Add(InlineKeyboardButton.WithCallbackData("➕", $"qty:{product.Id}:{quantity + 1}"));
            
            buttons.Add(quantityButtons.ToArray());
            
            // Add to cart button
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData(
                    $"🛒 Add to Cart", 
                    $"add:{product.Id}:{quantity}"
                ) 
            });
            
            // Navigation
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("⬅️ Back to Products", "browse") });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        public static InlineKeyboardMarkup CartMenu(ShoppingCart cart)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            if (!cart.IsEmpty())
            {
                // Item management buttons
                foreach (var item in cart.Items)
                {
                    buttons.Add(new[] {
                        InlineKeyboardButton.WithCallbackData(
                            $"❌ Remove {item.ProductName}", 
                            $"remove:{item.ProductId}"
                        )
                    });
                }
                
                // Checkout button
                buttons.Add(new[] { 
                    InlineKeyboardButton.WithCallbackData("✅ Proceed to Checkout", "checkout") 
                });
                
                // Clear cart button
                buttons.Add(new[] { 
                    InlineKeyboardButton.WithCallbackData("🗑️ Clear Cart", "clear_cart") 
                });
            }
            
            // Navigation
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("🛍️ Continue Shopping", "browse") });
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("⬅️ Main Menu", "menu") });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        public static InlineKeyboardMarkup CheckoutConfirmMenu()
        {
            return new InlineKeyboardMarkup(new[]
            {
                new[] { 
                    InlineKeyboardButton.WithCallbackData("✅ Confirm Order", "confirm_order"),
                    InlineKeyboardButton.WithCallbackData("❌ Cancel", "cart")
                }
            });
        }
        
        public static InlineKeyboardMarkup PaymentMethodMenu(List<string> currencies)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            // Group currencies in rows of 2
            for (int i = 0; i < currencies.Count; i += 2)
            {
                var row = new List<InlineKeyboardButton>();
                
                row.Add(InlineKeyboardButton.WithCallbackData(
                    GetCurrencyEmoji(currencies[i]) + " " + currencies[i], 
                    $"pay:{currencies[i]}"
                ));
                
                if (i + 1 < currencies.Count)
                {
                    row.Add(InlineKeyboardButton.WithCallbackData(
                        GetCurrencyEmoji(currencies[i + 1]) + " " + currencies[i + 1], 
                        $"pay:{currencies[i + 1]}"
                    ));
                }
                
                buttons.Add(row.ToArray());
            }
            
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("❌ Cancel", "cart") });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        public static InlineKeyboardMarkup PrivacyMenu(PrivacySettings settings)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData(
                    settings.UseEphemeralMode ? "✅ Ephemeral Mode" : "❌ Ephemeral Mode", 
                    "privacy:ephemeral"
                ) 
            });
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData(
                    settings.UseTorOnly ? "✅ Tor Only" : "❌ Tor Only", 
                    "privacy:tor"
                ) 
            });
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData(
                    settings.RequirePGP ? "✅ PGP Encryption" : "❌ PGP Encryption", 
                    "privacy:pgp"
                ) 
            });
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData(
                    settings.DisableAnalytics ? "✅ No Analytics" : "❌ No Analytics", 
                    "privacy:analytics"
                ) 
            });
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData(
                    settings.EnableDisappearingMessages ? "✅ Disappearing Messages" : "❌ Disappearing Messages", 
                    "privacy:disappearing"
                ) 
            });
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData("💥 Delete All My Data", "privacy:delete") 
            });
            
            buttons.Add(new[] { 
                InlineKeyboardButton.WithCallbackData("⬅️ Back to Menu", "menu") 
            });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        public static InlineKeyboardMarkup OrderListMenu(List<Order> orders)
        {
            var buttons = new List<InlineKeyboardButton[]>();
            
            foreach (var order in orders.Take(10)) // Limit to 10 most recent
            {
                var status = GetOrderStatusEmoji(order.Status);
                buttons.Add(new[] {
                    InlineKeyboardButton.WithCallbackData(
                        $"{status} Order {order.Id.ToString().Substring(0, 8)} - ${order.TotalAmount:F2}",
                        $"order:{order.Id}"
                    )
                });
            }
            
            buttons.Add(new[] { InlineKeyboardButton.WithCallbackData("⬅️ Back to Menu", "menu") });
            
            return new InlineKeyboardMarkup(buttons);
        }
        
        private static string GetCurrencyEmoji(string currency)
        {
            return currency.ToUpper() switch
            {
                "BTC" => "₿",
                "ETH" => "Ξ",
                "XMR" => "ɱ",
                "USDT" => "₮",
                "LTC" => "Ł",
                "DOGE" => "Ð",
                "DASH" => "Đ",
                "ZEC" => "ⓩ",
                _ => "💰"
            };
        }
        
        public static InlineKeyboardMarkup SupportMenu()
        {
            var markup = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("❌ Cancel", "cancel_support")
                }
            });
            
            return markup;
        }

        public static InlineKeyboardMarkup ConversationMenu()
        {
            var markup = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("🔄 Refresh Messages", "refresh_conversation"),
                    InlineKeyboardButton.WithCallbackData("⬅️ Back to Menu", "exit_chat")
                }
            });
            
            return markup;
        }

        private static string GetOrderStatusEmoji(int status)
        {
            return status switch
            {
                0 => "⏳", // PendingPayment
                1 => "💰", // PaymentReceived
                2 => "⚙️", // Processing
                3 => "📦", // PickingAndPacking
                4 => "🚚", // Shipped
                5 => "✅", // Delivered
                6 => "❌", // Cancelled
                7 => "💸", // Refunded
                _ => "📋"
            };
        }

        public static InlineKeyboardMarkup SingleProductMenu(Guid productId)
        {
            return new InlineKeyboardMarkup(new[]
            {
                new[] { 
                    InlineKeyboardButton.WithCallbackData("🛒 Buy Now", $"add:{productId}:1"),
                    InlineKeyboardButton.WithCallbackData("📄 Details", $"product:{productId}")
                }
            });
        }

        public static InlineKeyboardMarkup CategoryNavigationMenu(Guid? categoryId)
        {
            return new InlineKeyboardMarkup(new[]
            {
                new[] { 
                    InlineKeyboardButton.WithCallbackData("⬅️ Back to Categories", "browse"),
                    InlineKeyboardButton.WithCallbackData("🏠 Main Menu", "menu") 
                }
            });
        }

        public static InlineKeyboardMarkup BackToCategoriesMenu()
        {
            return new InlineKeyboardMarkup(new[]
            {
                new[] { 
                    InlineKeyboardButton.WithCallbackData("⬅️ Back to Categories", "browse")
                }
            });
        }

        public static InlineKeyboardMarkup ProductNavigationMenu(Guid? categoryId)
        {
            return new InlineKeyboardMarkup(new[]
            {
                new[] { 
                    InlineKeyboardButton.WithCallbackData("⬅️ Back to Categories", "browse"),
                    InlineKeyboardButton.WithCallbackData("🛒 View Cart", "cart")
                },
                new[] { 
                    InlineKeyboardButton.WithCallbackData("🏠 Main Menu", "menu")
                }
            });
        }

        private static string GetCategoryDisplayText(string categoryName, string? description)
        {
            var emoji = categoryName.ToLower() switch
            {
                var name when name.Contains("electronics") => "📱",
                var name when name.Contains("clothing") || name.Contains("fashion") => "👕",
                var name when name.Contains("books") || name.Contains("book") => "📚",
                var name when name.Contains("home") || name.Contains("house") => "🏠",
                var name when name.Contains("sports") || name.Contains("fitness") => "⚽",
                var name when name.Contains("beauty") || name.Contains("cosmetics") => "💄",
                var name when name.Contains("food") || name.Contains("grocery") => "🍎",
                _ => "📦"
            };

            // if (!string.IsNullOrEmpty(description))
            // {
            //     // Truncate description for button
            //     var shortDesc = description.Length > 40 
            //         ? description.Substring(0, 37) + "..."
            //         : description;
            //     return $"{emoji} {categoryName}\n\n\n{shortDesc}";
            // }
            
            return $"{emoji} {categoryName}";
        }
    }
}