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

// Create or update school details
exports.createOrUpdateSchoolDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const {
            currentClass,
            schoolState,
            schoolDistrict,
            schoolName,
            boardType,
            boardTypeOther,
            schoolType,
            schoolTypeOther,
            yearOfJoiningSchool,
            section,
            sectionOther
        } = 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 SchoolDetails.findOne({ userId });

        if (schoolDetails) {
            // Update existing details
            schoolDetails.currentClass = currentClass;
            schoolDetails.schoolState = schoolState;
            schoolDetails.schoolDistrict = schoolDistrict;
            schoolDetails.schoolName = schoolName;
            schoolDetails.boardType = boardType;
            schoolDetails.boardTypeOther = boardTypeOther;
            schoolDetails.schoolType = schoolType;
            schoolDetails.schoolTypeOther = schoolTypeOther;
            schoolDetails.yearOfJoiningSchool = yearOfJoiningSchool;
            schoolDetails.section = section;
            schoolDetails.sectionOther = sectionOther;

            await schoolDetails.save();
        } else {
            // Create new school details
            schoolDetails = await SchoolDetails.create({
                userId,
                currentClass,
                schoolState,
                schoolDistrict,
                schoolName,
                boardType,
                boardTypeOther,
                schoolType,
                schoolTypeOther,
                yearOfJoiningSchool,
                section,
                sectionOther
            });
        }

        // Check completion status
        schoolDetails.checkCompletion();

        res.status(201).json({
            success: true,
            message: 'School details saved successfully',
            data: {
                schoolDetails,
                completionPercentage: SchoolDetails.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 for current user
exports.getSchoolDetails = async (req, res) => {
    try {
        const userId = req.user._id;

        const schoolDetails = await SchoolDetails.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: SchoolDetails.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 by ID
exports.getSchoolDetailsById = async (req, res) => {
    try {
        const { id } = req.params;

        const schoolDetails = await SchoolDetails.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: SchoolDetails.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
exports.updateSchoolDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const updates = req.body;

        const schoolDetails = await SchoolDetails.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: SchoolDetails.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
exports.deleteSchoolDetails = async (req, res) => {
    try {
        const userId = req.user._id;

        const schoolDetails = await SchoolDetails.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
exports.getSchoolCompletion = async (req, res) => {
    try {
        const userId = req.user._id;

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

        // Check completion status
        schoolDetails.checkCompletion();

        const requiredFields = [
            'currentClass', '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: SchoolDetails.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 by class
exports.getSchoolsByClass = async (req, res) => {
    try {
        const { currentClass } = req.query;

        if (!currentClass) {
            return res.status(400).json({
                success: false,
                message: 'Current class is required'
            });
        }

        // Mock school data - in real implementation, this would come from UDISE database
        const mockSchools = [
            { name: 'Delhi Public School', state: 'Delhi', district: 'Central Delhi', classes: ['6th', '7th', '8th', '9th', '10th'] },
            { name: 'Kendriya Vidyalaya', state: 'Delhi', district: 'Central Delhi', classes: ['6th', '7th', '8th', '9th', '10th'] },
            { name: 'Springdales School', state: 'Delhi', district: 'Central Delhi', classes: ['6th', '7th', '8th', '9th', '10th'] },
            { name: 'Modern School', state: 'Delhi', district: 'Central Delhi', classes: ['6th', '7th', '8th', '9th', '10th'] }
        ];

        const schools = mockSchools.filter(school => 
            school.classes.includes(currentClass)
        );

        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 (Admin only)
exports.getAllSchoolDetails = async (req, res) => {
    try {
        const schoolDetails = await SchoolDetails.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
        });
    }
};
