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

// Create or update portfolio
const createOrUpdatePortfolio = async (req, res) => {
    try {
        const userId = req.user.id;
        const portfolioData = req.body;

        // Check if portfolio exists
        let portfolio = await Portfolio.findOne({ userId });

        if (portfolio) {
            // Update existing portfolio
            Object.keys(portfolioData).forEach(key => {
                if (portfolioData[key] !== undefined) {
                    portfolio[key] = portfolioData[key];
                }
            });
            portfolio.lastUpdated = new Date();
        } else {
            // Create new portfolio
            portfolio = new Portfolio({
                userId,
                ...portfolioData
            });
        }

        // Generate shareable link
        portfolio.shareableLink = `https://yourdomain.com/portfolio/${userId}`;

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: portfolio.isNew ? 'Portfolio created successfully' : 'Portfolio updated successfully',
            data: portfolio
        });
    } catch (error) {
        console.error('Create/Update portfolio error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to create/update portfolio',
            error: error.message
        });
    }
};

// Get user's portfolio
const getUserPortfolio = async (req, res) => {
    try {
        const userId = req.user.id;

        const portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio not found'
            });
        }

        res.status(200).json({
            success: true,
            data: portfolio
        });
    } catch (error) {
        console.error('Get user portfolio error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get portfolio',
            error: error.message
        });
    }
};

// Get public portfolio by link
const getPublicPortfolio = async (req, res) => {
    try {
        const { userId } = req.params;

        const portfolio = await Portfolio.findOne({ 
            userId,
            isPublic: true 
        }).populate('userId', 'name mobile');

        if (!portfolio) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio not found or not public'
            });
        }

        res.status(200).json({
            success: true,
            data: portfolio
        });
    } catch (error) {
        console.error('Get public portfolio error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get public portfolio',
            error: error.message
        });
    }
};

// Add education to portfolio
const addEducation = async (req, res) => {
    try {
        const userId = req.user.id;
        const educationData = req.body;

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            portfolio = new Portfolio({ userId });
        }

        portfolio.education.push(educationData);
        portfolio.lastUpdated = new Date();

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: 'Education added successfully',
            data: portfolio.education
        });
    } catch (error) {
        console.error('Add education error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add education',
            error: error.message
        });
    }
};

// Add skill to portfolio
const addSkill = async (req, res) => {
    try {
        const userId = req.user.id;
        const skillData = req.body;

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            portfolio = new Portfolio({ userId });
        }

        portfolio.skills.push(skillData);
        portfolio.lastUpdated = new Date();

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: 'Skill added successfully',
            data: portfolio.skills
        });
    } catch (error) {
        console.error('Add skill error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add skill',
            error: error.message
        });
    }
};

// Add project to portfolio
const addProject = async (req, res) => {
    try {
        const userId = req.user.id;
        const projectData = req.body;

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            portfolio = new Portfolio({ userId });
        }

        portfolio.projects.push(projectData);
        portfolio.lastUpdated = new Date();

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: 'Project added successfully',
            data: portfolio.projects
        });
    } catch (error) {
        console.error('Add project error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add project',
            error: error.message
        });
    }
};

// Add work experience to portfolio
const addWorkExperience = async (req, res) => {
    try {
        const userId = req.user.id;
        const workData = req.body;

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            portfolio = new Portfolio({ userId });
        }

        portfolio.workExperience.push(workData);
        portfolio.lastUpdated = new Date();

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: 'Work experience added successfully',
            data: portfolio.workExperience
        });
    } catch (error) {
        console.error('Add work experience error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add work experience',
            error: error.message
        });
    }
};

// Upload document to portfolio
const uploadDocument = async (req, res) => {
    try {
        const userId = req.user.id;
        const { name, type } = req.body;

        if (!req.file) {
            return res.status(400).json({
                success: false,
                message: 'No file uploaded'
            });
        }

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            portfolio = new Portfolio({ userId });
        }

        const document = {
            name: name || req.file.originalname,
            type: type || req.file.mimetype,
            url: req.file.path,
            uploadedAt: new Date()
        };

        portfolio.documents.push(document);
        portfolio.lastUpdated = new Date();

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: 'Document uploaded successfully',
            data: document
        });
    } catch (error) {
        console.error('Upload document error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to upload document',
            error: error.message
        });
    }
};

// Toggle portfolio visibility
const togglePortfolioVisibility = async (req, res) => {
    try {
        const userId = req.user.id;
        const { isPublic } = req.body;

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio not found'
            });
        }

        portfolio.isPublic = isPublic;
        portfolio.lastUpdated = new Date();

        await portfolio.save();

        res.status(200).json({
            success: true,
            message: `Portfolio is now ${isPublic ? 'public' : 'private'}`,
            data: { isPublic: portfolio.isPublic }
        });
    } catch (error) {
        console.error('Toggle portfolio visibility error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to toggle portfolio visibility',
            error: error.message
        });
    }
};

// Delete portfolio item
const deletePortfolioItem = async (req, res) => {
    try {
        const userId = req.user.id;
        const { section, itemId } = req.params;

        let portfolio = await Portfolio.findOne({ userId });

        if (!portfolio) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio not found'
            });
        }

        let itemRemoved = false;

        switch (section) {
            case 'education':
                portfolio.education = portfolio.education.filter(
                    item => item._id.toString() !== itemId
                );
                itemRemoved = true;
                break;
            case 'skills':
                portfolio.skills = portfolio.skills.filter(
                    item => item._id.toString() !== itemId
                );
                itemRemoved = true;
                break;
            case 'projects':
                portfolio.projects = portfolio.projects.filter(
                    item => item._id.toString() !== itemId
                );
                itemRemoved = true;
                break;
            case 'workExperience':
                portfolio.workExperience = portfolio.workExperience.filter(
                    item => item._id.toString() !== itemId
                );
                itemRemoved = true;
                break;
            case 'documents':
                portfolio.documents = portfolio.documents.filter(
                    item => item._id.toString() !== itemId
                );
                itemRemoved = true;
                break;
            default:
                return res.status(400).json({
                    success: false,
                    message: 'Invalid section'
                });
        }

        if (itemRemoved) {
            portfolio.lastUpdated = new Date();
            await portfolio.save();
        }

        res.status(200).json({
            success: true,
            message: 'Item deleted successfully'
        });
    } catch (error) {
        console.error('Delete portfolio item error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete item',
            error: error.message
        });
    }
};

module.exports = {
    createOrUpdatePortfolio,
    getUserPortfolio,
    getPublicPortfolio,
    addEducation,
    addSkill,
    addProject,
    addWorkExperience,
    uploadDocument,
    togglePortfolioVisibility,
    deletePortfolioItem
};
