import React, { useState, useRef, useEffect } from "react";
import { PlusIcon } from "@heroicons/react/24/outline";
import { extractPlatformFromUrl } from "../../helpers/extractPlatformFromUrl";
import { getPlatformIcon } from "../../helpers/getPlatformIcon";
import { twMerge } from "tailwind-merge";

interface PlatformLinksButtonProps {
    links: string[];
    className?: string;
}

const PlatformLinksButton: React.FC<PlatformLinksButtonProps> = ({
    links,
    className,
}) => {
    const [isPopupOpen, setIsPopupOpen] = useState(false);
    const popupRef = useRef<HTMLDivElement>(null);
    const buttonRef = useRef<HTMLDivElement>(null);

    const validLinks = links.filter((link) => link && link.trim().length > 0);

    const platforms = validLinks.map((link) => ({
        url: link,
        name: extractPlatformFromUrl(link),
    }));

    const displayPlatforms = platforms.slice(0, 2);
    const hasMorePlatforms = platforms.length > 2;

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                popupRef.current &&
                !popupRef.current.contains(event.target as Node) &&
                buttonRef.current &&
                !buttonRef.current.contains(event.target as Node)
            ) {
                setIsPopupOpen(false);
            }
        };

        if (isPopupOpen) {
            document.addEventListener("mousedown", handleClickOutside);
        }

        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [isPopupOpen]);

    if (validLinks.length === 0) {
        return null;
    }

    if (validLinks.length === 1) {
        return (
            <div className="flex items-center gap-2">
                <button
                    onClick={() => window.open(validLinks[0], "_blank")}
                    className={twMerge(
                        "hover:opacity-70 transition-opacity",
                        className,
                    )}
                    title={platforms[0].name}
                >
                    <img
                        src={getPlatformIcon(validLinks[0])}
                        alt={platforms[0].name}
                        className="h-6 w-6 object-contain rounded-lg"
                    />
                </button>
            </div>
        );
    }

    return (
        <div className="relative" ref={buttonRef}>
            <div className="flex items-center gap-2">
                <div className="flex gap-2">
                    {displayPlatforms.map((platform, index) => (
                        <button
                            key={index}
                            onClick={() => window.open(platform.url, "_blank")}
                            className={twMerge(
                                "hover:opacity-70 transition-opacity",
                                className,
                            )}
                            title={platform.name}
                        >
                            <img
                                src={getPlatformIcon(platform.url)}
                                alt={platform.name}
                                className="h-6 w-6 object-contain rounded-lg"
                            />
                        </button>
                    ))}

                    {hasMorePlatforms && (
                        <button
                            onClick={(e) => {
                                e.stopPropagation();
                                setIsPopupOpen(!isPopupOpen);
                            }}
                            className={twMerge(
                                "h-6 w-6 flex items-center justify-center rounded-lg bg-primary text-white hover:opacity-80 transition-opacity",
                                className,
                            )}
                            title="Voir plus de liens"
                        >
                            <PlusIcon className="h-4 w-4" />
                        </button>
                    )}
                </div>
            </div>

            {isPopupOpen && hasMorePlatforms && (
                <div
                    ref={popupRef}
                    className="absolute top-full mt-2 right-0 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-[250px] max-w-[300px]"
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="p-3">
                        <h3 className="text-sm font-semibold text-gray-700 mb-2">
                            Tous les liens
                        </h3>
                        <div className="space-y-2">
                            {platforms.map((platform, index) => (
                                <a
                                    key={index}
                                    href={platform.url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md transition-colors group"
                                >
                                    <img
                                        src={getPlatformIcon(platform.url)}
                                        alt={platform.name}
                                        className="h-6 w-6 object-contain flex-shrink-0"
                                    />
                                    <span className="text-sm text-gray-700 group-hover:text-primary truncate">
                                        {platform.name}
                                    </span>
                                </a>
                            ))}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default PlatformLinksButton;
