using TerrariaApi.Server;
using Microsoft.Xna.Framework;
using System.Data;
using Terraria;
using TShockAPI;
using TShockAPI.Hooks;
using Wolfje.Plugins.SEconomy;
using Wolfje.Plugins.SEconomy.Journal;
using IL.Terraria.ID;

namespace AuctionHouse;

[ApiVersion(2, 1)]
public class Main : TerrariaPlugin
{
    public override string Name => "Auction House";
    public override Version Version => new Version(1, 0, 0);
    public override string Author => "Discipile";
    public override string Description => "Adds an Auction House to Terraria.";

    public Main(Terraria.Main game) : base(game)
    {

    }




    private bool Frozen = false;


    internal static void LogToDiscord(string message)
    {
        message = $"[AH @ {Terraria.Netplay.ListenPort}] " + message;
        DiscordBot.DS.EnqueueMessage(DiscordBot.Channels.TerrariaStaffLogs, message);
    }

    public override void Initialize()
    {
        Commands.ChatCommands.Add(new Command("ah.use", AuctionHouse, "ah", "auction", "auctionhouse"));

        PlayerHooks.PlayerPostLogin += new PlayerHooks.PlayerPostLoginD(OnPlayerLogin);

        //CheckForExpiredListings();
        DS.LoadFromDisk();

    }

    private void AuctionHouse(CommandArgs args)
    {
        if (Frozen && !args.Player.HasPermission("ah.admin"))
        {
            args.Player.SendErrorMessage("The auction house is currently frozen and cannot be accessed.");
            return;
        }

        foreach (TSPlayer plr in TShock.Players.Where(p => p != null))
        {
            if (plr.Account == null || !plr.IsLoggedIn) { continue; }
            CheckForReturnListings(plr);
            CheckForReturnPayments(plr);
        }
        CheckForExpiredListings();

        if (args.Parameters.Count == 0)
        {
            if (args.Player.HasPermission("ah.admin"))
            {
                args.Player.SendErrorMessage("Usage: /ah <buy | sell | bump | pull | list | search | help || save | load | freeze | debug>."); ;
            }
            else
            {
                args.Player.SendErrorMessage("Usage: /ah <buy | sell | bump | pull | list | search | help>.");
            }
            return;
        }
        switch (args.Parameters[0].ToLower())
        {
            case "sell":
                SellOnAH(args);
                return;
            case "buy":
                BuyFromAH(args);
                return;
            case "list":
                if (args.Parameters.Count > 1 && args.Parameters[1].ToLower() == "own")
                {
                    ListOwnlistingsAH(args);
                    return;
                }
                else
                {
                    ListAH(args);
                    return;
                }
            case "search":
                SearchAH(args);
                return;
            case "pull":
                PullFromAH(args);
                return;
            case "bump":
                BumpListingOnAH(args);
                return;
            case "help":
                args.Player.SendMessage("Auction House Help & Information:", 0, 255, 255);
                args.Player.SendInfoMessage("/ah buy <id> - Buy the item(s) with the specified listing ID from the auction house.");
                args.Player.SendInfoMessage("/ah sell <price> - Put the item(s) you're CURRENTLY HOLDING on the auction house for the specified price. Tip: you can say \"4p36g52s28c\" and the auction house will convert it automatically!");
                args.Player.SendInfoMessage("/ah bump <id> - Resets the return date of a listing to 7 days and sets the listing as new. Can only be done if the listing has less than 3 days remaining.");
                args.Player.SendInfoMessage($"/ah pull <id> {(args.Player.HasPermission("ah.admin") ? "[-force]" : "")} - Pull a specified listing off the auction house. Be aware, you will not get your deposit back for pulled listings.");
                args.Player.SendInfoMessage("/ah list [page] - Provides a list of all items on the auction house. Your listings are highlighted in purple.");
                args.Player.SendInfoMessage("/ah list own [page] - Provides a list of all of your listings on the auction house.");
                args.Player.SendInfoMessage("/ah search <item1> <item2> ... <item5> [page] — Provides all listings whose item name contains at least something from any <item1> <item2>, et cetera.");
                args.Player.SendMessage("Be aware, for the [TimeLeft] category of /ah list, times in [c/00ff00:Green] you have at least this much time left (aka time until the return date is passed). Times in [c/ff0000:Red] mean you have at most that much time left (aka time until the expiration date is met and the listing forcifully disappears).", 0, 255, 255);
                args.Player.SendMessage("A 5% deposit is required to list an item on the auction house. This deposit will be returned to you even if the item is not sold.", 0, 255, 255);
                args.Player.SendMessage("You can have a maximum of 15 listings on the auction house at a time.", 0, 255, 255);
                args.Player.SendMessage("Items will be returned to you after 7 days if they are not sold, provided you join the server between this point and the expiration point.", 0, 255, 255);
                args.Player.SendMessage("The expiration date of all listings on the auction house is 15 days. (Meaning you have 8 days to re-claim the item(s) and deposit of a listing that was not purchased).", 0, 255, 255);
                args.Player.SendInfoMessage("/ah help - Displays this help message.");
                return;
            case "save":
                if (args.Player.HasPermission("ah.admin"))
                {
                    DS.SaveToDisk();
                    args.Player.SendSuccessMessage("Auction House data has been saved to disk.");
                }
                else
                {
                    args.Player.SendErrorMessage("You do not have permission to use this command.");
                    TShock.Log.ConsoleError("[Auction House] Player {0} ({1}) attempted to save the auction house data to disk.", args.Player.Name, args.Player.Account.Name);
                }
                return;
            case "load":
                if (args.Player.HasPermission("ah.admin"))
                {
                    DS.LoadFromDisk();
                    args.Player.SendSuccessMessage("Auction House data has been loaded from disk.");
                    return;
                }
                else
                {
                    args.Player.SendErrorMessage("You do not have permission to use this command.");
                    TShock.Log.ConsoleError("[Auction House] Player {0} ({1}) attempted to load the auction house data from disk.", args.Player.Name, args.Player.Account.Name);
                }
                return;
            case "freeze":
                if (args.Player.HasPermission("ah.admin")) 
                {
                    FreezeAH(args);
                }
                else
                {
                    args.Player.SendErrorMessage("You do not have permission to use this command.");
                    TShock.Log.ConsoleError("[Auction House] Player {0} ({1}) attempted to use the freeze command.", args.Player.Name, args.Player.Account.Name);
                }
                return;
            case "debug":
                if (args.Player.HasPermission("ah.admin"))
                {
                    if (args.Parameters.Count < 2)
                    {
                        args.Player.SendErrorMessage("Usage: /ah debug <command>. Valid commands: <p[ayments], l[istings]>");
                        return;
                    }
                    switch (args.Parameters[1].ToLower())
                    {
                        case "payments":
                        case "p":
                            DEBUGGetAllPayments(args);
                            return;
                        case "listings":
                        case "l":
                            DEBUGListAllListings(args);
                            return;
                        default:
                            args.Player.SendErrorMessage("Usage: /ah debug <command>. Valid commands: <p[ayments], l[istings]>");
                            return;
                    }
                }
                else
                {
                    args.Player.SendErrorMessage("You do not have permission to use this command.");
                    TShock.Log.ConsoleError("[Auction House] Player {0} ({1}) attempted to use the debug command.", args.Player.Name, args.Player.Account.Name);
                }
                return;
            default:
                if (args.Player.HasPermission("ah.admin"))
                {
                    args.Player.SendErrorMessage("Usage: /ah <buy | sell | bump | pull | list | search | help || save | load | freeze | debug>.");
                }
                else
                {
                    args.Player.SendErrorMessage("Usage: /ah <buy | sell | bump | pull | list | search | help>.");
                }
                return;
        }
    }

    // [i/p83:3542] - Prefixed nebula blaze
    // [i/s9999:2]  -- 9999 dirt

    private bool SellOnAH(CommandArgs args)  // -- /ah sell <price>
    {
        #region Error Checking
        if (!args.Player.IsLoggedIn) { args.Player.SendErrorMessage("You must be logged in to use this command!"); return false; }
        if (args.Player.Dead)
        {
            args.Player.SendErrorMessage("You cannot sell items on the auction house while dead.");
            return false;
        }

        if (!SEconomyPlugin.Instance.GetBankAccount(args.Player).IsAccountEnabled)
        {
            args.Player.SendErrorMessage("Your bank account is not enabled! You cannot access the auction house.");
            return false;
        }

        if (args.Player.SelectedItem.netID == 0)
        {
            args.Player.SendErrorMessage("You cannot sell oxygen! Please hold the item you wish to sell.");
            return false;
        }

        if (args.Parameters.Count < 2) { args.Player.SendErrorMessage("Usage: /ah sell <price>. Lists the item you're CURRENTLY HOLDING on the auction house for the specified price."); return false; }


        if (!Money.TryParse(Convert.ToString(args.Parameters[1]), out var itemCost))
        {
            args.Player.SendErrorMessage($"Could not convert \"{args.Parameters[1]}\" into a valid price.");
            return false;
        }
        if (itemCost <= 0)
        {
            args.Player.SendErrorMessage("Error! Listing price must be greater than 0.");
            return false;
        }

        if (GetPlayerListingCounts(args.Player.Account.ID) >= 15) // 15 max for now per account
        {
            args.Player.SendErrorMessage("You have reached the maximum amount of listings you can have on the auction house. Please wait until at least one of your listings expire or sell.");
            return false;
        }

        var SellerBank = SEconomyPlugin.Instance.GetBankAccount(args.Player.Account.Name);
        if (SellerBank == null)
        {
            args.Player.SendErrorMessage("Error! Bank account is null. Contact an Admin.");
            return false;
        }
        else if (SellerBank.Balance < itemCost * 0.05)
        {
            args.Player.SendErrorMessage($"You do not have enough money to put down a deposit for this item. You need {(Money)((itemCost * 0.05) - SellerBank.Balance)} more to make a deposit on an item listed at {itemCost}.");
            return false;
        }

        if (DS.Listings.Count >= 1000) // Emergency safeguard.
        {
            args.Player.SendErrorMessage("The auction house is full! Please wait until some items are sold or expired before listing more items.");
            TShock.Log.ConsoleError("[Auction House] The auction house is full!");
            LogToDiscord("The auction house is full!");
            return false;
        }
        #endregion

        DS.TotalListings++; // Increment ID by one

        DS.Listing listing = new DS.Listing();
        listing.ID = DS.TotalListings;
        listing.ItemID = args.Player.SelectedItem.netID;
        listing.Amount = args.Player.SelectedItem.stack;
        listing.PrefixID = args.Player.SelectedItem.prefix;
        listing.Price = itemCost; //ah sell <price> 
        listing.Deposit = (Money)(itemCost * 0.05);
        listing.ListerAccountID = args.Player.Account.ID;
        listing.ListerAccount = args.Player.Account.Name;

        DS.Listings.Add(listing); // Add it to the auction house

        // Remove the item they're holding
        int InvItem = Array.IndexOf(args.Player.TPlayer.inventory, args.Player.SelectedItem);
        args.Player.TPlayer.inventory[InvItem].netDefaults(0);
        NetMessage.SendData((int)PacketTypes.PlayerSlot, -1, -1, null, args.Player.Index, InvItem, 0, 0, 0, 0, 0);
        // Remove the item they're holding

        // Take the seller's 5% deposit
        SellerBank.TransferTo(SEconomyPlugin.Instance.WorldAccount, listing.Deposit, Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToSender | Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.IsPayment,
                                        "putting down a deposit", string.Format("Deposit for {0} {1} @ cost {2}", listing.Amount, listing.ItemName(), itemCost));

        // Confirmation message & log
        args.Player.SendSuccessMessage($"Successfully put {listing.Amount} of {listing.ItemName()} with prefix {listing.PrefixName()} on the auction house for {((Money)listing.Price)}. (Deposit of {((Money)listing.Deposit)}). Listing ID: {listing.ID}.");
        TShock.Log.ConsoleInfo($"[Auction House] (ID: {listing.ID}). {args.Player.Name} ({args.Player.Account.Name} has put {listing.Amount} of {listing.ItemName()} with prefix {listing.PrefixID} on the auction house for {((Money)listing.Price).ToTextString()}. (Deposit of {((Money)listing.Deposit).ToTextString()})");
        DS.SaveToDisk();
        LogToDiscord($"{args.Player.Name} ({args.Player.Account.Name}) has put {listing.Amount} of {listing.ItemName()} with prefix {listing.PrefixID} on the auction house for {((Money)listing.Price).ToTextString()}. (Deposit of {((Money)listing.Deposit).ToTextString()}). (Listing ID: {listing.ID}).");
        return true;
    }


    private bool BuyFromAH(CommandArgs args)
    {
        #region Error Checking
        if (!args.Player.IsLoggedIn) { args.Player.SendErrorMessage("You must be logged in to use this command!"); return false; }

        if (args.Player.Dead)
        {
            args.Player.SendErrorMessage("You cannot buy items from the auction house while dead.");
            return false;
        }

        if (!SEconomyPlugin.Instance.GetBankAccount(args.Player).IsAccountEnabled)
        {
            args.Player.SendErrorMessage("Your bank account is not enabled! You cannot access the auction house.");
            return false;
        }

        if (args.Parameters.Count < 2) { args.Player.SendErrorMessage("Usage: /ah buy <id>"); return false; }


        if (!int.TryParse(args.Parameters[1], out var listingID))
        {
            args.Player.SendErrorMessage($"Error: {args.Parameters[1]} is not a valid listing ID.");
            return false;
        }
        if (!args.Player.InventorySlotAvailable)
        {
            args.Player.SendErrorMessage("Your inventory seems full. Clear some space before purchasing items off of the auction house!");
            return false;
        }
        #endregion

        DS.Listing listingToBuy;


        foreach (DS.Listing listing in DS.Listings)
        {
            if (listing.ID == listingID)
            {
                listingToBuy = listing;
                goto ListingExists;
            }
        }

        args.Player.SendErrorMessage($"The specified listing ID could not be found on the auction house.");
        return false;

    ListingExists:
        if (listingToBuy.ListerAccountID == args.Player.Account.ID)
        {
            args.Player.SendErrorMessage("You cannot buy your own listing off of the auction house.");
            return false;
        }

        IBankAccount BuyerBank = SEconomyPlugin.Instance.GetBankAccount(args.Player);

        if (BuyerBank.Balance < listingToBuy.Price)
        {
            args.Player.SendErrorMessage($"You do not have enough money to buy this item. You need {(Money)(listingToBuy.Price - BuyerBank.Balance)} more.");
            return false;
        }

        if (listingToBuy.ItemID == Terraria.ID.ItemID.FallenStar && Terraria.Main.IsItDay()) 
        {
            args.Player.SendErrorMessage("You cannot buy Fallen Stars from the Auction House between 4:30 AM and 7:29 PM (in-game time)!");
            return false;
        }

        BuyerBank.TransferTo(SEconomyPlugin.Instance.WorldAccount, listingToBuy.Price, Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToSender | Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.IsPayment,
                                        string.Format("buying {0} {1}", listingToBuy.Amount, listingToBuy.ItemName()), string.Format("For buying {0} {1}", listingToBuy.Amount, listingToBuy.ItemName()));

        // Try giving the money directly to the seller if they're online
        TSPlayer? Seller = null;
        foreach (TSPlayer p in TShock.Players) 
        {
            if (p == null) { continue; }
            if (p.Account.ID == listingToBuy.ListerAccountID || p.Account.Name == listingToBuy.ListerAccount) 
            { 
                Seller = p;
                break;
            }
        }

        //TShock.Log.ConsoleWarn($"Seller: {Seller?.Name ?? "Offline/Null"}");

        IBankAccount? SellerBank = null;

        if (Seller != null)
        {
            SellerBank = SEconomyPlugin.Instance.GetBankAccount(Seller);
            if (SellerBank == null) 
            {
                TShock.Log.ConsoleError("Attempting to find SellerBank through AccountSearch.");
                SellerBank = SEconomyPlugin.Instance.GetBankAccount(listingToBuy.ListerAccount);
            }
        }

        if (SellerBank != null) // If the player is online, just give them their moeny.
        {
            SEconomyPlugin.Instance.WorldAccount.TransferTo(SellerBank, (listingToBuy.Price + listingToBuy.Deposit), Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToReceiver,
                                                                string.Format("selling {0} {1}", listingToBuy.Amount, listingToBuy.ItemName()), string.Format("[AH] Sold {0} {1} for {2}",
                                                                                            listingToBuy.Amount, listingToBuy.ItemName(), (listingToBuy.Price + listingToBuy.Deposit)));
            
            Seller.SendSuccessMessage($"You have received {(Money)(listingToBuy.Price + listingToBuy.Deposit)} for selling {listingToBuy.Amount} {listingToBuy.ItemName()}.");
        }
        else // Player is offline, add it to the payment queue
        {
            if (DS.PaymentQueue.Count >= 1000) // Emergency safeguard.
            {
                TShock.Log.ConsoleError($"[Auction House] The payment queue is full! {listingToBuy.ListerAccount} was not able to have their payment enqueued.");
                LogToDiscord($"The payment queue is full! {listingToBuy.ListerAccount} was not able to have their payment enqueued.");
            }
            else
            {
                DS.Payment payment = new DS.Payment(listingToBuy.ListerAccountID, (listingToBuy.Price + listingToBuy.Deposit), listingToBuy.ID, string.Format("selling {0} {1}",
                                                                                                            listingToBuy.Amount, listingToBuy.ItemName()));
                DS.PaymentQueue.Add(payment);
            }
        }

        args.Player.GiveItem(listingToBuy.ItemID, listingToBuy.Amount, listingToBuy.PrefixID);

        args.Player.SendSuccessMessage($"You have successfully bought {listingToBuy.Amount} of {listingToBuy.ItemName()} with prefix {listingToBuy.PrefixName()} for {((Money)listingToBuy.Price)}. Listing ID: {listingToBuy.ID}.");
        DS.Listings.Remove(listingToBuy);
        DS.SaveToDisk();
        LogToDiscord($"{args.Player.Name} ({args.Player.Account.Name}) has successfully bought {listingToBuy.Amount} of {listingToBuy.ItemName()} with prefix {listingToBuy.PrefixName()} for {((Money)listingToBuy.Price)}. (Listing ID: {listingToBuy.ID}).");

        return true;

    }


    public static readonly Color isSeller = new Color(255, 74, 225);
    private void ListAH(CommandArgs args)
    {
        if (DS.Listings.Count == 0)
        {
            args.Player.SendInfoMessage("There are no listings on the auction house at this time.");
            return;
        }

        int page = 1;
        if (args.Parameters.Count > 1)
        {
            if (!int.TryParse(args.Parameters[1], out page) || page <= 0)
            {
                args.Player.SendErrorMessage("Invalid page number.");
                return;
            }
        }

        const int listingsPerPage = 9;
        int totalPages = (int)Math.Ceiling((double)DS.Listings.Count / listingsPerPage);

        if (page > totalPages)
        {
            page = totalPages;
        }

        int startIndex = (page - 1) * listingsPerPage;
        int endIndex = Math.Min(startIndex + listingsPerPage, DS.Listings.Count);



        args.Player.SendInfoMessage($"Listings on the Auction House (Page {page}):");
        args.Player.SendMessage($"[c/ff0000:(ID)] - [item] [stack] [prefix] - (cost) - [TimeLeft] (in dd:hh:mm:ss). Page {page}/{totalPages}.", 0, 255, 255);

        bool loggedIn = args.Player.IsLoggedIn; // used for IRC handling.

        SortListingsByReturnDate();
        for (int i = startIndex; i < endIndex; i++)
        {
            Color color = Color.Yellow;
            DS.Listing listing = DS.Listings[i];
            TimeSpan timeLeft;

            if (loggedIn)
            {
                if (listing.ListerAccountID == args.Player.Account.ID)
                {
                    color = isSeller; // If the listing is the player's own, display it in purple.
                }
            }

            if (DateTime.Now < listing.ReturnDate)
            {
                timeLeft = listing.ReturnDate - DateTime.Now;
                string timeLeftFormatted = $"{timeLeft.Days:00}:{timeLeft.Hours:00}:{timeLeft.Minutes:00}:{timeLeft.Seconds:00}";
                args.Player.SendMessage($"[c/ff0000:({listing.ID})] - [i:{listing.ItemID}][{listing.ItemName()}] [{listing.Amount}] [{listing.PrefixName()}] - ( {((Money)listing.Price)}) - [[c/00ff00:{timeLeftFormatted}]].", color);
            }
            else if (DateTime.Now < listing.ExpirationDate)
            {
                timeLeft = listing.ExpirationDate - DateTime.Now;
                string timeLeftFormatted = $"{timeLeft.Days:00}:{timeLeft.Hours:00}:{timeLeft.Minutes:00}:{timeLeft.Seconds:00}";
                args.Player.SendMessage($"[c/ff0000:({listing.ID})] - [i:{listing.ItemID}][{listing.ItemName()}] [{listing.Amount}] [{listing.PrefixName()}] - ( {((Money)listing.Price)}) - [[c/ff0000:{timeLeftFormatted}]].", color);
            }
            else // This should never happen.
            {
                args.Player.SendErrorMessage("Report the listing below to a staff member!");
                args.Player.SendMessage($"[{listing.ID}] - {listing.Amount} {listing.ItemName()} {listing.PrefixName()} : {((Money)listing.Price)} — Expired", color);
            }
        }

        return;
    } 

    private void ListOwnlistingsAH(CommandArgs args) //ah list own [number]
    {
        if (!args.Player.IsLoggedIn) { args.Player.SendErrorMessage("You must be logged in to use this command!"); return; }

        if (DS.Listings.Count == 0)
        {
            args.Player.SendInfoMessage("There are no listings on the auction house at this time.");
            return;
        }

        int page = 1;
        if (args.Parameters.Count > 2)
        {
            if (!int.TryParse(args.Parameters[2], out page) || page <= 0)
            {
                args.Player.SendErrorMessage("Invalid page number.");
                return;
            }
        }
        List<DS.Listing> playerListings = new List<DS.Listing>();
        SortListingsByReturnDate(); 
        foreach (DS.Listing listing in DS.Listings)
        {
            if (listing.ListerAccountID == args.Player.Account.ID)
            {
                playerListings.Add(listing);
            }
        }
        if (playerListings.Count == 0)
        {
            args.Player.SendInfoMessage("You have no listings on the auction house at this time.");
            return;
        }

        const int listingsPerPage = 9;
        int totalPages = (int)Math.Ceiling((double)playerListings.Count / listingsPerPage); // Shouldn't be the count of the entire array. Just the count of the player's listings.

        if (page > totalPages)
        {
            page = totalPages;
        }

        int startIndex = (page - 1) * listingsPerPage;
        int endIndex = Math.Min(startIndex + listingsPerPage, playerListings.Count);

        args.Player.SendInfoMessage($"Your Listings on the Auction House (Page {page}):");
        args.Player.SendMessage($"[c/ff0000:(ID)] - [item] [stack] [prefix] - (cost) - [TimeLeft] (in dd:hh:mm:ss). Page {page}/{totalPages}.", 0, 255, 255);

        for (int i = startIndex; i < endIndex; i++)
        {
            DS.Listing listing = playerListings[i];
            TimeSpan timeLeft;

            if (DateTime.Now < listing.ReturnDate)
            {
                timeLeft = listing.ReturnDate - DateTime.Now;
                string timeLeftFormatted = $"{timeLeft.Days:00}:{timeLeft.Hours:00}:{timeLeft.Minutes:00}:{timeLeft.Seconds:00}";
                args.Player.SendMessage($"[c/ff0000:({listing.ID})] - [i:{listing.ItemID}][{listing.ItemName()}] [{listing.Amount}] [{listing.PrefixName()}] - ( {((Money)listing.Price)}) - [[c/00ff00:{timeLeftFormatted}]].", isSeller);
            }
            else if (DateTime.Now < listing.ExpirationDate)
            {
                timeLeft = listing.ExpirationDate - DateTime.Now;
                string timeLeftFormatted = $"{timeLeft.Days:00}:{timeLeft.Hours:00}:{timeLeft.Minutes:00}:{timeLeft.Seconds:00}";
                args.Player.SendMessage($"[c/ff0000:({listing.ID})] - [i:{listing.ItemID}][{listing.ItemName()}] [{listing.Amount}] [{listing.PrefixName()}] - ( {((Money)listing.Price)}) - [[c/ff0000:{timeLeftFormatted}]].", isSeller);
            }
            else // This should never happen.
            {
                args.Player.SendErrorMessage("Report the listing below to a staff member!");
                args.Player.SendMessage($"[{listing.ID}] - {listing.Amount} {listing.ItemName()} {listing.PrefixName()} : {((Money)listing.Price)} — Expired", isSeller);
            }
        }

        return;
    }


    private void SearchAH(CommandArgs args) 
    {
        if (args.Parameters.Count < 2)
        {
            args.Player.SendErrorMessage("Usage: /ah search <item1> <item2> ... [page].");
            return;
        }

        var searchTerms = new List<string>();
        int page = 1;

        // Parse last argument as page if it's an integer
        for (int i = 1; i < args.Parameters.Count; i++)
        {
            if (i == args.Parameters.Count - 1 && int.TryParse(args.Parameters[i], out int parsedPage))
            {
                page = parsedPage;
            }
            else
            {
                searchTerms.Add(args.Parameters[i].ToLowerInvariant());
            }
        }

        if (searchTerms.Count == 0)
        {
            args.Player.SendErrorMessage("Please specify at least one item name to search for.");
            return;
        }

        if (searchTerms.Count > 5) 
        {
            args.Player.SendErrorMessage("Please limit your search to at most 5 item names!");
            return;
        }

        if (searchTerms.Distinct().Count() != searchTerms.Count)
        {
            args.Player.SendErrorMessage("Please make sure all search terms are unique!");
            return;
        }

        List<DS.Listing> filteredListings = DS.Listings
            .Where(l => searchTerms.Any(term => l.ItemName().ToLowerInvariant().Contains(term)))
            .OrderBy(l => l.ItemID)
            .ThenBy(l => l.ReturnDate)
            .ToList();

        if (filteredListings.Count == 0)
        {
            args.Player.SendInfoMessage("No matching listings found for your search.");
            return;
        }

        const int listingsPerPage = 9;
        int totalPages = (int)Math.Ceiling((double)filteredListings.Count / listingsPerPage);

        if (page > totalPages) page = totalPages;
        if (page <= 0) page = 1;

        int startIndex = (page - 1) * listingsPerPage;
        int endIndex = Math.Min(startIndex + listingsPerPage, filteredListings.Count);

        args.Player.SendInfoMessage($"Auction House Search Results (Page {page}/{totalPages}) for: {string.Join(", ", searchTerms)}");
        args.Player.SendMessage($"[c/ff0000:(ID)] - [item] [stack] [prefix] - (cost) - [TimeLeft] (in dd:hh:mm:ss)", 0, 255, 255);

        for (int i = startIndex; i < endIndex; i++)
        {
            var listing = filteredListings[i];
            var color = Color.Yellow;

            if (args.Player.IsLoggedIn && listing.ListerAccountID == args.Player.Account.ID)
                color = isSeller; // highlight player’s own listing

            TimeSpan timeLeft;
            string timeColor;

            if (DateTime.Now < listing.ReturnDate)
            {
                timeLeft = listing.ReturnDate - DateTime.Now;
                timeColor = "00ff00"; // green
            }
            else if (DateTime.Now < listing.ExpirationDate)
            {
                timeLeft = listing.ExpirationDate - DateTime.Now;
                timeColor = "ff0000"; // red
            }
            else
            {
                args.Player.SendErrorMessage("Report the listing below to a staff member!");
                args.Player.SendMessage($"[{listing.ID}] - {listing.Amount} {listing.ItemName()} {listing.PrefixName()} : {((Money)listing.Price)} — Expired", color);
                continue;
            }

            string formatted = $"{timeLeft.Days:00}:{timeLeft.Hours:00}:{timeLeft.Minutes:00}:{timeLeft.Seconds:00}";

            args.Player.SendMessage(
                $"[c/ff0000:({listing.ID})] - [i:{listing.ItemID}][{listing.ItemName()}] [{listing.Amount}] [{listing.PrefixName()}] - ( {((Money)listing.Price)} ) - [[c/{timeColor}:{formatted}]]",
                color
            );
        }
    }

    private bool PullFromAH(CommandArgs args) // Needs a -force flag later...
    {
        if (!args.Player.IsLoggedIn) { args.Player.SendErrorMessage("You must be logged in to use this command!"); return false; }
        if (!SEconomyPlugin.Instance.GetBankAccount(args.Player).IsAccountEnabled) // This may not be necessary.
        {
            args.Player.SendErrorMessage("Your bank account is not enabled! You cannot access the auction house.");
            return false;
        }

        var SellerBank = SEconomyPlugin.Instance.GetBankAccount(args.Player.Account.Name);
        if (SellerBank == null)
        {
            args.Player.SendErrorMessage("Error! Bank account is null. Contact an Admin.");
            return false;
        }
        if (args.Parameters.Count < 2 && !args.Player.HasPermission("ah.admin"))
        {
            args.Player.SendErrorMessage("Usage: /ah pull <id>");
            return false;
        }

        else if (args.Parameters.Count < 2 && args.Player.HasPermission("ah.admin"))
        {
            args.Player.SendErrorMessage("Usage: /ah pull <id> -f[orce]");
            return false;
        }
        bool forcedPerm = false;
        if (args.Parameters.Count > 2 && args.Player.HasPermission("ah.admin") && (args.Parameters[2].ToLower() == "-force" || args.Parameters[2].ToLower() == "-f"))
        {
            forcedPerm = true;
        }

        if (!int.TryParse(args.Parameters[1], out var listingID))
        {
            args.Player.SendErrorMessage($"Error: {args.Parameters[1]} is not a valid listing ID.");
            return false;
        }
        if (!args.Player.InventorySlotAvailable && !forcedPerm)
        {
            args.Player.SendErrorMessage("Your inventory seems full. Clear some space before pulling listings off of the auction house!");
            return false;
        }

        DS.Listing listingToPull;


        foreach (DS.Listing listing in DS.Listings)
        {
            if (listing.ID == listingID)
            {
                listingToPull = listing;
                goto ListingExists;
            }
        }

        args.Player.SendErrorMessage($"The specified listing ID could not be found on the auction house.");
        return false;

    ListingExists:
        if (listingToPull.ListerAccountID != args.Player.Account.ID && !forcedPerm)
        {
            args.Player.SendErrorMessage("You cannot pull someone else's listing off of the auction house.");
            return false;
        }

        args.Player.SendSuccessMessage($"You have successfully taken {(!forcedPerm ? "your" : $"{listingToPull.ListerAccount}\'s")} listing, ({listingToPull.ID}) {listingToPull.Amount} {listingToPull.ItemName()} for {((Money)listingToPull.Price)}, off of the auction house. ");

        if (!forcedPerm)
        {
            args.Player.GiveItem(listingToPull.ItemID, listingToPull.Amount, listingToPull.PrefixID);
        }

        DS.Listings.Remove(listingToPull);
        DS.SaveToDisk();
        return true;
    }

    private bool BumpListingOnAH(CommandArgs args) 
    {
        if (!args.Player.IsLoggedIn) { args.Player.SendErrorMessage("You must be logged in to use this command!"); return false; }

        if (args.Parameters.Count < 2)
        {
            args.Player.SendErrorMessage("Usage: /ah bump <id>");
            return false;
        }

        if (!int.TryParse(args.Parameters[1], out var listingID))
        {
            args.Player.SendErrorMessage($"Error: {args.Parameters[1]} is not a valid listing ID.");
            return false;
        }

        DS.Listing listingToBump;

        foreach (DS.Listing listing in DS.Listings)
        {
            if (listing.ID == listingID)
            {
                listingToBump = listing;
                goto ListingExists;
            }
        }

        args.Player.SendErrorMessage($"The specified listing ID could not be found on the auction house.");
        return false;

        ListingExists:
        if (listingToBump.ListerAccountID != args.Player.Account.ID)
        {
            args.Player.SendErrorMessage("You cannot bump someone else's listing on the auction house.");
            return false;
        }
        if (listingToBump.ReturnDate > DateTime.Now.AddDays(3))
        {
            TimeSpan timeLeft = listingToBump.ReturnDate - DateTime.Now;
            string timeLeftString = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds",
                timeLeft.Days, timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds);

            args.Player.SendErrorMessage($"You cannot bump listings that have more than 3 days remaining. This listing still has {timeLeftString} until it is returned.");
            return false;
        }

        listingToBump.ReturnDate = DateTime.Now.AddDays(7); // Bump the return date by 7 days.
        listingToBump.ExpirationDate = DateTime.Now.AddDays(15); // Bump the expiration date by 15 days.

        args.Player.SendSuccessMessage($"You have successfully bumped your listing, ({listingToBump.ID}) {listingToBump.Amount} {listingToBump.ItemName()} for {((Money)listingToBump.Price)}, on the auction house. ");
        DS.SaveToDisk();

        return true;
    }


    private void OnPlayerLogin(PlayerPostLoginEventArgs args)
    {
        if (Frozen)
        {
            return;
        }

        TShock.Log.ConsoleInfo($"[Auction House] Checking {args.Player.Name} ({args.Player.Account.Name}) for payments to be made and return dates.");
        CheckForReturnListings(args.Player);
        CheckForReturnPayments(args.Player);
        CheckForExpiredListings();
        return;
    }

   

    private int GetPlayerListingCounts(int accountID)
    {
        int count = 0;
        foreach (DS.Listing listing in DS.Listings)
        {
            if (listing.ListerAccountID == accountID) { count++; }
        }
        return count;
    }

    private void CheckForExpiredListings() // EXPIRED
    {
        #region Clean up expired listings
        var expiredListings = new List<DS.Listing>(); // Needed to avoid the collection modification error

        foreach (DS.Listing listing in DS.Listings)
        {
            if (DateTime.Now >= listing.ExpirationDate)
            {
                expiredListings.Add(listing);
                TShock.Log.ConsoleInfo($"[Auction House] Listing {listing.ID} has expired and will be removed from the auction house.");
            }
        }

        foreach (DS.Listing expiredListing in expiredListings)
        {
            DS.Listings.Remove(expiredListing);
        }
        if (expiredListings.Count > 0) { TShock.Log.ConsoleInfo($"[Auction House] Removed {expiredListings.Count} expired listings from the auction house."); }
        #endregion

        #region Clean up expired payments
        var expiredPayments = new List<DS.Payment>();

        foreach (DS.Payment payment in DS.PaymentQueue)
        {
            if (DateTime.Now >= payment.DueBy)
            {
                expiredPayments.Add(payment);
                TShock.Log.ConsoleInfo($"[Auction House] Payment {payment.TransactionID} has expired and will be removed from the payment queue.");
            }
        }

        foreach (DS.Payment expiredPayment in expiredPayments)
        {
            DS.PaymentQueue.Remove(expiredPayment);
        }
        if (expiredPayments.Count > 0) { TShock.Log.ConsoleInfo($"[Auction House] Removed {expiredPayments.Count} expired payments from the payment queue."); }
        #endregion

        if (expiredListings.Count > 0 || expiredPayments.Count > 0) { DS.SaveToDisk(); } // Save to disk if we removed anything
        return;
    }

    #region Checks for payment and refunds
    private void CheckForReturnListings(TSPlayer player) 
    {
        var listingsToRemove = new List<DS.Listing>();
        foreach (DS.Listing listing in DS.Listings)
        {
            if (DateTime.Now >= listing.ReturnDate && listing.ListerAccountID == player.Account.ID)
            {
                var SellerBank = SEconomyPlugin.Instance.GetBankAccount(player.Account.Name);
                if (SellerBank != null)
                {
                    DS.Listing oldListing = listing;

                    if (player.InventorySlotAvailable)
                    {
                        SEconomyPlugin.Instance.WorldAccount.TransferTo(SellerBank, listing.Deposit, Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToReceiver, "Refunded deposit", string.Format("Returned deposit for {0} {1}", listing.Amount, listing.ItemName()));
                        
                        TShock.Log.ConsoleInfo($"[Auction House] Listing {listing.ID} has been returned to {player.Name}.");
                        listingsToRemove.Add(listing);
                        
                        GiveItemDelay(player, oldListing.ItemID, oldListing.Amount, oldListing.PrefixID);
                        NotificationDelay(player, $"You have been refunded your item(s) and deposit for {oldListing.Amount} of {oldListing.ItemName()}. Listing ID: {oldListing.ID}.");
                    }
                    else
                    {
                        player.SendErrorMessage($"Your deposit has been returned for {oldListing.Amount} {oldListing.ItemName()} (Listing ID: {oldListing.ID}), but your inventory was full and your item(s) could not be refunded at this time. Try logging in and out, or executing /ah.");
                    }
                }
                else
                {
                    player.SendErrorMessage("Error! Could not find your bank account for listing return. Contact an Admin.");
                    foreach (DS.Listing listingToRemove in listingsToRemove)
                    {
                        DS.Listings.Remove(listingToRemove);
                    }
                    return;
                }
            }
        }

        foreach (DS.Listing listingToRemove in listingsToRemove)
        {
            DS.Listings.Remove(listingToRemove);
        }

        if (listingsToRemove.Count > 0)
        {
            TShock.Log.ConsoleError($"[Auction House] Returned {listingsToRemove.Count} listings from the auction house to {player.Name} ({player.Account.Name}).");
            DS.SaveToDisk();
        }

        return;
    }
    private void CheckForReturnPayments(TSPlayer player)
    {
        List<DS.Payment> paymentsToRemove = new List<DS.Payment>();

        foreach (DS.Payment payment in DS.PaymentQueue)
        {
            var SellerBank = SEconomyPlugin.Instance.GetBankAccount(player.Account.Name);
            if (SellerBank != null)
            {

                if (payment.AccountID != player.Account.ID) { continue; }

                SEconomyPlugin.Instance.WorldAccount.TransferTo(SellerBank, payment.AmountDue, Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToReceiver,
                                                                                       payment.Reason, payment.Reason);
                paymentsToRemove.Add(payment);
                NotificationDelay(player, $"You have received {((Money)payment.AmountDue)} for {payment.Reason}.");
                TShock.Log.ConsoleInfo($"[Auction House] Player {player.Name} ({player.Account.Name}) has received {((Money)payment.AmountDue)} for {payment.Reason}.");
            }
            else
            {
                player.SendErrorMessage("Error! Could not find your bank account for listing return. Contact an Admin.");
                foreach (DS.Payment paymentToRemove in paymentsToRemove)
                {
                    DS.PaymentQueue.Remove(paymentToRemove);
                }
                return;
            }
        }

        // Remove all of the payments that were made
        foreach (DS.Payment paymentToRemove in paymentsToRemove)
        {
            DS.PaymentQueue.Remove(paymentToRemove);
        }

        if (paymentsToRemove.Count > 0)
        {
            TShock.Log.ConsoleInfo($"[Auction House] Payed out {paymentsToRemove.Count} queued payments to {player.Name} ({player.Account.Name}).");
            DS.SaveToDisk();
        }
        return;
    }

    #endregion

    #region Misc Helper Functions
    private async void NotificationDelay(TSPlayer player, string msg, int time = 2000)
    {
        await Task.Delay(time);
        player.SendSuccessMessage(msg);
        return;
    }
    private async void GiveItemDelay(TSPlayer player, int type, int stack, byte prefix, int time = 2000)
    {
        await Task.Delay(time);
        player.GiveItem(type, stack, prefix);
        return;
    }
    private void SortListingsByReturnDate()
    {
        DS.Listings.Sort((x, y) => y.ReturnDate.CompareTo(x.ReturnDate)); // Sort by return date (newest first)
    }
    #endregion

    #region Debug / Admin Only
    private void DEBUGGetAllPayments(CommandArgs args)
    {
        if (DS.PaymentQueue.Count == 0)
        {
            args.Player.SendInfoMessage("There are no payments in the queue.");
            return;
        }

        args.Player.SendInfoMessage("Payments in the queue:");
        foreach (DS.Payment payment in DS.PaymentQueue)
        {
            args.Player.SendMessage($"Payment ID: {payment.TransactionID}, Amount: {((Money)payment.AmountDue)}, AccountID: {payment.AccountID}, Due By: {payment.DueBy}", Color.Yellow);
        }
    }

    private void DEBUGListAllListings(CommandArgs args)
    {
        if (DS.Listings.Count == 0)
        {
            args.Player.SendInfoMessage("There are no listings on the auction house at this time.");
            return;
        }

        args.Player.SendInfoMessage("Listings on the Auction House:");
        foreach (DS.Listing listing in DS.Listings)
        {
            args.Player.SendMessage($"Listing ID: {listing.ID}, Item: {listing.ItemName()}, Amount: {listing.Amount}, Prefix: {listing.PrefixName()}, Price: {((Money)listing.Price)}, Deposit: {((Money)listing.Deposit)}, Return Date: {listing.ReturnDate}, Expiration Date: {listing.ExpirationDate}, Lister: {listing.ListerAccount}", Color.Yellow);
        }
    }

    private void FreezeAH(CommandArgs args) 
    { 
        Frozen = !Frozen;
        args.Player.SendSuccessMessage($"The auction House is now {(Frozen ? "frozen" : "unfrozen")}. Login checks {(Frozen ? "will not" : "will")} occur.");
        return;
    
    }
    #endregion



    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            PlayerHooks.PlayerPostLogin -= new PlayerHooks.PlayerPostLoginD(OnPlayerLogin);
            DS.SaveToDisk();
        }
        base.Dispose(disposing);
    }
}