--██████╗ ██████╗ ██████╗ ███████╗
--██╔════╝██╔═══██╗██╔══██╗██╔════╝
--██║     ██║   ██║██║  ██║█████╗  
--██║     ██║   ██║██║  ██║██╔══╝  
--╚██████╗╚██████╔╝██████╔╝███████╗
-- ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝     
local descriptionLabel = nil 
local descriptionPosition = nil
local descriptionProps = nil
local descriptionwhitelist = nil
local nameMailbox_valid = nil
local whitelistMailbox_valid = nil
local pos = false
local table_builder_manage = nil
local position = {}
local MarkerCreation = {}
local colorIconLabel = "rgba(255, 0, 0, 1)"
local colorIconPosition = "rgba(25, 0, 0, 1)"
local colorIconProps = "rgba(255, 0, 0, 1)"
local colorIconwhitelist = "rgba(255, 0, 0, 1)"
local propsmodel = nil
local propsenable = false
local heading = false
local disabledbool = true
onCreation = false

function initialiseDefaultValue()
    descriptionLabel = Locale["no_data"] 
    descriptionPosition = Locale["no_data"]
    descriptionProps = Locale["no_data"]
    descriptionwhitelist = Locale["no_data"]
    propsmodel = nil

    propsenable = false
    heading = false

    colorIconLabel = "rgba(255, 0, 0, 1)"
    colorIconPosition = "rgba(255, 0, 0, 1)"
    colorIconProps = "rgba(255, 0, 0, 1)"
    colorIconwhitelist = "rgba(255, 0, 0, 1)"

    nameMailbox_valid = nil
    whitelistMailbox_valid = nil
    pos = false
    onCreation = false
    MarkerCreation = {}
    position = {}
end

function main_menu_builder()
    Wait(200)
    
    elements = {
        { 
            title = Locale["create_mailbox"],
            icon = 'fa-solid fa-plus',  
            description = Locale["create_mailbox_description"],  
            arrow = true,
            iconColor = "rgba(0, 255, 72, 1)",
            onSelect = function(args)
                initialiseDefaultValue()
                Wait(150)
                create_mailbox()
            end
        },

        { 
            title = Locale["manage_mailbox"],
            icon = 'fa-solid fa-database', 
            description = Locale["manage_mailbox_description"], 
            arrow = true,
            iconColor = "rgba(0, 255, 72, 1)",
            onSelect = function(args)
                table_builder_manage = nil
                ESX.TriggerServerCallback('mailbox:listing', function(result)
                    table_builder_manage = result 
                end, id)

                while table_builder_manage == nil do
                    Wait(1)
                end

                manage_builder_mailbox()
            end
        },
    }

    lib.registerContext({
        id = 'main_menu_builder',
        title = Locale["builder_menu_header"],
        options = elements,
    })
    lib.showContext('main_menu_builder')
end

function manage_builder_mailbox()
    pos_edit = false
    elements = {}
    for k,v in pairs(listing) do
        table.insert(elements, {
            title = "["..v.id.."] "..v.label, 
            icon = 'fa-solid fa-envelopes-bulk',  
            arrow = true,
            iconColor = "rgba(255, 218, 72, 1)",
            onSelect = function(args)
                local action_manage = lib.inputDialog("["..v.id.."] "..v.label, {
                    {type = 'select', label = Locale["choose_option"], required = true, options = {
                        { value = 'edit_pos', label = Locale["edit_pos"]},
                        { value = 'delete', label = Locale["delete_mailbox"]},
                    }} 
                })

                if action_manage ~= nil then
                    if action_manage[1] == "delete" then
                        TriggerServerEvent('mailbox:deletemailbox', v.id,  v.position, v.props)
                    elseif action_manage[1] == "edit_pos" then
                        while pos_edit == false do
                            local playerpos = GetEntityCoords(PlayerPedId())
                            local headingpos = GetEntityHeading(PlayerPedId())
                            DrawMarker(0, playerpos.x, playerpos.y, playerpos.z + 1.3, 0.0, 0.0, 0.0, 0.0,0.0,0.0, 0.5, 0.5, 0.5, 255, 0, 0, 255, true, true, p19, false)  
                            Pawal.Text({message = Locale["place_point"]})
                            if IsControlJustPressed(0, 51) then
                                pos_edit = true
                                heading = headingpos
                                position = playerpos
                                Wait(150)
                                TriggerServerEvent('mailbox:editpos', v.id, position, heading, v.props, v.position)
                            end
                            Wait(0)
                        end
                    end
                else
                    manage_builder_mailbox()
                end
            end
        })
    end 

    if #listing == 0 then
        table.insert(elements, {
            title = Locale["no_mailbox"],
            disabled = true,
        })
    end

    lib.registerContext({
        id = 'manage_builder',
        title = Locale["manage_builder_header"],
        options = elements,
        menu = 'main_menu_builder',
    })
    lib.showContext('manage_builder')
end

function create_mailbox()
    if descriptionLabel ~= Locale["no_data"] and descriptionPosition ~= Locale["no_data"] and descriptionwhitelist ~= Locale["no_data"] and descriptionProps ~= Locale["no_data"] then
        disabledbool = false
    else
        disabledbool = true
    end

    Wait(50)

    elements = {
        { 
            title = Locale["builder_label"],
            description = descriptionLabel, 
            icon = "fa-solid fa-circle", 
            arrow = true,
            iconColor = colorIconLabel,
            onSelect = function(args)
                local nameMailbox = lib.inputDialog(Locale["name_mailbox_input"], {
                    { type = 'input', required = true, options = {}},
                })

                if nameMailbox ~= nil then
                    nameMailbox_valid = nameMailbox[1]
                    descriptionLabel = Locale["save"]
                    colorIconLabel = "rgba(0, 255, 72, 1)"
                    Wait(150)
                    create_mailbox()
                else
                    create_mailbox()
                end
            end
        },

        { 
            title = Locale["builder_position"],
            description = descriptionPosition, 
            arrow = true,
            icon = "fa-solid fa-circle", 
            iconColor = colorIconPosition,
            onSelect = function(args)
                while pos == false do
                    local playerpos = GetEntityCoords(PlayerPedId())
                    local headingpos = GetEntityHeading(PlayerPedId())
                    DrawMarker(0, playerpos.x, playerpos.y, playerpos.z + 1.3, 0.0, 0.0, 0.0, 0.0,0.0,0.0, 0.5, 0.5, 0.5, 255, 0, 0, 255, true, true, p19, false)  
                    Pawal.Text({message = Locale["place_point"]})
                    if IsControlJustPressed(0, 51) then
                        pos = true
                        onCreation = true
                        heading = headingpos
                        descriptionPosition = Locale["save"]
                        position = playerpos
                        print(position)
                        MarkerCreation["PositionProperty"] = {pos = position, rgb = {r = 0, g = 120, b = 255}}  
                        colorIconPosition = "rgba(0, 255, 72, 1)"
                        Wait(150)
                        create_mailbox()
                    end
                    Wait(0)
                end
            end
        },

        { 
            title = Locale["whitelist_mailbox"],
            description = descriptionwhitelist, 
            iconColor = colorIconwhitelist,
            arrow = true,
            icon = "fa-solid fa-circle", 
            onSelect = function(args)
                local input = lib.inputDialog(Locale["whitelist_mailbox"], {
                    {type = 'select', required = true, options = {
                        { value = 'job', label = Locale["job_select"]},
                        { value = 'civilian', label = Locale["civilian_select"]},
                        { value = 'no', label = Locale["libre_select"]},
                    }},
                })

                if input ~= nil then
                    if input[1] == "job" then
                        local whitelistMailbox = lib.inputDialog(Locale["job_mailbox_input"], {
                            { type = 'input', required = true, options = {}},
                        })
        
                        if whitelistMailbox ~= nil then
                            whitelistMailbox_valid = whitelistMailbox[1]
                            descriptionwhitelist = Locale["save"]
                            colorIconwhitelist = "rgba(0, 255, 72, 1)"
                            Wait(150)
                            create_mailbox()
                        else
                            create_mailbox()
                        end
                    elseif input[1] == "civilian" then
                        local whitelistMailbox = lib.inputDialog(Locale["civilan_mailbox_input"], {
                            { type = 'input', required = true, options = {}},
                        })
                        
                        if whitelistMailbox ~= nil then
                            whitelistMailbox_valid = whitelistMailbox[1]
                            descriptionwhitelist = Locale["save"]
                            colorIconwhitelist = "rgba(0, 255, 72, 1)"
                            Wait(150)
                            create_mailbox()
                        else
                            create_mailbox()
                        end
                    elseif input[1] == "no" then
                        whitelistMailbox_valid = "no"
                        descriptionwhitelist = Locale["save"]
                        colorIconwhitelist = "rgba(0, 255, 72, 1)"
                        Wait(150)
                        create_mailbox()
                    end
                else
                    create_mailbox()
                end
            end
        },
    }

    if Config.enableProps == true then
        table.insert(elements, {
            title = Locale["builder_props"],
            description = descriptionProps, 
            iconColor = colorIconProps,
            arrow = true,
            icon = "fa-solid fa-circle", 
            onSelect = function(args)
                local input = lib.inputDialog(Locale["activate_props"], {
                    {type = 'select', required = true, options = {
                        { value = 'yes', label = Locale["yes"]},
                        { value = 'no', label = Locale["no"]},
                    }},
                })

                if input ~= nil then
                    if input[1] == "yes" then
                        type_props()
                    else
                        propsenable = "no"
                        descriptionProps = Locale["save"]
                        colorIconProps = "rgba(0, 255, 72, 1)"
                        Wait(150)
                        create_mailbox()
                    end
                else
                    create_mailbox()
                end
            end
        })
    end
    
    table.insert(elements, {
        title = Locale["validate"],
        icon = 'fa-solid fa-check',
        arrow = true,
        disabled = disabledbool,
        iconColor = "rgba(0, 243, 72, 1)", 
        onSelect = function(args)
            TriggerServerEvent('mailbox:create', nameMailbox_valid, position, heading, whitelistMailbox_valid, propsenable, propsmodel)
            Wait(50)
            initialiseDefaultValue()
        end       
    })
    
    lib.registerContext({
        id = 'create_mailbox',
        title = Locale["builder_menu_header"],
        options = elements,
        menu = 'main_menu_builder',
        onExit = function()
            initialiseDefaultValue()
        end,
        onBack = function()
            initialiseDefaultValue()
        end
    })
    lib.showContext('create_mailbox')
end

function type_props()
    local elements = {}

    for k,v in pairs(Config.propsname) do
        print(v.img)
        table.insert(elements, {
            title = v.label,
            image = "nui://pw-mailbox/images/"..v.img..".png",
            onSelect = function(args)
                propsmodel = v.name
                descriptionProps = Locale["save"]
                colorIconProps = "rgba(0, 255, 72, 1)"
                propsenable = "yes"
                Wait(150)
                create_mailbox()
            end
        })
    end

    lib.registerContext({
        id = 'type_props',
        title = Locale["builder_menu_header"],
        options = elements,
        onExit = function()
            initialiseDefaultValue()
        end,
        onBack = function()
            initialiseDefaultValue()
        end
    })
    lib.showContext('type_props')
end

Keys.Register('F11', 'pw_mailbox', 'Ouvrir le menu mailbox', function()
    TriggerServerEvent('mailbox:openmenu')
end)

RegisterNetEvent('mailbox:openmenu')
AddEventHandler('mailbox:openmenu', function()
    main_menu_builder()
end)

Citizen.CreateThread(function()
    while true do
        if onCreation == true then
            for k,v in pairs(MarkerCreation) do
                local dst = GetDistanceBetweenCoords(GetEntityCoords(PlayerPedId()), v.pos, true)
                DrawMarker(0, v.pos.x, v.pos.y, v.pos.z, 0.0, 0.0, 0.0, 0.0,0.0,0.0, 0.5, 0.5, 0.5, 255, 0, 0, 255, true, true, p19, false)  
                Pawal.Text({message = Locale["preview_point"]})
            end
        end
        Citizen.Wait(0)
    end
end)