import React, {useEffect, useState} from 'react'
import './ThankYou.scss'
import {Icon, LinkAria, LoadingDots} from '$core-components'
import urlGenerator from '$ustoreinternal/services/urlGenerator'
import {t} from '$themelocalization'
import {Slot} from '$core-components'
import {useLocation} from "react-router-dom"
import {UStoreProvider} from '@ustore/core'
import Layout from '../components/layout'

const isSafeUrl = (url) => {
    try {
        const parsed = new URL(url, window.location.origin)
        return ['http:', 'https:'].includes(parsed.protocol)
    } catch {
        return false
    }
}

const ThankYou = (props) => {
    const location = useLocation()
    const [orderDetails, setOrderDetails] = useState({})

    useEffect(() => {
        (async () => {
            const pathMatch = location.pathname.match(/^(.*?)(?=\/thank-you)/)
            const path = pathMatch ? pathMatch[0] : location.pathname
            const params = new URLSearchParams(location.search)
            const orderID = params.get("orderID")

            const res = orderID
                ? await window.UStoreProvider.api.orders.getOrderDetails(orderID)
                : null;

            if (res) {
                setOrderDetails({
                    receiptUrl: res.ReceiptUrl,
                    orderNumber: res.OrderFriendlyID,
                    orderDetailsUrl: `${path}/order-details?orderID=${orderID}`,
                    requireOrderApproval: res.PendingApproval
                })
            }
            await UStoreProvider.state.store.loadCartItemsCount()
        })();
    }, []);

    const isLoading = !orderDetails.receiptUrl || !orderDetails.orderDetailsUrl

    return <Layout {...props} classname="thank-you">
        <div className={`ng-thankyou-page-wrapper ${isLoading ? 'loader-background' : ''}`}>
            {isLoading ? <LoadingDots/> : <>
                <div className="thankyou-icon">
                    <Icon name={'thankyou-image.svg'} width="100%x" height="100%"/>
                </div>
                <div className="thankyou-page-main-text">
                    {t("NGPages.ThankYou.Title")}
                </div>
                <div className="thankyou-page-sub-text">
                    {t("NGPages.ThankYou.SubText")}
                </div>
                {orderDetails.requireOrderApproval &&
                    <div className="approval-message">
                        <>{t("NGPages.ThankYou.ApprovalMessagePartOne")}<br/>{t("NGPages.ThankYou.ApprovalMessagePartTwo")}</>
                    </div>
                }
                <div className="order-number-block">
                    <div className="order-number-title">{`${t("NGPages.ThankYou.OrderNumber")}: `}<span
                        className="order-number">{orderDetails.orderNumber}</span></div>
                </div>
                <div className="link-block">
                    <a className="link view-order" href={orderDetails.orderDetailsUrl}>
                        {t("NGPages.ThankYou.ViewOrder")}
                    </a>
                    <div className="link">|</div>
                    <a className="link print-order"
                       href={isSafeUrl(orderDetails.receiptUrl) ? orderDetails.receiptUrl : '#'}
                       onClick={(e) => {
                           e.preventDefault()
                           if (isSafeUrl(orderDetails.receiptUrl)) {
                               window.open(
                                   orderDetails.receiptUrl,
                                   "printWindow",
                                   "width=800,height=600,resizable=yes,scrollbars=yes"
                               );
                           }
                       }}>
                        {t("NGPages.ThankYou.PrintOrder")}
                    </a>
                </div>
                <LinkAria to={urlGenerator.get({page: 'home'})}>
                    <div
                        className="button button-primary truncate action-button">{t("NGPages.ThankYou.BackToHome")}</div>
                </LinkAria>
                <Slot name="order_completePage_bottom"/>
            </>}
        </div>
    </Layout>
}

export default ThankYou
