"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import staticCopy from "@/i18n/staticCopy.json";
import {
    DEFAULT_LOCALE,
    getStoredLocale,
    getStoredLocaleRaw,
    LOCALE_CHANGE_EVENT,
    type LocaleCode,
} from "@/i18n/localeSwitcher";

interface OrderInfoSectionProps {
    orderNumber?: string;
    email?: string;
    nextPaymentDate?: string;
    contactEmail?: string;
    contactPhone?: string;
    importantInformationTitle?: string;
    importantInformationRichtext?: string;
    needHelpTitle?: string;
    needHelpDescription?: string;
    needHelpContacts?: Array<{ text?: string; logo_svg?: string }>;
    needHelpButtons?: Array<{ button_text?: string; button_url?: string; logo_svg?: string }>;
    invoiceUrl?: string;
    receiptUrl?: string;
    emailReceiptUrl?: string;
    orderId?: string;
}

const IconArrow1 = () => (
    <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M0 18C0 8.05887 8.05887 0 18 0C27.9411 0 36 8.05887 36 18C36 27.9411 27.9411 36 18 36C8.05887 36 0 27.9411 0 18Z" fill="#F7FAF8" />
        <path d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5" stroke="#053F31" strokeWidth="2" />
    </svg>
);
const IconArrow2 = () => (
    <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M0 18C0 8.05888 8.05888 0 18 0C27.9411 0 36 8.05888 36 18C36 27.9411 27.9411 36 18 36C8.05888 36 0 27.9411 0 18Z" fill="#053F31" />
        <path d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5" stroke="#DAE6DC" strokeWidth="2" />
    </svg>

);

const IconDownload = () => (
    <svg width="23" height="23" viewBox="0 0 23 23" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M20.125 17.25V14.375C20.125 14.1844 20.0493 14.0016 19.9145 13.8668C19.7797 13.732 19.5969 13.6562 19.4062 13.6562C19.2156 13.6562 19.0328 13.732 18.898 13.8668C18.7632 14.0016 18.6875 14.1844 18.6875 14.375V17.25C18.6875 17.4406 18.6118 17.6234 18.477 17.7582C18.3422 17.893 18.1594 17.9688 17.9688 17.9688H5.03125C4.84063 17.9688 4.65781 17.893 4.52302 17.7582C4.38823 17.6234 4.3125 17.4406 4.3125 17.25V14.375C4.3125 14.1844 4.23677 14.0016 4.10198 13.8668C3.96719 13.732 3.78437 13.6562 3.59375 13.6562C3.40313 13.6562 3.22031 13.732 3.08552 13.8668C2.95073 14.0016 2.875 14.1844 2.875 14.375V17.25C2.875 17.8219 3.10218 18.3703 3.50655 18.7747C3.91093 19.1791 4.45938 19.4062 5.03125 19.4062H17.9688C18.5406 19.4062 19.0891 19.1791 19.4935 18.7747C19.8978 18.3703 20.125 17.8219 20.125 17.25ZM15.5394 13.4981L11.9456 16.3731C11.8187 16.4734 11.6617 16.5279 11.5 16.5279C11.3383 16.5279 11.1813 16.4734 11.0544 16.3731L7.46063 13.4981C7.32968 13.3745 7.2499 13.2063 7.23707 13.0267C7.22424 12.8471 7.27929 12.6692 7.39134 12.5282C7.50338 12.3873 7.66426 12.2935 7.84213 12.2655C8.02 12.2374 8.20192 12.2772 8.35187 12.3769L10.7812 14.3175V4.3125C10.7812 4.12188 10.857 3.93906 10.9918 3.80427C11.1266 3.66948 11.3094 3.59375 11.5 3.59375C11.6906 3.59375 11.8734 3.66948 12.0082 3.80427C12.143 3.93906 12.2188 4.12188 12.2188 4.3125V14.3175L14.6481 12.3769C14.7205 12.3086 14.8063 12.256 14.9 12.2226C14.9938 12.1891 15.0934 12.1755 15.1927 12.1826C15.292 12.1897 15.3887 12.2174 15.4767 12.2638C15.5648 12.3102 15.6422 12.3744 15.7041 12.4523C15.7661 12.5302 15.8112 12.6202 15.8365 12.7164C15.8619 12.8126 15.867 12.9131 15.8515 13.0114C15.836 13.1097 15.8003 13.2038 15.7465 13.2875C15.6928 13.3713 15.6223 13.443 15.5394 13.4981Z"  fill="#F7FAF8"  />
    </svg>

);

const IconPrint = () => (
    <svg width="23" height="23" viewBox="0 0 23 23" fill="none" xmlns="http://www.w3.org/2000/svg">
        <g clipPath="url(#clip0_1420_27395)">
            <path d="M21.1792 5.51042H18.3042V3.40208C18.3042 3.30625 18.2563 3.1625 18.1604 3.06667L15.0938 0.14375C14.9979 0.0479167 14.8542 0 14.7583 0H5.175C4.8875 0 4.69583 0.191667 4.69583 0.479167V5.51042H1.82083C0.814583 5.51042 0 6.325 0 7.33125V16.3396C0 17.3458 0.814583 18.1604 1.82083 18.1604H4.69583V22.5208C4.69583 22.8083 4.8875 23 5.175 23H17.825C18.1125 23 18.3042 22.8083 18.3042 22.5208V18.1604H21.1792C22.1854 18.1604 23 17.3458 23 16.3396V7.33125C23 6.325 22.1854 5.51042 21.1792 5.51042ZM15.2375 1.58125L16.6271 2.875H15.2375V1.58125ZM5.65417 0.958333H14.2792V3.40208C14.2792 3.68958 14.4708 3.88125 14.7583 3.88125H17.3458V5.51042H5.65417V0.958333ZM5.65417 22.0417V14.8062H17.3458V22.0417H5.65417ZM22.0417 16.3396C22.0417 16.8187 21.6583 17.2021 21.1792 17.2021H18.3042V14.8062H19.55C19.8375 14.8062 20.0292 14.6146 20.0292 14.3271C20.0292 14.0396 19.8375 13.8479 19.55 13.8479H3.45C3.1625 13.8479 2.97083 14.0396 2.97083 14.3271C2.97083 14.6146 3.1625 14.8062 3.45 14.8062H4.69583V17.2021H1.82083C1.34167 17.2021 0.958333 16.8187 0.958333 16.3396V7.33125C0.958333 6.85208 1.34167 6.46875 1.82083 6.46875H21.1792C21.6583 6.46875 22.0417 6.85208 22.0417 7.33125V16.3396Z" fill="#F7FAF8" />
            <path d="M20.4146 7.80859H20.0313C19.7438 7.80859 19.5521 8.00026 19.5521 8.28776C19.5521 8.57526 19.7438 8.76693 20.0313 8.76693H20.4146C20.7021 8.76693 20.8938 8.57526 20.8938 8.28776C20.8938 8.00026 20.7021 7.80859 20.4146 7.80859ZM18.4021 7.80859H18.0188C17.7312 7.80859 17.5396 8.00026 17.5396 8.28776C17.5396 8.57526 17.7312 8.76693 18.0188 8.76693H18.4021C18.6896 8.76693 18.8813 8.57526 18.8813 8.28776C18.8813 8.00026 18.6417 7.80859 18.4021 7.80859ZM15.4313 19.4044H7.57292C7.28542 19.4044 7.09375 19.5961 7.09375 19.8836C7.09375 20.1711 7.28542 20.3628 7.57292 20.3628H15.4313C15.7188 20.3628 15.9104 20.1711 15.9104 19.8836C15.9104 19.5961 15.7188 19.4044 15.4313 19.4044ZM15.4313 16.4815H7.57292C7.28542 16.4815 7.09375 16.6732 7.09375 16.9607C7.09375 17.2482 7.28542 17.4398 7.57292 17.4398H15.4313C15.7188 17.4398 15.9104 17.2482 15.9104 16.9607C15.9104 16.6732 15.7188 16.4815 15.4313 16.4815Z" fill="#F7FAF8" />
        </g>
        <defs>
            <clipPath id="clip0_1420_27395">
                <rect width="23" height="23" fill="white" />
            </clipPath>
        </defs>
    </svg>

);

function isContactEmail(text: string) {
    return text.includes("@");
}

async function downloadPdf(url: string, filename: string) {
    const headers: Record<string, string> = {
        "Content-Type": "application/json",
        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
    };

    try {
        const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
        const user = raw ? JSON.parse(raw) : null;
        const token = String(user?.token ?? user?.access_token ?? "").trim();
        if (token) headers.Authorization = `Bearer ${token}`;
    } catch {}

    const res = await fetch(url, {
        method: "GET",
        headers,
        credentials: "include",
    });

    if (!res.ok) throw new Error("Failed to download PDF");

    const blob = await res.blob();
    const objectUrl = window.URL.createObjectURL(blob);

    const a = document.createElement("a");
    a.href = objectUrl;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();

    window.URL.revokeObjectURL(objectUrl);
}

function contactHref(text: string) {
    const t = text.trim();
    if (!t) return "#";
    return isContactEmail(t) ? `mailto:${t}` : `tel:${t.replace(/\s/g, "")}`;
}

function extractListItemsFromHtml(html: string): string[] {
    const items: string[] = [];
    const re = /<li[^>]*>([\s\S]*?)<\/li>/gi;
    let m: RegExpExecArray | null;
    while ((m = re.exec(html)) !== null) {
        items.push(m[1].trim());
    }
    return items;
}

const IconMailOutline = () => (
    <svg width="23" height="23" viewBox="0 0 23 23" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M21.0833 2.875H1.91668C0.85958 2.875 0 3.73458 0 4.79168V18.2084C0 19.2654 0.85958 20.125 1.91668 20.125H21.0834C22.1404 20.125 23 19.2654 23 18.2083V4.79168C23 3.73458 22.1404 2.875 21.0833 2.875ZM1.91668 3.83332H21.0834C21.154 3.83332 21.2162 3.85906 21.2825 3.87361C19.6231 5.39229 14.1209 10.4259 12.1954 12.1607C12.0447 12.2964 11.8019 12.4583 11.5 12.4583C11.1982 12.4583 10.9554 12.2964 10.8042 12.1603C8.8789 10.4257 3.37637 5.39184 1.71727 3.8737C1.78367 3.85915 1.84602 3.83332 1.91668 3.83332ZM0.958318 18.2083V4.79168C0.958318 4.69779 0.986619 4.61262 1.01196 4.52682C2.28199 5.68922 6.12119 9.20139 8.61058 11.4651C6.12928 13.5965 2.28908 17.2374 1.00895 18.4581C0.98635 18.3766 0.958318 18.2969 0.958318 18.2083ZM21.0833 19.1667H1.91668C1.84013 19.1667 1.77208 19.14 1.70061 19.1229C3.02342 17.8619 6.88805 14.2001 9.32574 12.1147C9.6043 12.3676 9.88327 12.62 10.1626 12.872C10.5576 13.2286 11.0199 13.4167 11.5 13.4167C11.9801 13.4167 12.4424 13.2285 12.8369 12.8725C13.1164 12.6203 13.3955 12.3677 13.6743 12.1147C16.1121 14.1999 19.9762 17.8614 21.2994 19.1229C21.2279 19.14 21.16 19.1667 21.0833 19.1667ZM22.0417 18.2083C22.0417 18.2969 22.0136 18.3766 21.9911 18.4581C20.7105 17.2367 16.8707 13.5963 14.3895 11.4652C16.8789 9.20144 20.7176 5.68958 21.988 4.52673C22.0134 4.61253 22.0417 4.69775 22.0417 4.79164V18.2083Z" fill="#F7FAF8" />
    </svg>

);

export default function OrderInfoSection({
    importantInformationTitle,
    importantInformationRichtext,
    needHelpTitle,
    needHelpDescription,
    needHelpContacts,
    needHelpButtons,
    invoiceUrl,
    receiptUrl,
    emailReceiptUrl,
    orderId,
}: OrderInfoSectionProps) {
    const [emailLoading, setEmailLoading] = useState(false);
    const [emailSuccess, setEmailSuccess] = useState(false);
    const [emailError, setEmailError] = useState(false);
    const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

    useEffect(() => {
        const syncLocale = () => setUiLocale(getStoredLocale());
        syncLocale();
        window.addEventListener("storage", syncLocale);
        window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
        return () => {
            window.removeEventListener("storage", syncLocale);
            window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
        };
    }, []);

    const labels =
        staticCopy.orderInfoSection[uiLocale as keyof typeof staticCopy.orderInfoSection] ??
        staticCopy.orderInfoSection["en-EN"];

    const handleDownloadInvoice = async () => {
        if (!invoiceUrl || !orderId) return;
        try {
            const fullUrl = invoiceUrl.startsWith("http") ? invoiceUrl : `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}${invoiceUrl}`;
            await downloadPdf(fullUrl, `invoice-${orderId}.pdf`);
        } catch (error) {
        }
    };

    const handlePrintReceipt = async () => {
        if (!receiptUrl || !orderId) return;
        try {
            const fullUrl = receiptUrl.startsWith("http") ? receiptUrl : `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}${receiptUrl}`;
            await downloadPdf(fullUrl, `receipt-${orderId}.pdf`);
        } catch (error) {
        }
    };

    const handleEmailReceipt = async () => {
        if (!emailReceiptUrl) return;
        setEmailLoading(true);
        setEmailSuccess(false);
        setEmailError(false);
        try {
            const headers: Record<string, string> = {
                "Content-Type": "application/json",
                "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
                "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
            };

            try {
                const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
                const user = raw ? JSON.parse(raw) : null;
                const token = String(user?.token ?? user?.access_token ?? "").trim();
                if (token) headers.Authorization = `Bearer ${token}`;
            } catch {}

            const fullUrl = emailReceiptUrl.startsWith("http") ? emailReceiptUrl : `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}${emailReceiptUrl}`;
            const res = await fetch(fullUrl, {
                method: "POST",
                headers,
                credentials: "include",
            });
            if (res.ok) {
                setEmailSuccess(true);
                setTimeout(() => setEmailSuccess(false), 3000);
            } else {
                setEmailError(true);
                setTimeout(() => setEmailError(false), 3000);
            }
        } catch (error) {
            setEmailError(true);
            setTimeout(() => setEmailError(false), 3000);
        } finally {
            setEmailLoading(false);
        }
    };

    const infoHtml = importantInformationRichtext?.trim();
    const infoHeading = importantInformationTitle?.trim() || "Important Information";
    const importantInfoListItems = infoHtml ? extractListItemsFromHtml(infoHtml) : [];

    const needHelpButtonsFiltered =
        needHelpButtons?.filter(
            (b) => String(b.button_text ?? "").trim() !== "" || String(b.button_url ?? "").trim() !== ""
        ) ?? [];
    const needHelpContactsFiltered =
        needHelpContacts?.filter((c) => String(c.text ?? "").trim() !== "") ?? [];
    const hasNeedHelpCms =
        Boolean(needHelpTitle?.trim()) ||
        Boolean(needHelpDescription?.trim()) ||
        needHelpContactsFiltered.length > 0 ||
        needHelpButtonsFiltered.length > 0;

    return (
        <section className="mb-[50px] xl:mb-[70px] font-outfit">

            <div className="flex flex-col md:flex-row gap-[30px]">

                {infoHtml ? (
                    <div className="flex-1 rounded-[20px] border border-[#053F31]/10 bg-[#DAE6DC]/70 p-5">
                        <h4 className="font-outfit font-semibold text-[#053F31] mb-[10px] border-b border-[#000000]/10 pb-[10px]">
                            {infoHeading}
                        </h4>
                        {importantInfoListItems.length > 0 ? (
                            <ul className="space-y-[10px]">
                                {importantInfoListItems.map((innerHtml, i) => (
                                    <li key={i} className="flex items-center gap-[15px]">
                                        <span className="mt-[9px] h-[4px] w-[4px] shrink-0 rounded-full bg-black" />
                                        <span
                                            className="font-light text-[18px] leading-[150%]"
                                            dangerouslySetInnerHTML={{ __html: innerHtml }}
                                        />
                                    </li>
                                ))}
                            </ul>
                        ) : (
                            <div
                                className="font-light text-[18px] leading-[150%]"
                                dangerouslySetInnerHTML={{ __html: infoHtml }}
                            />
                        )}
                    </div>
                ) : null}

                {hasNeedHelpCms ? (
                    <div className="flex-1 rounded-[20px] border border-[#DAE6DC] bg-white px-6 py-7 md:[15px_30px] md:py-[15px_30px]">
                        {needHelpTitle?.trim() ? (
                            <p className="font-outfit text-[20px] font-medium text-[#000000] mb-[10px] border-b border-[#000000]/10 pb-[10px]">
                                {needHelpTitle.trim()}
                            </p>
                        ) : null}
                        {needHelpDescription?.trim() ? (
                            <span className="font-light text-[#999999]">{needHelpDescription.trim()}</span>
                        ) : null}

                        {needHelpContactsFiltered.length > 0 ? (
                            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 mt-[10px] mb-[10px]">
                                {needHelpContactsFiltered.flatMap((item, index) => {
                                    const text = String(item.text ?? "").trim();
                                    const svg = String(item.logo_svg ?? "").trim();
                                    const row = (
                                        <div key={`${text}-${index}`} className="flex items-center gap-3">
                                            <a
                                                href={contactHref(text)}
                                                className="flex items-center justify-center shrink-0 rounded-[12px] border border-[#DAE6DC] bg-[#053F31]/5 p-[14px] transition"
                                            >
                                                {svg ? (
                                                    <span
                                                        className="inline-flex shrink-0 [&_svg]:block"
                                                        dangerouslySetInnerHTML={{ __html: svg }}
                                                        aria-hidden
                                                    />
                                                ) : null}
                                            </a>
                                            <p className="font-medium text-[14px] text-[#053F31]">{text}</p>
                                        </div>
                                    );
                                    if (index === 0) return [row];
                                    return [
                                        <div
                                            key={`divider-${index}`}
                                            className="hidden sm:block w-px h-[50px] bg-[#000000]/10 mx-[10px] shrink-0"
                                        />,
                                        row,
                                    ];
                                })}
                            </div>
                        ) : null}

                        {needHelpButtonsFiltered.length > 0 ? (
                            <div
                                className={`flex flex-col sm:flex-row gap-3 ${
                                    needHelpTitle?.trim() ||
                                    needHelpDescription?.trim() ||
                                    needHelpContactsFiltered.length > 0
                                        ? "mt-[10px]"
                                        : ""
                                }`}
                            >
                                {needHelpButtonsFiltered.map((btn: any, index) => {
                                    const label = String(btn.button_text || btn.button_label || btn.text || "").trim() || "Learn more";
                                    const href = String(btn.button_url || btn.url || btn.href || "").trim() || "#";
                                    const btnSvg = String(btn.logo_svg || btn.icon_svg || btn.icon || "").trim();
                                    const primary = index % 2 === 0;

                                    return (
                                        <Link
                                            key={`${href}-${label}-${index}`}
                                            href={href}
                                            className={
                                                primary
                                                    ? "group flex items-center justify-center gap-3 font-outfit text-[18px] font-semibold cursor-pointer border-2 border-[#0F3F32] bg-[#0F3F32] text-white p-[7px_7px_7px_15px] rounded-full hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
                                                    : "group flex items-center justify-center gap-3 font-outfit text-[18px] font-semibold cursor-pointer border-2 border-[#0F3F32] text-[#0F3F32] p-[7px_7px_7px_15px] rounded-full hover:bg-[#0F3F32] hover:text-white transition"
                                            }
                                        >
                                            <span className="shrink-0">{label}</span>
                                            {btnSvg ? (
                                                <span
                                                    className="inline-flex shrink-0 [&_svg]:block w-[36px] h-[36px]"
                                                    dangerouslySetInnerHTML={{ __html: btnSvg }}
                                                    aria-hidden
                                                />
                                            ) : (
                                                <span className="shrink-0">
                                                    {primary ? <IconArrow1 /> : <IconArrow2 />}
                                                </span>
                                            )}
                                        </Link>
                                    );
                                })}
                            </div>
                        ) : null}
                    </div>
                ) : null}
            </div>

            <div className="mt-[30px] grid grid-cols-1 sm:grid-cols-3 gap-[20px]">
                <button
                    onClick={handleDownloadInvoice}
                    disabled={!invoiceUrl || !orderId}
                    className="flex items-center justify-center gap-3 rounded-full bg-[#053F31] px-6 py-[10px] font-outfit text-[18px] font-semibold text-white transition
                        hover:bg-[#021f18] cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {labels.downloadInvoice}
                    <span><IconDownload /></span>
                </button>
                <button
                    onClick={handlePrintReceipt}
                    disabled={!receiptUrl || !orderId}
                    className="flex items-center justify-center gap-3 rounded-full bg-[#053F31] px-6 py-[10px] font-outfit text-[18px] font-semibold text-white transition
                        hover:bg-[#021f18] cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {labels.printReceipt}
                    <span><IconPrint /></span>
                </button>
                <button
                    onClick={handleEmailReceipt}
                    disabled={!emailReceiptUrl || emailLoading}
                    className={`flex items-center justify-center gap-3 rounded-full px-6 py-[10px] font-outfit text-[18px] font-semibold text-white transition
                        hover:bg-[#021f18] cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed
                        ${emailSuccess ? "bg-green-600 hover:bg-green-700" : emailError ? "bg-red-600 hover:bg-red-700" : "bg-[#053F31]"}`}
                >
                    {emailLoading ? labels.emailSending : emailSuccess ? labels.emailSent : emailError ? labels.emailFailed : labels.emailReceipt}
                    <span><IconMailOutline /></span>
                </button>
            </div>
        </section>
    );
}
