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

// Create or update working professional details
exports.createOrUpdateWorkingProfessionalDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const { 
            jobEntries,
            // School Details (separate model)
            schoolDetails,
            // Graduate Details
            collegeState, collegeDistrict, collegeName,
            graduationJoiningYear, mainStream, mainStreamOther,
            branchStream, collegeType, collegeTypeOther,
            // PG Details
            isPursuingOrCompletedPG, pgCollegeName, pgJoiningYear
        } = req.body;

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

        // Validate job entries
        if (!jobEntries || !Array.isArray(jobEntries) || jobEntries.length === 0) {
            return res.status(400).json({
                success: false,
                message: 'At least one job entry is required'
            });
        }

        // Create or update school details without current class
        let schoolDetailsDoc;
        if (schoolDetails) {
            const existingSchoolDetails = await SchoolDetailsWithoutCurrentClass.findOne({ userId });
            
            if (existingSchoolDetails) {
                // Update existing school details
                Object.keys(schoolDetails).forEach(key => {
                    if (schoolDetails[key] !== undefined) {
                        existingSchoolDetails[key] = schoolDetails[key];
                    }
                });
                await existingSchoolDetails.save();
                schoolDetailsDoc = existingSchoolDetails;
            } else {
                // Create new school details
                schoolDetailsDoc = await SchoolDetailsWithoutCurrentClass.create({
                    userId,
                    ...schoolDetails
                });
            }
        } else {
            // Check if school details already exist
            schoolDetailsDoc = await SchoolDetailsWithoutCurrentClass.findOne({ userId });
            if (!schoolDetailsDoc) {
                return res.status(400).json({
                    success: false,
                    message: 'School details are required'
                });
            }
        }

        // Check if working professional details already exist
        let workingProfessionalDetails = await WorkingProfessionalDetails.findOne({ userId });

        const updateData = {
            schoolDetailsId: schoolDetailsDoc._id,
            jobEntries,
            // Graduate Details
            collegeState, collegeDistrict, collegeName,
            graduationJoiningYear, mainStream, mainStreamOther,
            branchStream, collegeType, collegeTypeOther,
            // PG Details
            isPursuingOrCompletedPG, pgCollegeName, pgJoiningYear
        };

        if (workingProfessionalDetails) {
            // Update existing details
            Object.keys(updateData).forEach(key => {
                if (updateData[key] !== undefined) {
                    workingProfessionalDetails[key] = updateData[key];
                }
            });
            await workingProfessionalDetails.save();
        } else {
            // Create new working professional details
            workingProfessionalDetails = await WorkingProfessionalDetails.create({
                userId,
                ...updateData
            });
        }

        // Check completion status
        workingProfessionalDetails.checkCompletion();

        res.status(201).json({
            success: true,
            message: 'Working professional details saved successfully',
            data: {
                workingProfessionalDetails,
                schoolDetails,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                isCompleted: workingProfessionalDetails.isCompleted
            }
        });

    } catch (error) {
        console.error('Error creating/updating working professional details:', error);
        res.status(500).json({
            success: false,
            message: 'Error creating/updating working professional details',
            error: error.message
        });
    }
};

// Get working professional details for current user
exports.getWorkingProfessionalDetails = async (req, res) => {
    try {
        const userId = req.user._id;

        const workingProfessionalDetails = await WorkingProfessionalDetails.findOne({ userId })
            .populate('schoolDetailsId');
        
        if (!workingProfessionalDetails) {
            return res.status(404).json({
                success: false,
                message: 'Working professional details not found'
            });
        }

        res.json({
            success: true,
            message: 'Working professional details retrieved successfully',
            data: {
                workingProfessionalDetails,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                isCompleted: workingProfessionalDetails.isCompleted
            }
        });

    } catch (error) {
        console.error('Error retrieving working professional details:', error);
        res.status(500).json({
            success: false,
            message: 'Error retrieving working professional details',
            error: error.message
        });
    }
};

// Get working professional details by ID
exports.getWorkingProfessionalDetailsById = async (req, res) => {
    try {
        const { id } = req.params;

        const workingProfessionalDetails = await WorkingProfessionalDetails.findById(id)
            .populate('schoolDetailsId');
        
        if (!workingProfessionalDetails) {
            return res.status(404).json({
                success: false,
                message: 'Working professional details not found'
            });
        }

        res.json({
            success: true,
            message: 'Working professional details retrieved successfully',
            data: {
                workingProfessionalDetails,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                isCompleted: workingProfessionalDetails.isCompleted
            }
        });

    } catch (error) {
        console.error('Error retrieving working professional details:', error);
        res.status(500).json({
            success: false,
            message: 'Error retrieving working professional details',
            error: error.message
        });
    }
};

// Add new job entry
exports.addJobEntry = async (req, res) => {
    try {
        const userId = req.user._id;
        const newJobEntry = req.body;

        const workingProfessionalDetails = await WorkingProfessionalDetails.findOne({ userId });
        
        if (!workingProfessionalDetails) {
            // Create new document with first job entry
            const newDetails = await WorkingProfessionalDetails.create({
                userId,
                jobEntries: [newJobEntry]
            });

            newDetails.checkCompletion();

            return res.status(201).json({
                success: true,
                message: 'Job entry added successfully',
                data: {
                    workingProfessionalDetails: newDetails,
                    completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(newDetails),
                    isCompleted: newDetails.isCompleted
                }
            });
        }

        // Add job entry to existing document
        workingProfessionalDetails.jobEntries.push(newJobEntry);
        await workingProfessionalDetails.save();

        // Check completion status
        workingProfessionalDetails.checkCompletion();

        res.status(201).json({
            success: true,
            message: 'Job entry added successfully',
            data: {
                workingProfessionalDetails,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                isCompleted: workingProfessionalDetails.isCompleted
            }
        });

    } catch (error) {
        console.error('Error adding job entry:', error);
        res.status(500).json({
            success: false,
            message: 'Error adding job entry',
            error: error.message
        });
    }
};

// Update specific job entry
exports.updateJobEntry = async (req, res) => {
    try {
        const userId = req.user._id;
        const { jobEntryId } = req.params;
        const updates = req.body;

        const workingProfessionalDetails = await WorkingProfessionalDetails.findOne({ userId });
        
        if (!workingProfessionalDetails) {
            return res.status(404).json({
                success: false,
                message: 'Working professional details not found'
            });
        }

        const jobEntry = workingProfessionalDetails.jobEntries.id(jobEntryId);
        if (!jobEntry) {
            return res.status(404).json({
                success: false,
                message: 'Job entry not found'
            });
        }

        // Update job entry fields
        Object.keys(updates).forEach(key => {
            if (updates[key] !== undefined) {
                jobEntry[key] = updates[key];
            }
        });

        await workingProfessionalDetails.save();

        // Check completion status
        workingProfessionalDetails.checkCompletion();

        res.json({
            success: true,
            message: 'Job entry updated successfully',
            data: {
                workingProfessionalDetails,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                isCompleted: workingProfessionalDetails.isCompleted
            }
        });

    } catch (error) {
        console.error('Error updating job entry:', error);
        res.status(500).json({
            success: false,
            message: 'Error updating job entry',
            error: error.message
        });
    }
};

// Delete specific job entry
exports.deleteJobEntry = async (req, res) => {
    try {
        const userId = req.user._id;
        const { jobEntryId } = req.params;

        const workingProfessionalDetails = await WorkingProfessionalDetails.findOne({ userId });
        
        if (!workingProfessionalDetails) {
            return res.status(404).json({
                success: false,
                message: 'Working professional details not found'
            });
        }

        const jobEntry = workingProfessionalDetails.jobEntries.id(jobEntryId);
        if (!jobEntry) {
            return res.status(404).json({
                success: false,
                message: 'Job entry not found'
            });
        }

        jobEntry.remove();
        await workingProfessionalDetails.save();

        // Check completion status
        workingProfessionalDetails.checkCompletion();

        res.json({
            success: true,
            message: 'Job entry deleted successfully',
            data: {
                workingProfessionalDetails,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                isCompleted: workingProfessionalDetails.isCompleted
            }
        });

    } catch (error) {
        console.error('Error deleting job entry:', error);
        res.status(500).json({
            success: false,
            message: 'Error deleting job entry',
            error: error.message
        });
    }
};

// Delete working professional details
exports.deleteWorkingProfessionalDetails = async (req, res) => {
    try {
        const userId = req.user._id;

        const workingProfessionalDetails = await WorkingProfessionalDetails.findOneAndDelete({ userId });
        
        if (!workingProfessionalDetails) {
            return res.status(404).json({
                success: false,
                message: 'Working professional details not found'
            });
        }

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

    } catch (error) {
        console.error('Error deleting working professional details:', error);
        res.status(500).json({
            success: false,
            message: 'Error deleting working professional details',
            error: error.message
        });
    }
};

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

        const workingProfessionalDetails = await WorkingProfessionalDetails.findOne({ userId });
        
        if (!workingProfessionalDetails) {
            return res.status(404).json({
                success: false,
                message: 'Working professional details not found'
            });
        }

        // Check completion status
        workingProfessionalDetails.checkCompletion();

        let missingFields = [];
        
        // Check school details
        const schoolRequiredFields = [
            'schoolState', 'schoolDistrict', 
            'schoolName', 'boardType', 'schoolType', 'yearOfJoiningSchool'
        ];
        
        schoolRequiredFields.forEach(field => {
            if (!workingProfessionalDetails[field] || workingProfessionalDetails[field].toString().trim().length === 0) {
                missingFields.push(`schoolDetails.${field}`);
            }
        });
        
        // Check "Other" fields for school if applicable
        if (workingProfessionalDetails.boardType === 'Other' && (!workingProfessionalDetails.boardTypeOther || workingProfessionalDetails.boardTypeOther.trim().length === 0)) {
            missingFields.push('schoolDetails.boardTypeOther');
        }
        
        if (workingProfessionalDetails.schoolType === 'Other' && (!workingProfessionalDetails.schoolTypeOther || workingProfessionalDetails.schoolTypeOther.trim().length === 0)) {
            missingFields.push('schoolDetails.schoolTypeOther');
        }
        
        // Check graduate details
        const graduateRequiredFields = [
            'collegeState', 'collegeDistrict', 
            'collegeName', 'graduationJoiningYear', 'mainStream', 
            'branchStream', 'collegeType'
        ];
        
        graduateRequiredFields.forEach(field => {
            if (!workingProfessionalDetails[field] || workingProfessionalDetails[field].toString().trim().length === 0) {
                missingFields.push(`graduateDetails.${field}`);
            }
        });
        
        // Check "Other" fields for graduate if applicable
        if (workingProfessionalDetails.mainStream === 'Other' && (!workingProfessionalDetails.mainStreamOther || workingProfessionalDetails.mainStreamOther.trim().length === 0)) {
            missingFields.push('graduateDetails.mainStreamOther');
        }
        
        if (workingProfessionalDetails.collegeType === 'Other' && (!workingProfessionalDetails.collegeTypeOther || workingProfessionalDetails.collegeTypeOther.trim().length === 0)) {
            missingFields.push('graduateDetails.collegeTypeOther');
        }
        
        // If PG is marked as pursuing/completed, check PG fields
        if (workingProfessionalDetails.isPursuingOrCompletedPG) {
            const pgFields = ['pgCollegeName', 'pgJoiningYear'];
            pgFields.forEach(field => {
                if (!workingProfessionalDetails[field] || workingProfessionalDetails[field].toString().trim().length === 0) {
                    missingFields.push(`graduateDetails.${field}`);
                }
            });
        }
        
        // Check job entries
        if (workingProfessionalDetails.jobEntries.length === 0) {
            missingFields.push('jobEntries');
        } else {
            workingProfessionalDetails.jobEntries.forEach((job, index) => {
                const requiredFields = ['jobRole', 'companyName', 'industry', 'jobPincode', 'jobState', 'jobDistrict', 'jobCity', 'jobLocality'];
                
                requiredFields.forEach(field => {
                    if (!job[field] || job[field].toString().trim().length === 0) {
                        missingFields.push(`jobEntries[${index}].${field}`);
                    }
                });
                
                // Check "Other" fields if applicable
                if (job.industry === 'Other' && (!job.industryOther || job.industryOther.trim().length === 0)) {
                    missingFields.push(`jobEntries[${index}].industryOther`);
                }
            });
        }

        res.json({
            success: true,
            message: 'Working professional completion status retrieved',
            data: {
                isCompleted: workingProfessionalDetails.isCompleted,
                completionPercentage: WorkingProfessionalDetails.getCompletionPercentage(workingProfessionalDetails),
                missingFields,
                totalJobEntries: workingProfessionalDetails.jobEntries.length
            }
        });

    } catch (error) {
        console.error('Error retrieving working professional completion:', error);
        res.status(500).json({
            success: false,
            message: 'Error retrieving working professional completion status',
            error: error.message
        });
    }
};

// Get all working professional details (Admin)
exports.getAllWorkingProfessionalDetails = async (req, res) => {
    try {
        const workingProfessionalDetails = await WorkingProfessionalDetails.find()
            .populate('userId', 'name mobile email')
            .sort({ createdAt: -1 });

        res.json({
            success: true,
            message: 'All working professional details retrieved successfully',
            data: {
                workingProfessionalDetails,
                totalCount: workingProfessionalDetails.length
            }
        });

    } catch (error) {
        console.error('Error retrieving all working professional details:', error);
        res.status(500).json({
            success: false,
            message: 'Error retrieving all working professional details',
            error: error.message
        });
    }
};
