const User = require('../models/User');

// Create or update personal details
exports.createOrUpdatePersonalDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const {
            name,
            gender,
            emailId,
            bloodGroup,
            pincodeNative,
            state,
            district,
            nativePlace,
            nameMeaning
        } = req.body;

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

        // Update personal details fields
        if (name) user.name = name;
        if (gender) user.gender = gender;
        if (emailId) user.emailId = emailId;
        if (bloodGroup) user.bloodGroup = bloodGroup;
        if (pincodeNative) user.pincodeNative = pincodeNative;
        if (state) user.state = state;
        if (district) user.district = district;
        if (nativePlace) user.nativePlace = nativePlace;
        if (nameMeaning) user.nameMeaning = nameMeaning;

        // Update completion status
        const completion = user.updatePersonalDetailsStatus();
        await user.save();

        res.status(201).json({
            success: true,
            message: 'Personal details saved successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    gender: user.gender,
                    emailId: user.emailId,
                    bloodGroup: user.bloodGroup,
                    pincodeNative: user.pincodeNative,
                    state: user.state,
                    district: user.district,
                    nativePlace: user.nativePlace,
                    nameMeaning: user.nameMeaning,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted
                },
                completionPercentage: completion.percentage,
                isCompleted: completion.isCompleted,
                completedFields: completion.completedFields,
                totalFields: completion.totalFields
            }
        });

    } catch (error) {
        console.error('Personal details error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to save personal details',
            error: error.message
        });
    }
};

// Get personal details for a user
exports.getPersonalDetails = async (req, res) => {
    try {
        const userId = req.user._id;

        const user = await User.findById(userId);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found',
                data: null
            });
        }

        const completion = user.getPersonalDetailsCompletion();

        res.json({
            success: true,
            message: 'Personal details retrieved successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    gender: user.gender,
                    emailId: user.emailId,
                    bloodGroup: user.bloodGroup,
                    pincodeNative: user.pincodeNative,
                    state: user.state,
                    district: user.district,
                    nativePlace: user.nativePlace,
                    nameMeaning: user.nameMeaning,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted
                },
                completionPercentage: completion.percentage,
                isCompleted: completion.isCompleted,
                completedFields: completion.completedFields,
                totalFields: completion.totalFields
            }
        });

    } catch (error) {
        console.error('Get personal details error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve personal details',
            error: error.message
        });
    }
};

// Get personal details by user ID (admin or self-access)
exports.getPersonalDetailsById = async (req, res) => {
    try {
        const { userId } = req.params;
        const requestingUserId = req.user._id;

        // Check if user is accessing their own data or has admin privileges
        if (userId !== requestingUserId.toString()) {
            // For now, only allow self-access. Add admin check later if needed
            return res.status(403).json({
                success: false,
                message: 'Access denied. You can only access your own personal details'
            });
        }

        const user = await User.findById(userId);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found',
                data: null
            });
        }

        const completion = user.getPersonalDetailsCompletion();

        res.json({
            success: true,
            message: 'Personal details retrieved successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    gender: user.gender,
                    emailId: user.emailId,
                    bloodGroup: user.bloodGroup,
                    pincodeNative: user.pincodeNative,
                    state: user.state,
                    district: user.district,
                    nativePlace: user.nativePlace,
                    nameMeaning: user.nameMeaning,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted
                },
                completionPercentage: completion.percentage,
                isCompleted: completion.isCompleted,
                completedFields: completion.completedFields,
                totalFields: completion.totalFields
            }
        });

    } catch (error) {
        console.error('Get personal details by ID error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve personal details',
            error: error.message
        });
    }
};

// Update specific fields of personal details
exports.updatePersonalDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const updateData = req.body;

        // Remove userId from update data if present (security measure)
        delete updateData.userId;

        const user = await User.findById(userId);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Update only provided fields
        const allowedFields = ['name', 'gender', 'emailId', 'bloodGroup', 'pincodeNative', 'state', 'district', 'nativePlace', 'nameMeaning'];
        Object.keys(updateData).forEach(key => {
            if (allowedFields.includes(key) && updateData[key] !== undefined) {
                user[key] = updateData[key];
            }
        });

        // Update completion status
        const completion = user.updatePersonalDetailsStatus();
            await user.save();

        res.json({
            success: true,
            message: 'Personal details updated successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    gender: user.gender,
                    emailId: user.emailId,
                    bloodGroup: user.bloodGroup,
                    pincodeNative: user.pincodeNative,
                    state: user.state,
                    district: user.district,
                    nativePlace: user.nativePlace,
                    nameMeaning: user.nameMeaning,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted
                },
                completionPercentage: completion.percentage,
                isCompleted: completion.isCompleted,
                completedFields: completion.completedFields,
                totalFields: completion.totalFields
            }
        });

    } catch (error) {
        console.error('Update personal details error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update personal details',
            error: error.message
        });
    }
};

// Update personal details by userId (simpler approach)
exports.updatePersonalDetailsByUserId = async (req, res) => {
    try {
        const { userId } = req.params;
        const updateData = req.body;
        const requestingUserId = req.user._id;

        // Check if user is updating their own data or has admin privileges
        if (userId !== requestingUserId.toString()) {
            // For now, only allow self-access. Add admin check later if needed
            return res.status(403).json({
                success: false,
                message: 'Access denied. You can only update your own personal details'
            });
        }

        // Remove userId from update data if present (security measure)
        delete updateData.userId;

        const user = await User.findById(userId);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Update only provided fields
        const allowedFields = ['name', 'gender', 'emailId', 'bloodGroup', 'pincodeNative', 'state', 'district', 'nativePlace', 'nameMeaning'];
        Object.keys(updateData).forEach(key => {
            if (allowedFields.includes(key) && updateData[key] !== undefined) {
                user[key] = updateData[key];
            }
        });

        // Update completion status
        const completion = user.updatePersonalDetailsStatus();
        await user.save();

        res.json({
            success: true,
            message: 'Personal details updated successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    gender: user.gender,
                    emailId: user.emailId,
                    bloodGroup: user.bloodGroup,
                    pincodeNative: user.pincodeNative,
                    state: user.state,
                    district: user.district,
                    nativePlace: user.nativePlace,
                    nameMeaning: user.nameMeaning,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted
                },
                completionPercentage: completion.percentage,
                isCompleted: completion.isCompleted,
                completedFields: completion.completedFields,
                totalFields: completion.totalFields
            }
        });

    } catch (error) {
        console.error('Update personal details by userId error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update personal details',
            error: error.message
        });
    }
};

// Delete personal details (reset to default values)
exports.deletePersonalDetails = async (req, res) => {
    try {
        const userId = req.user._id;

        const user = await User.findById(userId);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Reset personal details fields to default values
        user.gender = undefined;
        user.emailId = undefined;
        user.bloodGroup = undefined;
        user.pincodeNative = undefined;
        user.state = undefined;
        user.district = undefined;
        user.nativePlace = undefined;
        user.nameMeaning = undefined;
            user.hasPersonalDetails = false;
            user.personalDetailsCompleted = false;

            await user.save();

        res.json({
            success: true,
            message: 'Personal details deleted successfully'
        });

    } catch (error) {
        console.error('Delete personal details error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete personal details',
            error: error.message
        });
    }
};

// Get profile completion status
exports.getProfileCompletion = async (req, res) => {
    try {
        const userId = req.user._id;

        const user = await User.findById(userId);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        const completion = user.getPersonalDetailsCompletion();

        res.json({
            success: true,
            message: 'Profile completion status retrieved',
            data: {
                completionPercentage: completion.percentage,
                isCompleted: completion.isCompleted,
                completedFields: completion.completedFields,
                totalFields: completion.totalFields,
                hasPersonalDetails: user.hasPersonalDetails,
                personalDetailsCompleted: user.personalDetailsCompleted
            }
        });

    } catch (error) {
        console.error('Get profile completion error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get profile completion status',
            error: error.message
        });
    }
};

// Get all personal details (admin function - for testing)
exports.getAllPersonalDetails = async (req, res) => {
    try {
        const users = await User.find({})
            .select('name mobile gender emailId bloodGroup pincodeNative state district nativePlace nameMeaning hasPersonalDetails personalDetailsCompleted createdAt updatedAt');

        res.json({
            success: true,
            message: 'All personal details retrieved successfully',
            data: {
                users,
                total: users.length
            }
        });

    } catch (error) {
        console.error('Get all personal details error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve personal details',
            error: error.message
        });
    }
};
