import React, {FC, ReactNode} from "react";
import {useNavigationActions, useOnHeight, UseOnHeightCallback} from "./tree/hooks";
import {__} from "./globals";
import {PopupWindowProps, ScreenNavigation, ScreenProps} from "./PopupWindow";
import {render} from "./helpers";
import classNames from "classnames";
import {EmulatedButton} from "./tree/EmulatedButton";
import Tippy from "@tippyjs/react/headless";
import {ShowMore} from "@re-dev/react-truncate";
import {Color, ColorWithCustomTint, resolveTint} from "./tree/Color";
import {colors} from "./tree/Colors";

export type PopupWindowHeaderProps = Omit<ScreenNavigation, 'screenId'> & {
    currentScreenId: number,
    icon?: ReactNode,
    title: ScreenProps['title'],
    description?: ScreenProps['description'],
    onHeight?: UseOnHeightCallback,
    popupId: string,
    onClose?: () => void,
    onBack?: (fromScreenId: number, toScreenId: number) => void,
    screensLength: number,
    backLabel?: string,
    backId?: number,
    showNavigationButtons?: boolean, // default is true,
    centeredContent?: ReactNode,
    color?: Color | ColorWithCustomTint,
} & Pick<PopupWindowProps, 'canGoBack'>

const stripHtmlTags = (text: string): string => {
    return text.replace(/<[^>]*>/g, ' ')
}

const getTextFromNode = (node: ReactNode): string => {
    if (node === null || node === undefined || typeof node === 'boolean') {
        return ''
    }

    if (typeof node === 'string') {
        return stripHtmlTags(node)
    }

    if (typeof node === 'number') {
        return String(node)
    }

    return React.Children.toArray(node).map((child) => {
        if (typeof child === 'string') {
            return stripHtmlTags(child)
        }

        if (typeof child === 'number') {
            return String(child)
        }

        if (React.isValidElement(child)) {
            return getTextFromNode(child.props.children)
        }

        return ''
    }).join(' ')
}

export const PopupWindowHeader: FC<PopupWindowHeaderProps> = ({
    popupId,
    title,
    icon,
    description,
    onHeight,
    onClose,
    onBack,
    screensLength,
    backLabel,
    backId,
    canGoBack,
    currentScreenId,
    setCurrentScreenId,
    showNavigationButtons = true,
    centeredContent,
    color,
}) => {
    const ref = useOnHeight(onHeight)
    const { next } = useNavigationActions(currentScreenId, setCurrentScreenId)
    const themeColor = color || colors.purple
    let showBackButton = showNavigationButtons

    if ((currentScreenId || 1) > 1 && typeof canGoBack === 'function') {
        const to = currentScreenId! - 1

        if (!canGoBack(to)) {
            showBackButton = false
        }
    }
    const renderedTitle = render(title)
    const resolvedDescription = typeof description === 'function' ? description() : description
    const normalizedDescription = getTextFromNode(resolvedDescription).replace(/\s+/g, ' ').trim()

    const selectedTab = 'config'

    return <header ref={ref} className="w-full flex flex-col gap-4 items-center --mb-3">
        <div className="w-full space-y-1 --bg-purple-tint-10 --bg-opacity-40 --border-px --border-purple-tint-10 --bg-gray-150 --bg-opacity-50 rounded-t-1 --mt-3 -mx-20-- --w-[calc(100%+56px)] --px-6 --px-2 --border-b-px border-gray-150">
            <div className="relative flex justify-between w-full mt-6">
                <div className={classNames('flex items-center gap-3 px-2 py-1 rounded-1 bg-gray-150 bg-opacity-50', {
                    'invisible pointer-events-none': !showBackButton,
                })}>
                    <button className={classNames('flex items-center gap-1 text-1x text-gray-350 transition-all ease active:scale-95', {
                        'invisible': !showBackButton,
                    })} disabled={!showBackButton} onClick={() => {
                        if (!showBackButton) return

                        if (currentScreenId === 1) {
                            onClose && onClose()
                        } else {
                            let targetScreenId: number

                            if (typeof backId === 'number') {
                                setCurrentScreenId(backId)
                                targetScreenId = backId
                            } else {
                                targetScreenId = currentScreenId! - 1
                                setCurrentScreenId(targetScreenId)
                                //targetScreenId = prev()
                            }

                            onBack && onBack(currentScreenId!, targetScreenId)
                        }
                    }}>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5}
                         stroke="currentColor" className="w-4 h-4">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18"/>
                    </svg>
                    <span className="text-1x">{backLabel || __('Back')}</span>
                </button>
                <Tippy
                    zIndex={10000000}
                    placement="bottom"
                    delay={[300, 0]}
                    render={(attrs) => (
                        <div
                            className="px-2 py-1 text-1x text-gray-100 bg-gray-900 rounded-1 shadow-lg"
                            {...attrs}
                        >
                            {__("Start over")}
                        </div>
                    )}
                >
                    <button className="transition-all ease active:scale-[.80]">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="min-w-4 min-h-4 max-w-4 max-h-4 text-gray-400" onClick={() => {
                            setCurrentScreenId(1)
                        }}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" />
                        </svg>
                    </button>
                </Tippy>
                </div>
                <div className="absolute left-1/2 translate-x-[-50%] text-4x font-black text-gray-200 tracking-[-0.3px]">
                    {centeredContent ?? 'Coupons+'}
                </div>
                <div className="relative w-7 h-7 overflow-visible">
                    <EmulatedButton onClick={onClose} className="absolute right-0 top-0 z-10">
                        <div className="group">
                            <div className="flex items-center justify-end gap-1 rounded-full bg-gray-200 bg-opacity-80 group-hover:bg-gray-150 group-hover:bg-opacity-90 active:scale-[.96] transition-all duration-200 ease-out w-7 h-7 group-hover:rounded-2 group-hover:pl-3 group-hover:w-auto overflow-hidden">
                                <span className="text-1x text-gray-400  whitespace-nowrap opacity-0 max-w-0 group-hover:opacity-100 group-hover:max-w-20 transition-all duration-200 ease-out overflow-hidden">
                                    {__('Cancel')}
                                </span>
                                <div className="flex items-center justify-center w-7 h-7 flex-shrink-0">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                         className="w-5 h-5 text-gray-400">
                                        <path fillRule="evenodd"
                                              d="M5.47 5.47a.75.75 0 0 1 1.06 0L12 10.94l5.47-5.47a.75.75 0 1 1 1.06 1.06L13.06 12l5.47 5.47a.75.75 0 1 1-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 0 1-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 0 1 0-1.06Z"
                                              clipRule="evenodd"/>
                                    </svg>
                                </div>
                            </div>
                        </div>
                    </EmulatedButton>
                </div>
            </div>
            <div className={"flex flex-col gap-6 --bg-gray-150 bg-opacity-50 rounded-2 --px-7 pb-5 pt-3 -mx-5-- "}>
                {(renderedTitle || resolvedDescription) &&
                    <div className="flex flex-col items-start space-y-2 text-start">
                        <div className="relative flex flex-row items-start gap-3 w-full">
                            {icon && <div
                                className={classNames(
                                    'relative z-10 flex items-center justify-center min-w-8 min-h-8 max-w-8 max-h-8 rounded-3 group-hover:rounded-full transition duration-300 hover:scale-[1.08] active:scale-[.98]',
                                    resolveTint(themeColor, 'popupwindow.icon.background', 'bg-purple-tint-90', 'background')
                                )}>
                                {icon}
                                {false &&
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                         className="min-w-5 min-h-5 max-w-5 max-h-5 text-purple-tint-10">
                                        <path fillRule="evenodd"
                                              d="M11.99 2.243a4.49 4.49 0 0 0-3.398 1.55 4.49 4.49 0 0 0-3.497 1.306 4.491 4.491 0 0 0-1.307 3.498 4.491 4.491 0 0 0-1.548 3.397c0 1.357.6 2.573 1.548 3.397a4.491 4.491 0 0 0 1.307 3.498 4.49 4.49 0 0 0 3.498 1.307 4.49 4.49 0 0 0 3.397 1.549 4.49 4.49 0 0 0 3.397-1.549 4.49 4.49 0 0 0 3.497-1.307 4.491 4.491 0 0 0 1.306-3.497 4.491 4.491 0 0 0 1.55-3.398c0-1.357-.601-2.573-1.549-3.397a4.491 4.491 0 0 0-1.307-3.498 4.49 4.49 0 0 0-3.498-1.307 4.49 4.49 0 0 0-3.396-1.549Zm3.53 7.28a.75.75 0 0 0-1.06-1.06l-6 6a.75.75 0 1 0 1.06 1.06l6-6Zm-5.78-.905a1.125 1.125 0 1 0 0 2.25 1.125 1.125 0 0 0 0-2.25Zm4.5 4.5a1.125 1.125 0 1 0 0 2.25 1.125 1.125 0 0 0 0-2.25Z"
                                              clipRule="evenodd"/>
                                    </svg>
                                }                            </div>
                            }
                            <h2 className={classNames('--max-w-100 text-5x leading-7 --text-gray-900', resolveTint(themeColor, 'popupwindow.title', 'text-purple-normal', 'get', 'text.dark.primary'))} style={{textWrap: 'auto'}}>
                                {renderedTitle}
                            </h2>
                        </div>
                        {description && (
                            normalizedDescription
                                ? <ShowMore
                                    lines={2}
                                    more={__('More')}
                                    less={__('Less')}
                                    className="--w-120 block text-1x text-gray-400 text-left leading-[20px]"
                                    anchorClass={classNames("ml-1 inline cursor-pointer font-medium", resolveTint(themeColor, 'popupwindow.link', 'text-purple-normal', 'get', 'text.dark.primary'))}
                                >
                                    {normalizedDescription}
                                </ShowMore>
                                : resolvedDescription
                                    ? <div className="--w-120 text-1x leading-5 text-gray-400 text-left leading-[20px]">
                                        {resolvedDescription}
                                    </div>
                                    : null
                        )}
                    </div>
                }
                {false && <div className="flex items-center justify-start gap-2">
                    {[{
                        id: 'config',
                        label: 'Configuration',
                    }, {
                        id: 'examples',
                        label: 'Examples',
                    },].map((tab) => (
                        <button
                            key={tab.id}
                            className={classNames('relative rounded-full px-2 h-6  border-transparent flex items-center text-smaller-1 font-medium after:block after:h-[2px] after:w-full after:absolute after:-bottom-4 after:-left-0', {
                                'bg-purple-tint-10 after:bg-purple-tint-60 text-purple-tint-80': selectedTab === tab.id,
                                'text-gray-400': selectedTab !== tab.id,
                            })}
                            onClick={() => setSelectedTab(tab.id)}
                        >
                            {tab.label}
                        </button>))}
                </div>
                }
            </div>
            {false && <div className="h-px   border-b-px border-gray-150 w-full"></div>}
        </div>
    </header>;
}
