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

// Create or update graduate details
exports.createOrUpdateGraduateDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const {
            // School Details (from Educational Details)
            schoolState,
            schoolDistrict,
            schoolVillage,
            schoolName,
            boardType,
            boardTypeOther,
            schoolType,
            schoolTypeOther,
            yearOfJoiningSchool,
            section,
            // College 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'
            });
        }

        // Create or update school details without current class
        let schoolDetails = await SchoolDetailsWithoutCurrentClass.findOne({ userId });
        
        if (schoolDetails) {
            // Update existing school details
            schoolDetails.schoolState = schoolState;
            schoolDetails.schoolDistrict = schoolDistrict;
            schoolDetails.schoolVillage = schoolVillage;
            schoolDetails.schoolName = schoolName;
            schoolDetails.boardType = boardType;
            schoolDetails.boardTypeOther = boardTypeOther;
            schoolDetails.schoolType = schoolType;
            schoolDetails.schoolTypeOther = schoolTypeOther;
            schoolDetails.yearOfJoiningSchool = yearOfJoiningSchool;
            schoolDetails.section = section;
            await schoolDetails.save();
        } else {
            // Create new school details
            schoolDetails = await SchoolDetailsWithoutCurrentClass.create({
                userId,
                schoolState,
                schoolDistrict,
                schoolVillage,
                schoolName,
                boardType,
                boardTypeOther,
                schoolType,
                schoolTypeOther,
                yearOfJoiningSchool,
                section
            });
        }

        // Check if graduate details already exist
        let graduateDetails = await GraduateDetails.findOne({ userId });

        if (graduateDetails) {
            // Update existing details
            graduateDetails.schoolDetailsId = schoolDetails._id;
            // College Details
            graduateDetails.collegeState = collegeState;
            graduateDetails.collegeDistrict = collegeDistrict;
            graduateDetails.collegeName = collegeName;
            graduateDetails.graduationJoiningYear = graduationJoiningYear;
            graduateDetails.mainStream = mainStream;
            graduateDetails.mainStreamOther = mainStreamOther;
            graduateDetails.branchStream = branchStream;
            graduateDetails.collegeType = collegeType;
            graduateDetails.collegeTypeOther = collegeTypeOther;
            // PG Details
            graduateDetails.isPursuingOrCompletedPG = isPursuingOrCompletedPG || false;
            graduateDetails.pgCollegeName = pgCollegeName;
            graduateDetails.pgJoiningYear = pgJoiningYear;

            await graduateDetails.save();
        } else {
            // Create new graduate details
            graduateDetails = await GraduateDetails.create({
                userId,
                schoolDetailsId: schoolDetails._id,
                // College Details
                collegeState,
                collegeDistrict,
                collegeName,
                graduationJoiningYear,
                mainStream,
                mainStreamOther,
                branchStream,
                collegeType,
                collegeTypeOther,
                // PG Details
                isPursuingOrCompletedPG: isPursuingOrCompletedPG || false,
                pgCollegeName,
                pgJoiningYear
            });
        }

        // Check completion status
        graduateDetails.checkCompletion();

        res.status(201).json({
            success: true,
            message: 'Graduate details saved successfully',
            data: {
                graduateDetails,
                schoolDetails,
                completionPercentage: GraduateDetails.getCompletionPercentage(graduateDetails),
                isCompleted: graduateDetails.isCompleted
            }
        });

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

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

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

        res.json({
            success: true,
            message: 'Graduate details retrieved successfully',
            data: {
                graduateDetails,
                completionPercentage: GraduateDetails.getCompletionPercentage(graduateDetails),
                isCompleted: graduateDetails.isCompleted
            }
        });

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

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

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

        res.json({
            success: true,
            message: 'Graduate details retrieved successfully',
            data: {
                graduateDetails,
                completionPercentage: GraduateDetails.getCompletionPercentage(graduateDetails),
                isCompleted: graduateDetails.isCompleted
            }
        });

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

// Update graduate details
exports.updateGraduateDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const updates = req.body;

        const graduateDetails = await GraduateDetails.findOne({ userId });
        
        if (!graduateDetails) {
            return res.status(404).json({
                success: false,
                message: 'Graduate details not found'
            });
        }

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

        await graduateDetails.save();

        // Check completion status
        graduateDetails.checkCompletion();

        res.json({
            success: true,
            message: 'Graduate details updated successfully',
            data: {
                graduateDetails,
                completionPercentage: GraduateDetails.getCompletionPercentage(graduateDetails),
                isCompleted: graduateDetails.isCompleted
            }
        });

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

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

        const graduateDetails = await GraduateDetails.findOneAndDelete({ userId });
        
        if (!graduateDetails) {
            return res.status(404).json({
                success: false,
                message: 'Graduate details not found'
            });
        }

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

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

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

        const graduateDetails = await GraduateDetails.findOne({ userId });
        
        if (!graduateDetails) {
            return res.status(404).json({
                success: false,
                message: 'Graduate details not found'
            });
        }

        // Check completion status
        graduateDetails.checkCompletion();

        const requiredFields = [
            // School Details (from Educational Details)
            'schoolState', 'schoolDistrict', 
            'schoolName', 'yearOfJoiningSchool',
            // College Details
            'collegeState', 'collegeDistrict', 
            'collegeName', 'graduationJoiningYear', 'mainStream', 
            'branchStream', 'collegeType'
        ];

        let missingFields = requiredFields.filter(field => {
            return !graduateDetails[field] || graduateDetails[field].toString().trim().length === 0;
        });

        // Check "Other" fields if applicable
        if (graduateDetails.mainStream === 'Other' && (!graduateDetails.mainStreamOther || graduateDetails.mainStreamOther.trim().length === 0)) {
            missingFields.push('mainStreamOther');
        }

        if (graduateDetails.collegeType === 'Other' && (!graduateDetails.collegeTypeOther || graduateDetails.collegeTypeOther.trim().length === 0)) {
            missingFields.push('collegeTypeOther');
        }

        // If PG is pursuing/completed, check PG fields
        if (graduateDetails.isPursuingOrCompletedPG) {
            const pgFields = ['pgCollegeName', 'pgJoiningYear'];
            const pgMissing = pgFields.filter(field => {
                return !graduateDetails[field] || graduateDetails[field].toString().trim().length === 0;
            });
            missingFields = [...missingFields, ...pgMissing];
        }

        res.json({
            success: true,
            message: 'Graduate completion status retrieved',
            data: {
                isCompleted: graduateDetails.isCompleted,
                completionPercentage: GraduateDetails.getCompletionPercentage(graduateDetails),
                missingFields,
                totalRequiredFields: requiredFields.length + (graduateDetails.isPursuingOrCompletedPG ? 2 : 0)
            }
        });

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

// Get colleges
exports.getColleges = async (req, res) => {
    try {
        // Mock college data - in real implementation, this would come from a database
        const mockColleges = [
            { name: 'Delhi University', state: 'Delhi', district: 'Central Delhi' },
            { name: 'JNU', state: 'Delhi', district: 'South Delhi' },
            { name: 'Amity University', state: 'Delhi', district: 'Central Delhi' },
            { name: 'IP University', state: 'Delhi', district: 'Central Delhi' }
        ];

        const colleges = mockColleges;

        res.json({
            success: true,
            message: 'Colleges retrieved successfully',
            data: {
                colleges,
                totalColleges: colleges.length
            }
        });

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

// Get schools (for graduate students)
exports.getSchools = async (req, res) => {
    try {
        // Mock school data - in real implementation, this would come from a database
        const mockSchools = [
            { name: 'Delhi Public School', state: 'Delhi', district: 'Central Delhi' },
            { name: 'Kendriya Vidyalaya', state: 'Delhi', district: 'Central Delhi' },
            { name: 'Springdales School', state: 'Delhi', district: 'Central Delhi' },
            { name: 'Modern School', state: 'Delhi', district: 'Central Delhi' }
        ];

        const schools = mockSchools;

        res.json({
            success: true,
            message: 'Schools retrieved successfully',
            data: {
                schools,
                totalSchools: schools.length
            }
        });

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

// Get all graduate details (Admin only)
exports.getAllGraduateDetails = async (req, res) => {
    try {
        const graduateDetails = await GraduateDetails.find()
            .populate('userId', 'name mobile email')
            .sort({ createdAt: -1 });

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

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