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

// Create or update business details
exports.createOrUpdateBusinessDetails = async (req, res) => {
    try {
        const userId = req.user._id;
        const { 
            // School Details (separate model)
            schoolDetails,
            // Graduate Details (separate model)
            graduateDetails,
            // Business Details
            businessName, businessType, industry, yearsRunning,
            businessPincode, businessState, businessDistrict, businessTown,
            websiteOrInstaLink, businessPOCName, businessPOCMobile
        } = 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 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'
                });
            }
        }

        // Create or update graduate details
        let graduateDetailsDoc;
        if (graduateDetails) {
            const existingGraduateDetails = await GraduateDetails.findOne({ userId });
            
            if (existingGraduateDetails) {
                // Update existing graduate details
                Object.keys(graduateDetails).forEach(key => {
                    if (graduateDetails[key] !== undefined) {
                        existingGraduateDetails[key] = graduateDetails[key];
                    }
                });
                await existingGraduateDetails.save();
                graduateDetailsDoc = existingGraduateDetails;
            } else {
                // Create new graduate details
                graduateDetailsDoc = await GraduateDetails.create({
                    userId,
                    schoolDetailsId: schoolDetailsDoc._id,
                    ...graduateDetails
                });
            }
        } else {
            // Check if graduate details already exist
            graduateDetailsDoc = await GraduateDetails.findOne({ userId });
            if (!graduateDetailsDoc) {
                return res.status(400).json({
                    success: false,
                    message: 'Graduate details are required'
                });
            }
        }

        // Check if business details already exist
        let businessDetails = await BusinessDetails.findOne({ userId });

        const updateData = {
            schoolDetailsId: schoolDetailsDoc._id,
            graduateDetailsId: graduateDetailsDoc._id,
            // Business Details
            businessName, businessType, industry, yearsRunning,
            businessPincode, businessState, businessDistrict, businessTown,
            websiteOrInstaLink, businessPOCName, businessPOCMobile
        };

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

        // Check completion status
        businessDetails.checkCompletion();

        res.status(201).json({
            success: true,
            message: 'Business details saved successfully',
            data: {
                businessDetails,
                schoolDetails: schoolDetailsDoc,
                graduateDetails: graduateDetailsDoc,
                completionPercentage: BusinessDetails.getCompletionPercentage(businessDetails),
                isCompleted: businessDetails.isCompleted
            }
        });

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

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

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

        res.json({
            success: true,
            message: 'Business details retrieved successfully',
            data: {
                businessDetails,
                completionPercentage: BusinessDetails.getCompletionPercentage(businessDetails),
                isCompleted: businessDetails.isCompleted
            }
        });

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

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

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

        res.json({
            success: true,
            message: 'Business details retrieved successfully',
            data: {
                businessDetails,
                completionPercentage: BusinessDetails.getCompletionPercentage(businessDetails),
                isCompleted: businessDetails.isCompleted
            }
        });

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

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

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

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

        await businessDetails.save();

        // Check completion status
        businessDetails.checkCompletion();

        res.json({
            success: true,
            message: 'Business details updated successfully',
            data: {
                businessDetails,
                completionPercentage: BusinessDetails.getCompletionPercentage(businessDetails),
                isCompleted: businessDetails.isCompleted
            }
        });

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

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

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

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

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

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

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

        // Check completion status
        businessDetails.checkCompletion();

        let missingFields = [];
        
        // Check if required references exist
        if (!businessDetails.schoolDetailsId) {
            missingFields.push('schoolDetails');
        }
        
        if (!businessDetails.graduateDetailsId) {
            missingFields.push('graduateDetails');
        }
        
        // Check business details
        const businessRequiredFields = [
            'businessName', 'businessType', 'industry', 'yearsRunning',
            'businessPincode', 'businessState', 'businessDistrict', 
            'businessTown', 'businessPOCName', 'businessPOCMobile'
        ];
        
        businessRequiredFields.forEach(field => {
            if (!businessDetails[field] || businessDetails[field].toString().trim().length === 0) {
                missingFields.push(`businessDetails.${field}`);
            }
        });

        res.json({
            success: true,
            message: 'Business completion status retrieved',
            data: {
                isCompleted: businessDetails.isCompleted,
                completionPercentage: BusinessDetails.getCompletionPercentage(businessDetails),
                missingFields,
                sections: {
                    schoolDetails: businessDetails.schoolDetailsId ? 1 : 0,
                    graduateDetails: businessDetails.graduateDetailsId ? 1 : 0,
                    businessDetails: businessRequiredFields.length
                }
            }
        });

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

// Get all business details (Admin)
exports.getAllBusinessDetails = async (req, res) => {
    try {
        const businessDetails = await BusinessDetails.find()
            .populate('userId', 'name mobile email')
            .populate('schoolDetailsId')
            .populate('graduateDetailsId')
            .sort({ createdAt: -1 });

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

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

// Search businesses by location
exports.searchBusinessesByLocation = async (req, res) => {
    try {
        const { pincode, state, district, town } = req.query;
        
        let query = {};
        
        if (pincode) {
            query.businessPincode = pincode;
        }
        if (state) {
            query.businessState = new RegExp(state, 'i');
        }
        if (district) {
            query.businessDistrict = new RegExp(district, 'i');
        }
        if (town) {
            query.businessTown = new RegExp(town, 'i');
        }

        const businesses = await BusinessDetails.find(query)
            .populate('userId', 'name mobile email')
            .populate('schoolDetailsId')
            .populate('graduateDetailsId')
            .select('businessName businessType industry yearsRunning businessPincode businessState businessDistrict businessTown businessPOCName businessPOCMobile')
            .limit(50);

        res.json({
            success: true,
            message: 'Businesses found successfully',
            data: {
                businesses,
                totalCount: businesses.length
            }
        });

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

// Search businesses by industry
exports.searchBusinessesByIndustry = async (req, res) => {
    try {
        const { industry } = req.query;
        
        if (!industry) {
            return res.status(400).json({
                success: false,
                message: 'Industry parameter is required'
            });
        }

        const businesses = await BusinessDetails.find({
            industry: new RegExp(industry, 'i')
        })
        .populate('userId', 'name mobile email')
        .populate('schoolDetailsId')
        .populate('graduateDetailsId')
        .select('businessName businessType industry yearsRunning businessPincode businessState businessDistrict businessTown businessPOCName businessPOCMobile')
        .limit(50);

        res.json({
            success: true,
            message: 'Businesses found successfully',
            data: {
                businesses,
                totalCount: businesses.length
            }
        });

    } catch (error) {
        console.error('Error searching businesses by industry:', error);
        res.status(500).json({
            success: false,
            message: 'Error searching businesses by industry',
            error: error.message
        });
    }
};
