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

// Create or update school details without current class
exports.createOrUpdateSchoolDetailsWithoutCurrentClass = async (req, res) => {
    try {
        const userId = req.user._id;
        const {
            schoolState,
            schoolDistrict,
            schoolVillage,
            schoolName,
            boardType,
            boardTypeOther,
            schoolType,
            schoolTypeOther,
            yearOfJoiningSchool,
            section
        } = 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'
            });
        }

        // Check if school details already exist
        let schoolDetails = await SchoolDetailsWithoutCurrentClass.findOne({ userId });

        if (schoolDetails) {
            // Update existing 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 completion status
        schoolDetails.checkCompletion();

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

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

// Get school details without current class for current user
exports.getSchoolDetailsWithoutCurrentClass = async (req, res) => {
    try {
        const userId = req.user._id;

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

        res.json({
            success: true,
            message: 'School details retrieved successfully',
            data: {
                schoolDetails,
                completionPercentage: SchoolDetailsWithoutCurrentClass.getCompletionPercentage(schoolDetails),
                isCompleted: schoolDetails.isCompleted
            }
        });

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

// Get school details without current class by ID
exports.getSchoolDetailsWithoutCurrentClassById = async (req, res) => {
    try {
        const { id } = req.params;

        const schoolDetails = await SchoolDetailsWithoutCurrentClass.findById(id);
        
        if (!schoolDetails) {
            return res.status(404).json({
                success: false,
                message: 'School details not found'
            });
        }

        res.json({
            success: true,
            message: 'School details retrieved successfully',
            data: {
                schoolDetails,
                completionPercentage: SchoolDetailsWithoutCurrentClass.getCompletionPercentage(schoolDetails),
                isCompleted: schoolDetails.isCompleted
            }
        });

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

// Update school details without current class
exports.updateSchoolDetailsWithoutCurrentClass = async (req, res) => {
    try {
        const userId = req.user._id;
        const updates = req.body;

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

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

        await schoolDetails.save();

        // Check completion status
        schoolDetails.checkCompletion();

        res.json({
            success: true,
            message: 'School details updated successfully',
            data: {
                schoolDetails,
                completionPercentage: SchoolDetailsWithoutCurrentClass.getCompletionPercentage(schoolDetails),
                isCompleted: schoolDetails.isCompleted
            }
        });

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

// Delete school details without current class
exports.deleteSchoolDetailsWithoutCurrentClass = async (req, res) => {
    try {
        const userId = req.user._id;

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

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

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

// Get school completion status without current class
exports.getSchoolCompletionWithoutCurrentClass = async (req, res) => {
    try {
        const userId = req.user._id;

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

        // Check completion status
        schoolDetails.checkCompletion();

        const requiredFields = [
            'schoolState', 
            'schoolDistrict', 'schoolName', 'boardType', 
            'schoolType', 'yearOfJoiningSchool'
        ];

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

        // Check "Other" fields if applicable
        if (schoolDetails.boardType === 'Other' && (!schoolDetails.boardTypeOther || schoolDetails.boardTypeOther.trim().length === 0)) {
            missingFields.push('boardTypeOther');
        }

        if (schoolDetails.schoolType === 'Other' && (!schoolDetails.schoolTypeOther || schoolDetails.schoolTypeOther.trim().length === 0)) {
            missingFields.push('schoolTypeOther');
        }

        res.json({
            success: true,
            message: 'School completion status retrieved',
            data: {
                isCompleted: schoolDetails.isCompleted,
                completionPercentage: SchoolDetailsWithoutCurrentClass.getCompletionPercentage(schoolDetails),
                missingFields,
                totalRequiredFields: requiredFields.length + (schoolDetails.boardType === 'Other' ? 1 : 0) + (schoolDetails.schoolType === 'Other' ? 1 : 0)
            }
        });

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

// Get schools (for graduates and working professionals)
exports.getSchools = async (req, res) => {
    try {
        // Mock school data - in real implementation, this would come from UDISE 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 school details without current class (Admin only)
exports.getAllSchoolDetailsWithoutCurrentClass = async (req, res) => {
    try {
        const schoolDetails = await SchoolDetailsWithoutCurrentClass.find()
            .populate('userId', 'name mobile email')
            .sort({ createdAt: -1 });

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

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