import type { Interaction } from "discord.js";
import { TextChannel, MessageFlags } from "discord.js";
import { config } from "@/lib/config";
import { AuroraClient } from "@/lib/BotClient";
import { buildFeedbackMessage, getFeedbackModal } from "./feedback.view";
import { FEEDBACK_CUSTOM_IDS, type FeedbackType, type FeedbackData } from "./feedback.types";
import { UserError } from "@/lib/errors";

export const handleFeedbackInteraction = async (interaction: Interaction) => {
    // Handle select menu for choosing feedback type
    if (interaction.isStringSelectMenu() && interaction.customId === "feedback_select_type") {
        const feedbackType = interaction.values[0] as FeedbackType;

        if (!feedbackType) {
            throw new UserError("Invalid feedback type selected.");
        }

        const modal = getFeedbackModal(feedbackType);
        await interaction.showModal(modal);
        return;
    }

    // Handle modal submission
    if (interaction.isModalSubmit() && interaction.customId.startsWith(FEEDBACK_CUSTOM_IDS.MODAL)) {
        // Extract feedback type from customId (format: feedback_modal_FEATURE_REQUEST)
        const parts = interaction.customId.split("_");
        const feedbackType = parts.slice(2).join("_") as FeedbackType;

        console.log(`Processing feedback modal. CustomId: ${interaction.customId}, Extracted type: ${feedbackType}`);

        if (!feedbackType || !["FEATURE_REQUEST", "BUG_REPORT", "GENERAL"].includes(feedbackType)) {
            console.error(`Invalid feedback type extracted: ${feedbackType} from customId: ${interaction.customId}`);
            throw new UserError("An error occurred processing your feedback. Please try again.");
        }

        if (!config.feedbackChannelId) {
            throw new UserError("Feedback channel is not configured. Please contact an administrator.");
        }

        // Parse modal inputs
        const title = interaction.fields.getTextInputValue(FEEDBACK_CUSTOM_IDS.TITLE_FIELD);
        const description = interaction.fields.getTextInputValue(FEEDBACK_CUSTOM_IDS.DESCRIPTION_FIELD);

        // Build feedback data
        const feedbackData: FeedbackData = {
            type: feedbackType,
            title,
            description,
            userId: interaction.user.id,
            username: interaction.user.username,
            timestamp: new Date()
        };

        // Get feedback channel
        const channel = await AuroraClient.channels.fetch(config.feedbackChannelId).catch(() => null) as TextChannel | null;

        if (!channel) {
            throw new UserError("Feedback channel not found. Please contact an administrator.");
        }

        // Build and send beautiful message
        const containers = buildFeedbackMessage(feedbackData);

        const feedbackMessage = await channel.send({
            components: containers as any,
            flags: MessageFlags.IsComponentsV2
        });

        // Add reaction votes
        await feedbackMessage.react("👍");
        await feedbackMessage.react("👎");

        // Confirm to user
        await interaction.reply({
            content: "✨ **Feedback Submitted**\nYour feedback has been submitted successfully! Thank you for helping improve Aurora.",
            flags: MessageFlags.Ephemeral
        });
    }
};
