"use client";

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import Image, { StaticImageData } from "next/image";
import Link from "next/link";
import BlueArrow from "../../../../public/images/blue-arrow-up-right.svg";
import CloseModal from "../../../../public/images/close-modal.svg";
import { getImageSrc } from "@/utils/image";

export interface BookAnAppointmentModalProps {
    className?: string;
    buttonText?: string;
    buttonBgClass?: string;
    buttonTextClass?: string;
    arrowIcon?: StaticImageData;
}

export interface BookAppointmentData {
    modal_title: string;
    services: ServiceItem[];
    contacts: ContactEnquiries;
}

export interface ServiceItem {
    label: string;
    title: string;
    link: string;
}

export interface ContactEnquiries {
    label: string;
    phone_icon: string;
    phone_number: string;
    email_icon: string;
    email_address: string;
}

export default function BookAnAppointmentModal({
    className = "",
    buttonText = "Book appointment",
    buttonBgClass = "bg-[#1718FF]",
    buttonTextClass = "text-white",
    arrowIcon,
}: BookAnAppointmentModalProps) {
    const [open, setOpen] = useState(false);
    const [mounted, setMounted] = useState(false);
    const [modalData, setModalData] = useState<BookAppointmentData | null>(null);

    // Ensure we are in a client environment before rendering portal
    useEffect(() => {
        setMounted(true);
    }, []);

    // Fetch appointment data from API when modal opens or language changes
    useEffect(() => {
        if (!open) return;

        async function fetchAppointmentData() {
            try {
                const matches = document.cookie.match(/(?:^|; )lang=([^;]*)/);
                const lang = matches ? matches[1]?.toLowerCase() : "fr";

                const apiBaseUrl =
                    process.env.NEXT_PUBLIC_API_BASE_URL ||
                    "https://cms.terralogic.in/oculus_be/wp-json/api/";
                const cleanUrl = apiBaseUrl.trim().replace(/^['"]|['"]$/g, "");
                const separator = cleanUrl.includes("?") ? "&" : "?";
                const url = `${cleanUrl}book-appointment${separator}lang=${lang}`;

                const res = await fetch(url, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    cache: "no-store",
                });
                const result = await res.json();
                if (result.status && result.data) {
                    setModalData(result.data);
                }
            } catch (error) {
                console.error("Failed to fetch appointment data", error);
            }
        }

        fetchAppointmentData();

        const handleLanguageUpdate = () => {
            fetchAppointmentData();
        };

        window.addEventListener("languageChange", handleLanguageUpdate);
        return () => {
            window.removeEventListener("languageChange", handleLanguageUpdate);
        };
    }, [open]);

    // Handle ESC key to close modal
    useEffect(() => {
        if (!open) return;

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === "Escape") {
                setOpen(false);
            }
        };

        window.addEventListener("keydown", handleKeyDown);
        return () => {
            window.removeEventListener("keydown", handleKeyDown);
        };
    }, [open]);

    // Lock page scroll when modal is open and prevent Windows scrollbar layout shift (jerking)
    useEffect(() => {
        let timer: NodeJS.Timeout;

        if (open) {
            const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
            document.body.style.overflow = "hidden";
            if (scrollbarWidth > 0) {
                document.body.style.paddingRight = `${scrollbarWidth}px`;
            }
        } else {
            // Delay unlocking body overflow until smooth 500ms exit animation finishes
            timer = setTimeout(() => {
                document.body.style.overflow = "";
                document.body.style.paddingRight = "";
            }, 500);
        }

        return () => {
            clearTimeout(timer);
        };
    }, [open]);

    // Listen for Calendly popup close event or DOM removal to ensure scroll is restored
    useEffect(() => {
        if (typeof window === "undefined" || !document?.body) return;

        const handleCalendlyClose = (e: MessageEvent) => {
            if (e.data?.event === "calendly.popup_closed") {
                document.body.style.overflow = "";
                document.body.style.paddingRight = "";
            }
        };

        window.addEventListener("message", handleCalendlyClose);

        const observer = new MutationObserver(() => {
            const hasCalendlyOverlay = !!document.querySelector(".calendly-overlay");
            if (!hasCalendlyOverlay) {
                document.body.style.overflow = "";
                document.body.style.paddingRight = "";
            }
        });

        observer.observe(document.body, { childList: true, subtree: true });

        return () => {
            window.removeEventListener("message", handleCalendlyClose);
            observer.disconnect();
        };
    }, []);

    // API fallback data matching the Figma spec and provided response structure
    const displayTitle = modalData?.modal_title || "Book an appointment";
    const displayServices = modalData?.services || [
        {
            label: "FREE!",
            title: "Laser Assessment",
            link: "https://calendly.com/oculus-laser",
        },
        {
            label: "COSMETIC",
            title: "Cosmetic & Medical Surgery",
            link: "https://calendly.com/esthetikamed",
        },
        {
            label: "ORTHO & OPHTHALMOLOGY",
            title: "Medical Consultation",
            link: "#",
        },
    ];
    const displayContacts = modalData?.contacts || {
        label: "GENERAL ENQUIRIES",
        phone_number: "+12 3452 3543",
        phone_icon: "https://cms.terralogic.in/oculus_be/wp-content/uploads/2026/07/phone-appoint.svg",
        email_address: "contact@oculuscliniques.com",
        email_icon: "https://cms.terralogic.in/oculus_be/wp-content/uploads/2026/07/email-icon.svg",
    };

    // Handle service click: Open Calendly in an in-page popup modal immediately
    const handleServiceClick = (e: React.MouseEvent<HTMLAnchorElement>, link: string) => {
        if (!link || link === "#") {
            e.preventDefault();
            return;
        }

        if (link.includes("calendly.com")) {
            e.preventDefault();
            setOpen(false);

            if (typeof window !== "undefined") {
                const calendlyWindow = window as any;
                const triggerCalendly = () => {
                    if (calendlyWindow.Calendly) {
                        calendlyWindow.Calendly.initPopupWidget({ url: link });
                    }
                };

                if (calendlyWindow.Calendly) {
                    triggerCalendly();
                } else {
                    // Dynamically load Calendly widget stylesheet and script
                    const cssId = "calendly-widget-css";
                    if (!document.getElementById(cssId)) {
                        const linkEl = document.createElement("link");
                        linkEl.id = cssId;
                        linkEl.rel = "stylesheet";
                        linkEl.href = "https://assets.calendly.com/assets/external/widget.css";
                        document.head.appendChild(linkEl);
                    }

                    const script = document.createElement("script");
                    script.src = "https://assets.calendly.com/assets/external/widget.js";
                    script.onload = () => {
                        triggerCalendly();
                    };
                    document.body.appendChild(script);
                }
            }
        }
    };

    return (
        <>
            {/* Modal Trigger Button */}
            <button
                onClick={() => setOpen(true)}
                className={`${buttonBgClass} ${buttonTextClass} ${className} text-[16px] md:text-[18px] group font-bold inline-flex items-center justify-center rounded-[8px] py-3 px-5 md:px-6 whitespace-normal md:whitespace-nowrap cursor-pointer transition-all duration-300 outline-none focus-visible:ring-2 focus-visible:ring-[#1718FF]`}
            >
                {buttonText}
                {getImageSrc(arrowIcon) && (
                    <Image
                        className="ml-2 transition-transform duration-300 ease-in-out group-hover:translate-x-1"
                        src={getImageSrc(arrowIcon)!}
                        width={20}
                        height={20}
                        alt="Arrow Icon"
                    />
                )}
            </button>

            {/* Portal-rendered Modal Backdrop and Frame */}
            {mounted &&
                createPortal(
                    <div
                        onClick={() => setOpen(false)}
                        className={`fixed inset-0 z-[9999999] flex items-center justify-center p-4 transition-all duration-500 ease-in-out ${open
                            ? "opacity-100 bg-[rgba(15,23,42,0.75)] pointer-events-auto"
                            : "opacity-0 bg-transparent pointer-events-none"
                            }`}
                    >
                        {/* Modal Container */}
                        <div
                            onClick={(e) => e.stopPropagation()}
                            className={`relative w-full max-w-[530px] bg-white rounded-[24px] shadow-2xl overflow-hidden transition-all duration-500 cubic-bezier(0.16,1,0.3,1) ${open
                                ? "translate-y-0 scale-100 opacity-100"
                                : "translate-y-8 scale-[0.94] opacity-0 pointer-events-none"
                                }`}
                        >
                            {/* Modal Header */}
                            <div className="flex items-center justify-between px-6 py-6 md:px-8 md:py-7 bg-white">
                                <h2 className="text-[20px] md:text-[24px] font-bold text-[#00204F]">
                                    {displayTitle}
                                </h2>

                                <button
                                    onClick={() => setOpen(false)}
                                    className="cursor-pointer outline-none p-2 rounded-full hover:bg-[#EEF1F7] transition-all duration-300"
                                    aria-label="Close modal"
                                >
                                    <Image
                                        src={CloseModal}
                                        alt="Close Icon"
                                        width={20}
                                        height={20}
                                        className="transition-opacity duration-300 ease-out hover:opacity-80"
                                    />
                                </button>
                            </div>

                            {/* Service Appointment Links */}
                            <div className="flex flex-col bg-white">
                                {displayServices.map((item, index) => (
                                    <Link
                                        key={index}
                                        href={item.link}
                                        onClick={(e) => handleServiceClick(e, item.link)}
                                        className="group flex items-center justify-between border-t border-[#E5E9ED] px-6 py-5 md:px-8 md:py-6 transition-all duration-300 bg-white hover:bg-[#F2F4F6] outline-none focus-visible:bg-[#EEF1F7]/50"
                                    >
                                        <div className="flex flex-col text-left">
                                            <span className="text-[12px] text-[#4D6384] font-medium tracking-[0.5px] uppercase mb-1">
                                                {item.label}
                                            </span>
                                            <h3 className="text-[16px] font-medium text-[#00204F] transition-colors duration-200">
                                                {item.title}
                                            </h3>
                                        </div>

                                        <div className="flex-shrink-0 ml-4">
                                            <Image
                                                src={BlueArrow}
                                                alt="Blue Arrow Link"
                                                width={20}
                                                height={20}
                                                className="transition-transform duration-300 ease-out group-hover:rotate-45"
                                            />
                                        </div>
                                    </Link>
                                ))}
                            </div>

                            {/* Modal Footer (Contacts) */}
                            <div className="border-t border-[#E5E9ED] bg-[#EEF1F7] px-6 py-5 md:px-8 md:py-6 text-left">
                                <span className="text-[12px] font-medium text-[#4D6384] tracking-[0.5px] uppercase mb-4 block">
                                    {displayContacts.label}
                                </span>

                                <div className="flex flex-col gap-4 sm:flex-row sm:items-center md:justify-between sm:gap-8 md:gap-12">
                                    {/* Phone Link */}
                                    <Link
                                        href={`tel:${(displayContacts?.phone_number || "").replace(/\s+/g, "")}`}
                                        className="flex items-center gap-2.5 text-[16px] font-medium text-[#00204F] transition-colors duration-200 hover:text-[#1718FF] outline-none focus-visible:text-[#1718FF]"
                                    >
                                        {getImageSrc(displayContacts.phone_icon) && (
                                            <Image
                                                src={getImageSrc(displayContacts.phone_icon)!}
                                                alt="Phone Icon"
                                                width={18}
                                                height={18}
                                                className="object-contain"
                                            />
                                        )}
                                        {displayContacts.phone_number}
                                    </Link>

                                    {/* Email Link */}
                                    <Link
                                        href={`mailto:${displayContacts.email_address}`}
                                        className="flex items-center gap-2.5 text-[16px] font-medium text-[#00204F] transition-colors duration-200 hover:text-[#1718FF] outline-none focus-visible:text-[#1718FF]"
                                    >
                                        {getImageSrc(displayContacts.email_icon) && (
                                            <div className="w-[18px] relative">
                                                <Image
                                                    src={getImageSrc(displayContacts.email_icon)!}
                                                    alt="Email Icon"
                                                    width={18}
                                                    height={18}
                                                    className="object-contain"
                                                    style={{ width: '100%', height: 'auto' }}
                                                />
                                            </div>
                                        )}
                                        {displayContacts.email_address}
                                    </Link>
                                </div>
                            </div>
                        </div>
                    </div>,
                    document.body
                )}
        </>
    );
}