const Header = require("../models/header");

// Get all social links
exports.index = async (req, res) => {
    try {
        const header = await Header.findOne({ status: "active" }).sort({ order: 1 });

        if (!header) {
            return res.status(404).json({
                success: false,
                message: "No active header found",
            });
        }

        res.json({
            success: true,
            data: header.top?.socialLinks || [],
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message,
        });
    }
};

// Get single social link by platform
exports.show = async (req, res) => {
    try {
        const { platform } = req.params;
        const header = await Header.findOne({ status: "active" }).sort({ order: 1 });

        if (!header) {
            return res.status(404).json({
                success: false,
                message: "No active header found",
            });
        }

        const socialLink = header.top?.socialLinks?.find((link) => link.platform === platform);

        if (!socialLink) {
            return res.status(404).json({
                success: false,
                message: "Social link not found",
            });
        }

        res.json({
            success: true,
            data: socialLink,
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message,
        });
    }
};

// Create social link
exports.store = async (req, res) => {
    try {
        let { platform, url, icon } = req.body;

        // Convert platform to lowercase
        platform = platform.toLowerCase().trim();
        url = url.trim();
        icon = icon ? icon.trim() : null;

        console.log("Creating social link:", { platform, url, icon });

        // Validate required fields
        if (!platform || !url) {
            console.log("Validation failed: platform or url missing");
            return res.status(400).json({
                success: false,
                message: "Platform and URL are required",
            });
        }

        // Validate platform is in enum
        const validPlatforms = ["linkedin", "twitter", "instagram", "youtube", "facebook"];
        if (!validPlatforms.includes(platform)) {
            console.log("Invalid platform:", platform);
            return res.status(400).json({
                success: false,
                message: `Invalid platform. Must be one of: ${validPlatforms.join(", ")}`,
            });
        }

        // Find header
        let header = await Header.findOne({ status: "active" }).sort({ order: 1 });

        if (!header) {
            console.log("No active header found");
            return res.status(404).json({
                success: false,
                message: "No active header found",
            });
        }

        console.log("Found header:", header._id);

        // Check if platform already exists
        const existingLink = header.top?.socialLinks?.find((link) => link.platform === platform);

        if (existingLink) {
            console.log("Platform already exists:", platform);
            return res.status(400).json({
                success: false,
                message: `Social link for ${platform} already exists`,
            });
        }

        // Add new social link
        if (!header.top) {
            header.top = {};
        }
        if (!header.top.socialLinks) {
            header.top.socialLinks = [];
        }

        // Calculate next order number
        const maxOrder =
            header.top.socialLinks.length > 0 ? Math.max(...header.top.socialLinks.map((link) => link.order || 0)) : 0;

        header.top.socialLinks.push({
            platform,
            url,
            icon: icon || `fa-brands fa-${platform}`,
            order: maxOrder + 1,
        });

        console.log("Saving header with new social link");
        await header.save();

        console.log("Social link created successfully");
        res.status(201).json({
            success: true,
            message: "Social link created successfully",
            data: header.top.socialLinks[header.top.socialLinks.length - 1],
        });
    } catch (error) {
        console.error("Error creating social link:", error);
        res.status(400).json({
            success: false,
            message: error.message,
        });
    }
};

// Update social link
exports.update = async (req, res) => {
    try {
        let { platform } = req.params;
        let { url, icon } = req.body;

        // Convert to lowercase
        platform = platform.toLowerCase().trim();
        url = url.trim();
        icon = icon ? icon.trim() : null;

        // Validate required fields
        if (!url) {
            return res.status(400).json({
                success: false,
                message: "URL is required",
            });
        }

        // Find header
        const header = await Header.findOne({ status: "active" }).sort({ order: 1 });

        if (!header) {
            return res.status(404).json({
                success: false,
                message: "No active header found",
            });
        }

        // Find and update social link
        const socialLink = header.top?.socialLinks?.find((link) => link.platform === platform);

        if (!socialLink) {
            return res.status(404).json({
                success: false,
                message: "Social link not found",
            });
        }

        socialLink.url = url;
        if (icon) {
            socialLink.icon = icon;
        }

        await header.save();

        res.json({
            success: true,
            message: "Social link updated successfully",
            data: socialLink,
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message,
        });
    }
};

// Delete social link
exports.destroy = async (req, res) => {
    try {
        let { platform } = req.params;

        // Convert to lowercase
        platform = platform.toLowerCase().trim();

        console.log("Deleting social link:", platform);

        // Find header
        const header = await Header.findOne({ status: "active" }).sort({ order: 1 });

        if (!header) {
            console.log("No active header found");
            return res.status(404).json({
                success: false,
                message: "No active header found",
            });
        }

        // Find and remove social link
        const index = header.top?.socialLinks?.findIndex((link) => link.platform === platform);

        if (index === -1 || index === undefined) {
            console.log("Social link not found:", platform);
            return res.status(404).json({
                success: false,
                message: "Social link not found",
            });
        }

        const deletedLink = header.top.socialLinks.splice(index, 1);

        console.log("Saving header after delete");
        await header.save();

        console.log("Social link deleted successfully");
        res.json({
            success: true,
            message: "Social link deleted successfully",
            data: deletedLink[0],
        });
    } catch (error) {
        console.error("Error deleting social link:", error);
        res.status(500).json({
            success: false,
            message: error.message,
        });
    }
};

// Bulk update social links (used for reordering and batch updates)
exports.reorder = async (req, res) => {
    try {
        const { socialLinks } = req.body;

        if (!Array.isArray(socialLinks)) {
            return res.status(400).json({
                success: false,
                message: "socialLinks must be an array",
            });
        }

        // Find header
        let header = await Header.findOne({ status: "active" }).sort({ order: 1 });

        if (!header) {
            return res.status(404).json({
                success: false,
                message: "No active header found",
            });
        }

        // Validate all social links
        for (const link of socialLinks) {
            if (!link.platform || !link.url) {
                return res.status(400).json({
                    success: false,
                    message: "Each social link must have platform and url",
                });
            }
        }

        // Update social links with order field
        if (!header.top) {
            header.top = {};
        }

        header.top.socialLinks = socialLinks.map((link, index) => ({
            platform: link.platform,
            url: link.url,
            icon: link.icon || `fa-brands fa-${link.platform}`,
            order: link.order || index + 1, // Use provided order or calculate from index
        }));

        await header.save();

        res.json({
            success: true,
            message: "Social links updated successfully",
            data: header.top.socialLinks,
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message,
        });
    }
};
