import TaleButton from "@components/TaleButton";
import { TaleInput } from "@components/TaleInput";
import { SharingContainer } from "@pages/survey/new/scratch/Step4/SharingContainer";
import { useMemo, useState } from "react";

export const SocialMediaShare = ({ linkName, setLinkName, surveyTitle, surveyBannerUrl }) => {
    const [copied, setCopied] = useState(false);

    const storedUser = JSON.parse(localStorage.getItem("user"));
    const companyName = storedUser?.companyName;
    const survLink = `${process.env.REACT_APP_WEBSITE}/survey/${companyName}/${linkName}`;

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(survLink);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        } catch (err) {
            console.error("Failed to copy:", err);
        }
    };

    const shareHandlers = useMemo(
        () => ({
            Facebook: () => {
                // OG tags are read from the public survey page by Facebook's crawler.
                // The sharer dialog reads og:title, og:description, og:image from that URL.
                const url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(survLink)}`;
                window.open(url, "_blank", "width=600,height=400,noopener,noreferrer");
            },
            Linkedin: () => {
                const url = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(survLink)}`;
                window.open(url, "_blank", "width=600,height=500,noopener,noreferrer");
            },
            "Twitter/X": () => {
                const text = surveyTitle ? `${surveyTitle} — Take the survey!` : "Take this survey!";
                const url = `https://twitter.com/intent/tweet?url=${encodeURIComponent(survLink)}&text=${encodeURIComponent(text)}`;
                window.open(url, "_blank", "width=600,height=400,noopener,noreferrer");
            },
        }),
        [survLink, surveyTitle]
    );

    const socialMedias = useMemo(
        () => [
            { label: "Facebook", bg: "#064DD7", icon: "/assets/social-media/facebook.svg" },
            { label: "Linkedin", bg: "#0673D7", icon: "/assets/social-media/linkedin.svg" },
            { label: "Twitter/X", bg: "#00A3FF", icon: "/assets/social-media/x.svg" },
        ],
        []
    );

    return (
        <SharingContainer
            title="Share a survey link in social media"
            text="Copy this URL to share your survey. For example, post it on Facebook, Twitter or LinkedIn."
        >
            <TaleInput
                className="md:!max-w-[40%]"
                label="Link name"
                labelClassName="!text-base"
                placeholder="Enter a name for the link"
                readOnly={true}
                value={linkName}
                onChange={(e) => setLinkName(e.target.value)}
            />
            <TaleInput
                className="md:!max-w-[40%] !font-semibold"
                label="Your link"
                labelClassName="!text-base"
                readOnly={true}
                disabled={true}
                value={survLink}
                forceEmptyStyling={true}
                adornment={<img src="/assets/link.svg" alt="Link" />}
                suffix={
                    <div className="grow flex items-center justify-end h-full">
                        <TaleButton role="normal" className="!max-h-[calc(100%-9px)]" onClick={handleCopy}>
                            {copied ? "Copied!" : "Copy"}
                        </TaleButton>
                    </div>
                }
            />

            {/* Preview card — shown when banner/title are available */}
            {(surveyTitle || surveyBannerUrl) && (
                <div className="md:max-w-[40%] border border-gray-200 rounded-xl overflow-hidden shadow-sm">
                    {surveyBannerUrl && (
                        <img
                            src={surveyBannerUrl}
                            alt="Survey banner"
                            className="w-full h-32 object-cover"
                        />
                    )}
                    <div className="p-3 bg-gray-50">
                        <p className="text-xs text-gray-400 uppercase tracking-wide mb-1">
                            {new URL(process.env.REACT_APP_WEBSITE).hostname}
                        </p>
                        {surveyTitle && (
                            <p className="text-sm font-semibold text-gray-800 line-clamp-2">{surveyTitle}</p>
                        )}
                    </div>
                </div>
            )}

            <div className="flex gap-2 flex-wrap">
                {socialMedias.map((e, i) => (
                    <button
                        key={i}
                        onClick={() => shareHandlers[e.label]?.()}
                        disabled={!linkName}
                        className="flex gap-2 items-center justify-center p-3 rounded-lg font-semibold text-white text-lg min-w-[150px] transition-opacity disabled:opacity-40 disabled:cursor-not-allowed"
                        style={{ background: e.bg }}
                    >
                        <img src={e.icon} alt={e.label} />
                        {e.label}
                    </button>
                ))}
            </div>
        </SharingContainer>
    );
};