import asyncHandler from "#middlewares/asyncHandler";
import { TransactionHistory, validateTransactionHistory } from "#models/transaction_history_model";
import { Task } from "#models/task_model";
import { UserWallet } from "#models/user_wallet_model";
import { Referral } from "#models/referral_model";


const submitTransaction = asyncHandler(async (req, res) => {
    const { taskId, userId, mcqResponse, linkOpened } = req.body;

    console.log(taskId, userId, mcqResponse, linkOpened, "taskId, userId, mcqResponse, linkOpened");

    // Find task details
    const taskDetails = await Task.findById(taskId);
    if (!taskDetails) return res.status(404).json({ status: false, message: "Task not found" });

    // Find user details
    const userDetails = await UserWallet.findById(userId);
    if (!userDetails) return res.status(404).json({ status: false, message: "User not found" });

    // Find referral details
    const referralBy = await Referral.findOne({ referred_user: userDetails?._id });

    let transactionData = {
        taskId: taskId,
        userId: userId,
        referrerId: referralBy?.referring_by || null,
        rewardAmount: 0, // Default reward amount
        referrerRewardAmount: 0,
        isUserClaimed: false,
        isReferrerClaimed: false,
        taskType: taskDetails.type,
        status: 'completed'
    };

    if (taskDetails.type === 'MCQ') {
        if (mcqResponse === taskDetails.mcq.correctAnswer) {
            // Calculate reward for correct MCQ answer
            const rewardAmount = userDetails.isPremiumUser ? taskDetails.reward_amount * 0.08 : taskDetails.reward_amount * 0.04;
            transactionData.rewardAmount = taskDetails.reward_amount;
            transactionData.referrerRewardAmount = referralBy ? rewardAmount : 0;
            transactionData.isCorrectAnswer = true;
            transactionData.mcqResponse = mcqResponse;
            const transaction = new TransactionHistory(transactionData);
            await transaction.save();

            res.status(201).json({ status: true, message: "You give Correct Answer Congrates ", transaction });
        } else {
            transactionData.isUserClaimed = true;
            transactionData.isCorrectAnswer = false;
            transactionData.rewardAmount = 0;
            transactionData.mcqResponse = mcqResponse;
            const transaction = new TransactionHistory(transactionData);
            await transaction.save();

            res.status(201).json({ status: false, message: "Sorry You gave Wrong Answer ", transaction });
        }
    } else if (taskDetails.type === 'OpenLink') {
        // Handle OpenLink task
        if (linkOpened) {
            // Reward calculation for OpenLink tasks
            const rewardAmount = userDetails.isPremiumUser ? taskDetails.reward_amount * 0.08 : taskDetails.reward_amount * 0.04;
            transactionData.rewardAmount = taskDetails.reward_amount;
            transactionData.referrerRewardAmount = referralBy ? rewardAmount : 0; // Assuming 50% of the user's reward goes to the referrer
            transactionData.isLinkOpened = linkOpened;
            // Create and save transaction
            const transaction = new TransactionHistory(transactionData);
            await transaction.save();

            res.status(201).json({ status: true, message: "Link Opened successfully!", transaction });
        } else {
            return res.status(400).json({ status: false, message: "Link not opened" });
        }
    }
});


// const submitTransaction = asyncHandler(async (req, res) => {
//     const { taskId, userId, mcqResponse } = req.body;

//     console.log(taskId, userId, mcqResponse, "taskId, userId, mcqResponse");

//     const taskDetails = await Task.findById({ _id: taskId });
//     if (!taskDetails) return res.status(404).json({ status: false, message: "Task not found" });

//     const userDetails = await UserWallet.findById({ _id: userId });
//     if (!userDetails) return res.status(404).json({ status: false, message: "User not found" });

//     //referred_user
//     //referring_by
//     const referralBy = await Referral.findOne({ referred_user: userDetails?._id });

//     if (taskDetails?.type == "MCQ") {
//         if (mcqResponse === taskDetails?.mcq.correctAnswer) {

//             let rewardAmount = userDetails?.isPremiumUser ? taskDetails?.reward_amount * 0.08 : taskDetails?.reward_amount * 0.04


//             const transaction = new TransactionHistory({
//                 "taskId": taskId,
//                 "userId": userId,
//                 "referrerId": referralBy?.referring_by,
//                 "rewardAmount": taskDetails?.reward_amount,
//                 "referrerRewardAmount": referralBy ? rewardAmount : 0,
//                 "isUserClaimed": false,
//                 "isCorrectAnswer": true,
//                 "isReferrerClaimed": false,
//                 "taskType": taskDetails?.type,
//                 "mcqResponse": mcqResponse,
//                 "status": 'completed',
//             });
//             await transaction.save();
//             res.status(201).json({ status: true, message: "Answer submitted created successfully!", transaction });
//         }
//         else {
//             const transaction = new TransactionHistory({
//                 "taskId": taskId,
//                 "userId": userId,
//                 "referrerId": referralBy?.referring_by,
//                 "rewardAmount": 0,
//                 "referrerRewardAmount": 0,
//                 "isUserClaimed": true,
//                 "isReferrerClaimed": true,
//                 "isCorrectAnswer": false,
//                 "taskType": taskDetails?.type,
//                 "mcqResponse": mcqResponse,
//                 "status": "completed",
//             });
//             await transaction.save();
//             res.status(201).json({ status: true, message: "Answer submitted created successfully!", transaction });
//         }
//     }

// });

// const getTransactionHistoryForUser = asyncHandler(async (req, res) => {
//     const transactions = await TransactionHistory.find({ userId: req.params.userId });
//     res.status(200).json({ status: true, transactions });
// });


// // Controller function to get unclaimed transactions and missing tasks
// const getUnclaimedTasks = asyncHandler(async (req, res) => {
//     const userId = req.params.id;

//     // Fetch transactions where isUserClaimed is false
//     const transactions = await TransactionHistory.find({ isUserClaimed: false, userId })
//         .populate('taskId') // Populate task details if needed
//         .populate('referrerId'); // Populate referrer details if needed

//     // Fetch all tasks
//     const allTasks = await Task.find({});
//     console.log(transactions,"transactions");
//     // Extract task IDs from transactions
//     const transactionTaskIds = transactions.map(transaction => transaction?.taskId?._id.toString());

//     // Find tasks that are not in the transactions
//     const missingTasks = allTasks.filter(task => !transactionTaskIds.includes(task._id.toString()));

//     if (transactions.length === 0 && missingTasks.length === 0) {
//         return res.status(404).json({ status: false, message: "No unclaimed transactions and missing tasks found" });
//     }

//     res.status(200).json({
//         status: true,
//         transactions,
//         missingTasks
//     });
// })

const claimTaskReward = asyncHandler(async (req, res) => {
    const { taskId, userDatabaseId } = req.body;
    //if its not working then user transactionId instead of task id
    // Find the transaction by taskId
    const transaction = await TransactionHistory.findOne({ taskId: taskId, userId: userDatabaseId, status: "completed", isUserClaimed: false });

    // Find the user account by userDatabaseId
    const userAccount = await UserWallet.findById(userDatabaseId);

    // Check if transaction exists
    if (!transaction) {
        return res.status(404).json({ status: false, message: "Transaction not found" });
    }

    // Check if user account exists
    if (!userAccount) {
        return res.status(404).json({ status: false, message: "User account not found" });
    }
    console.log(transaction, "transactiontransaction");
    console.log(userDatabaseId, "userDatabaseIduserDatabaseIduserDatabaseId");
    // Check if the user is trying to claim their own reward and if it hasn't been claimed yet
    if (userDatabaseId == transaction?.userId && transaction.isUserClaimed == false) {
        console.log("if condition Enter");
        transaction.isUserClaimed = true;
        userAccount.userBalance += transaction?.rewardAmount;
        userAccount.userLevels += 1;
        await userAccount.save();
        // Save the transaction after making changes
        await transaction.save();
        if (transaction.referrerId !== null && transaction.isReferrerClaimed === false) {
            console.log("else if condition Enter");
            const referralAccount = await UserWallet.findById(transaction.referrerId);
            transaction.isReferrerClaimed = true;
            referralAccount.userBalance += transaction.referrerRewardAmount;
            await referralAccount.save();
            // Save the transaction after making changes
            await transaction.save();
        }
    }
    // // Check if the user is trying to claim a referrer reward and if it hasn't been claimed yet
    // else if (userDatabaseId === transaction.referrerId && transaction.isReferrerClaimed === false) {
    //     console.log("else if condition Enter");
    //     transaction.isReferrerClaimed = true;
    //     userAccount.userBalance += transaction.referrerRewardAmount;
    //     await userAccount.save();
    //     // Save the transaction after making changes
    //     await transaction.save();
    // }
    // If neither condition is met, return an error
    else {
        console.log("else Enter");
        return res.status(400).json({ status: false, message: "Invalid claim attempt" });
    }


    res.status(200).json({ status: true, message: "Reward claimed successfully!", transaction });
});

const getAllTransaction = asyncHandler(async (req, res) => {
    const transactions = await TransactionHistory.find({});
    res.status(200).json({ status: true, transactions });
});

const getReferalCount = asyncHandler(async (req, res) => {
    try {
        // Fetch all referral tasks excluding 'correctAnswer' from MCQ schema
        const allReferralTasks = await Task.find({ type: 'Referral' }, { 'mcq.correctAnswer': 0 });

        // Fetch ongoing and completed transactions for the given user
        const transactions = await TransactionHistory.find({
            userId: req.params.id,
            taskType: 'Referral' // Ensure we are only considering 'Referral' tasks
        }).populate('taskId');

        // Extract task IDs from transactions and classify them by status
        const ongoingTasks = transactions.filter(transaction => transaction.status === 'ongoing');
        const completedTasks = transactions.filter(transaction => transaction.status === 'completed');

        const ongoingTaskIds = new Set(ongoingTasks.map(transaction => transaction.taskId._id.toString()));
        const completedTaskIds = new Set(completedTasks.map(transaction => transaction.taskId._id.toString()));
        
        console.log(ongoingTaskIds,"ongoingTaskIds");
        console.log(ongoingTasks,"ongoingTasks");
        
        // // Filter tasks based on status
        // const ongoingTasksList = allReferralTasks.filter(task => ongoingTaskIds.has(task._id.toString()));

        const remainingTasksList = allReferralTasks.filter(task => !ongoingTaskIds.has(task._id.toString()) && !completedTaskIds.has(task._id.toString()));

        res.status(200).json({
            success: true,
            ongoingTasks: ongoingTasks, // Referral tasks that are ongoing
            remainingTasks: remainingTasksList // Referral tasks that are neither ongoing nor completed
        });
    } catch (error) {
        console.error('Error fetching tasks for user:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching tasks for user',
        });
    }
});

// Get All Tasks
const progressReport = asyncHandler(async (req, res) => {
    // Count the number of tasks the user has claimed
    const claimedTaskCount = await TransactionHistory.countDocuments({
        userId: req.params.id,
        isCorrectAnswer: true,
        isLinkOpened: true,
        isReferralCompleted: true
    });
    // Send the count as a response
    res.status(200).json({
        success: true,
        claimedTaskCount: claimedTaskCount || 0
    });
});


export {
    submitTransaction,
    getReferalCount,
    // getTransactionHistoryForUser, 
    claimTaskReward, getAllTransaction, progressReport
}