// DragonX Wallet - ImGui Edition
// Copyright 2024-2026 The Hush Developers
// Released under the GPLv3

#pragma once

#include "../material/material.h"
#include "../../embedded/IconsMaterialDesign.h"
#include "../../config/version.h"
#include "imgui.h"
#include <string>
#include <vector>
#include <functional>
#include <cstring>

namespace dragonx {
namespace ui {
namespace screens {

using namespace material;

// ============================================================================
// Send Screen
// ============================================================================
// Material Design form for sending DRGX

/**
 * @brief Address book entry
 */
struct AddressBookEntry {
    std::string label;
    std::string address;
};

/**
 * @brief Send form data
 */
struct SendFormData {
    char toAddress[512] = {0};
    char amount[32] = {0};
    char memo[512] = {0};
    bool useShielded = true;
    double fee = DRAGONX_DEFAULT_FEE;
    
    // Validation state
    bool addressValid = false;
    bool amountValid = false;
    std::string addressError;
    std::string amountError;
};

/**
 * @brief Send screen with Material form
 */
class SendScreen {
public:
    SendScreen() = default;
    
    void setAvailableBalance(double shielded, double transparent) {
        m_shieldedBalance = shielded;
        m_transparentBalance = transparent;
    }
    
    void setAddressBook(const std::vector<AddressBookEntry>& entries) {
        m_addressBook = entries;
    }
    
    void setOnSend(std::function<void(const SendFormData&)> callback) {
        m_onSend = callback;
    }
    
    void setOnCancel(std::function<void()> callback) {
        m_onCancel = callback;
    }
    
    void setOnValidateAddress(std::function<bool(const std::string&)> callback) {
        m_onValidateAddress = callback;
    }
    
    void clear() {
        memset(m_formData.toAddress, 0, sizeof(m_formData.toAddress));
        memset(m_formData.amount, 0, sizeof(m_formData.amount));
        memset(m_formData.memo, 0, sizeof(m_formData.memo));
        m_formData.useShielded = true;
        m_formData.addressValid = false;
        m_formData.amountValid = false;
        m_formData.addressError.clear();
        m_formData.amountError.clear();
    }
    
    void render();
    
private:
    void renderFromSelector();
    void renderAddressField();
    void renderAmountField();
    void renderMemoField();
    void renderFeeDisplay();
    void renderActions();
    void validateForm();
    
    SendFormData m_formData;
    double m_shieldedBalance = 0.0;
    double m_transparentBalance = 0.0;
    std::vector<AddressBookEntry> m_addressBook;
    
    std::function<void(const SendFormData&)> m_onSend;
    std::function<void()> m_onCancel;
    std::function<bool(const std::string&)> m_onValidateAddress;
    
    bool m_showAddressBook = false;
};

// ============================================================================
// Implementation
// ============================================================================

inline void SendScreen::render() {
    float availWidth = ImGui::GetContentRegionAvail().x;
    float formWidth = std::min(availWidth, 500.0f);
    float offsetX = (availWidth - formWidth) * 0.5f;
    
    ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX);
    ImGui::BeginGroup();
    {
        // Title
        Typography::instance().text(TypeStyle::H5, "Send DRGX");
        ImGui::Dummy(ImVec2(0, spacing::dp(3)));
        
        // Form card
        CardSpec cardSpec;
        cardSpec.elevation = 2;
        cardSpec.padding = spacing::dp(3);
        cardSpec.width = formWidth;
        
        if (BeginCard(cardSpec)) {
            // From selector (shielded vs transparent)
            renderFromSelector();
            ImGui::Dummy(ImVec2(0, spacing::dp(3)));
            
            // To address field
            renderAddressField();
            ImGui::Dummy(ImVec2(0, spacing::dp(2)));
            
            // Amount field
            renderAmountField();
            ImGui::Dummy(ImVec2(0, spacing::dp(2)));
            
            // Memo field (only for shielded)
            if (m_formData.useShielded) {
                renderMemoField();
                ImGui::Dummy(ImVec2(0, spacing::dp(2)));
            }
            
            // Fee display
            renderFeeDisplay();
            ImGui::Dummy(ImVec2(0, spacing::dp(3)));
            
            // Divider
            ImGui::GetWindowDrawList()->AddLine(
                ImVec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y),
                ImVec2(ImGui::GetCursorScreenPos().x + formWidth - spacing::dp(6), ImGui::GetCursorScreenPos().y),
                ImGui::GetColorU32(Divider()),
                1.0f
            );
            ImGui::Dummy(ImVec2(0, spacing::dp(2)));
            
            // Action buttons
            renderActions();
            
            EndCard();
        }
    }
    ImGui::EndGroup();
}

inline void SendScreen::renderFromSelector() {
    Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "SEND FROM");
    ImGui::Dummy(ImVec2(0, spacing::dp(1)));
    
    float buttonWidth = 200.0f;
    
    // Shielded option
    ImGui::PushID("from_shielded");
    {
        bool selected = m_formData.useShielded;
        ImVec4 bgColor = selected ? colors::withAlpha(Primary(), 0.12f) : Surface();
        ImVec4 borderColor = selected ? Primary() : Divider();
        
        ImGui::PushStyleColor(ImGuiCol_Button, bgColor);
        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(Primary(), 0.16f));
        ImGui::PushStyleColor(ImGuiCol_Border, borderColor);
        ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, selected ? 2.0f : 1.0f);
        ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f);
        
        char label[128];
        snprintf(label, sizeof(label), ICON_MD_SHIELD " Shielded\n%.4f DRGX", m_shieldedBalance);
        
        if (ImGui::Button(label, ImVec2(buttonWidth, 60))) {
            m_formData.useShielded = true;
        }
        
        ImGui::PopStyleVar(2);
        ImGui::PopStyleColor(3);
    }
    ImGui::PopID();
    
    ImGui::SameLine(0, spacing::dp(2));
    
    // Transparent option
    ImGui::PushID("from_transparent");
    {
        bool selected = !m_formData.useShielded;
        ImVec4 bgColor = selected ? colors::withAlpha(Secondary(), 0.12f) : Surface();
        ImVec4 borderColor = selected ? Secondary() : Divider();
        
        ImGui::PushStyleColor(ImGuiCol_Button, bgColor);
        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(Secondary(), 0.16f));
        ImGui::PushStyleColor(ImGuiCol_Border, borderColor);
        ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, selected ? 2.0f : 1.0f);
        ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f);
        
        char label[128];
        snprintf(label, sizeof(label), ICON_MD_DESCRIPTION " Transparent\n%.4f DRGX", m_transparentBalance);
        
        if (ImGui::Button(label, ImVec2(buttonWidth, 60))) {
            m_formData.useShielded = false;
        }
        
        ImGui::PopStyleVar(2);
        ImGui::PopStyleColor(3);
    }
    ImGui::PopID();
}

inline void SendScreen::renderAddressField() {
    TextFieldSpec spec;
    spec.label = "Recipient Address";
    spec.placeholder = "Enter DRGX address...";
    spec.variant = TextFieldVariant::Outlined;
    spec.width = -1;  // Full width
    spec.hasError = !m_formData.addressError.empty();
    spec.helperText = m_formData.addressError.empty() ? 
        "z-address (shielded) or t-address (transparent)" : 
        m_formData.addressError.c_str();
    spec.leadingIcon = ICON_MD_MARKUNREAD_MAILBOX;
    spec.trailingIcon = ICON_MD_MENU_BOOK;  // Address book
    
    TextFieldResult result = TextField("send_address", m_formData.toAddress, 
                                       sizeof(m_formData.toAddress), spec);
    
    if (result.trailingIconClicked) {
        m_showAddressBook = !m_showAddressBook;
    }
    
    if (result.changed) {
        // Validate address
        if (m_onValidateAddress) {
            m_formData.addressValid = m_onValidateAddress(m_formData.toAddress);
            if (!m_formData.addressValid && strlen(m_formData.toAddress) > 10) {
                m_formData.addressError = "Invalid address format";
            } else {
                m_formData.addressError.clear();
            }
        }
    }
    
    // Address book dropdown
    if (m_showAddressBook && !m_addressBook.empty()) {
        ImGui::Dummy(ImVec2(0, spacing::dp(1)));
        
        CardSpec cardSpec;
        cardSpec.elevation = 8;
        cardSpec.padding = spacing::dp(1);
        
        if (BeginCard(cardSpec)) {
            BeginList("address_book_list", false);
            
            for (const auto& entry : m_addressBook) {
                ListItemSpec itemSpec;
                itemSpec.leadingIcon = "👤";
                itemSpec.primaryText = entry.label.c_str();
                itemSpec.secondaryText = entry.address.substr(0, 20).c_str();
                itemSpec.dividerBelow = true;
                
                if (ListItem(itemSpec)) {
                    strncpy(m_formData.toAddress, entry.address.c_str(), 
                           sizeof(m_formData.toAddress) - 1);
                    m_formData.addressValid = true;
                    m_formData.addressError.clear();
                    m_showAddressBook = false;
                }
            }
            
            EndList();
            EndCard();
        }
    }
}

inline void SendScreen::renderAmountField() {
    TextFieldSpec spec;
    spec.label = "Amount";
    spec.placeholder = "0.00000000";
    spec.variant = TextFieldVariant::Outlined;
    spec.width = 200.0f;
    spec.hasError = !m_formData.amountError.empty();
    spec.helperText = m_formData.amountError.c_str();
    spec.suffix = "DRGX";
    
    TextFieldResult result = TextField("send_amount", m_formData.amount, 
                                       sizeof(m_formData.amount), spec);
    
    if (result.changed) {
        // Validate amount
        double amt = atof(m_formData.amount);
        double maxBalance = m_formData.useShielded ? m_shieldedBalance : m_transparentBalance;
        
        if (amt <= 0) {
            m_formData.amountValid = false;
            if (strlen(m_formData.amount) > 0) {
                m_formData.amountError = "Amount must be greater than 0";
            }
        } else if (amt > maxBalance - m_formData.fee) {
            m_formData.amountValid = false;
            m_formData.amountError = "Insufficient balance";
        } else {
            m_formData.amountValid = true;
            m_formData.amountError.clear();
        }
    }
    
    ImGui::SameLine();
    
    // Max button
    if (TextButton("MAX")) {
        double maxBalance = m_formData.useShielded ? m_shieldedBalance : m_transparentBalance;
        double maxAmount = maxBalance - m_formData.fee;
        if (maxAmount > 0) {
            snprintf(m_formData.amount, sizeof(m_formData.amount), "%.8f", maxAmount);
            m_formData.amountValid = true;
            m_formData.amountError.clear();
        }
    }
}

inline void SendScreen::renderMemoField() {
    TextFieldSpec spec;
    spec.label = "Memo (encrypted)";
    spec.placeholder = "Optional private message...";
    spec.variant = TextFieldVariant::Outlined;
    spec.width = -1;
    spec.multiline = true;
    spec.helperText = "512 characters max. Only visible to recipient.";
    spec.maxLength = 512;
    
    TextField("send_memo", m_formData.memo, sizeof(m_formData.memo), spec);
}

inline void SendScreen::renderFeeDisplay() {
    ImGui::BeginGroup();
    {
        Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), "Network Fee:");
        ImGui::SameLine();
        
        char feeStr[32];
        snprintf(feeStr, sizeof(feeStr), "%.8f DRGX", m_formData.fee);
        Typography::instance().text(TypeStyle::Body2, feeStr);
    }
    ImGui::EndGroup();
    
    // Total if amount is valid
    if (m_formData.amountValid) {
        double amt = atof(m_formData.amount);
        double total = amt + m_formData.fee;
        
        ImGui::BeginGroup();
        {
            Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "Total:");
            ImGui::SameLine();
            
            char totalStr[32];
            snprintf(totalStr, sizeof(totalStr), "%.8f DRGX", total);
            Typography::instance().textColored(TypeStyle::Body1, Primary(), totalStr);
        }
        ImGui::EndGroup();
    }
}

inline void SendScreen::renderActions() {
    float buttonWidth = 120.0f;
    float availWidth = ImGui::GetContentRegionAvail().x;
    
    // Right-align buttons
    ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - buttonWidth * 2 - spacing::dp(2));
    
    // Cancel button
    if (TextButton("CANCEL")) {
        if (m_onCancel) m_onCancel();
    }
    
    ImGui::SameLine(0, spacing::dp(2));
    
    // Send button
    bool canSend = m_formData.addressValid && m_formData.amountValid;
    
    ImGui::BeginDisabled(!canSend);
    if (ContainedButton("SEND")) {
        if (m_onSend) m_onSend(m_formData);
    }
    ImGui::EndDisabled();
}

inline void SendScreen::validateForm() {
    // Address validation
    if (strlen(m_formData.toAddress) == 0) {
        m_formData.addressValid = false;
        m_formData.addressError = "Address is required";
    }
    
    // Amount validation
    if (strlen(m_formData.amount) == 0) {
        m_formData.amountValid = false;
        m_formData.amountError = "Amount is required";
    }
}

} // namespace screens
} // namespace ui
} // namespace dragonx
