import React, {FC, useState} from "react";
import {__} from "../../globals";
import {useQuery} from "@tanstack/react-query";
import {FeaturedPreset, Preset} from "./FeaturedPreset";
import {EmulatedButton} from "../EmulatedButton";
import classNames from "classnames";
import {Quantum} from 'ldrs/react'
import 'ldrs/react/Quantum.css'
import {colors} from "../Colors";
import {motion, AnimatePresence} from "framer-motion";
import {Button} from "../cards/Button";
import {TreeDashboardSection} from "../TreeDashboardSections";
import {useIsMobile} from "../hooks";

export type GuidedPresetsProps = { onBack?: () => void }

export type PresetOption = {
    name: string;
    presets?: Preset[];  // Terminal node - has presets
    next?: PresetOptions; // Non-terminal node - leads to more options
}

export type PresetOptions = {
    name: string;
    options: PresetOption[];
}

export type PresetStep = {
    name: string;
    examples?: string[];
    next: PresetOptions;
}

type RootOptions = PresetStep[];

type SelectionPath = {
    options: PresetOptions;
    selectedIndex: number | null;
}

type OptionButtonProps = {
    name: string,
    isSelected: boolean,
    onClick: () => void,
    hasSelectedSiblings?: boolean
}

const OptionButton: FC<OptionButtonProps> = ({name, isSelected, onClick,  hasSelectedSiblings}) => {
    return (
        <EmulatedButton
            onClick={onClick}
            className={classNames('transition-all pb-0 border-b-[2px] border-b-transparent', {
                'border-b-gray-600--': isSelected
            })}
        >
            <span
                className={classNames('transition-all flex px-3 leading-7 font-medium text-1x rounded-full mb-2 border-b-px border-b-transparent ', {
                    'text-gray-750 bg-gray-650 bg-opacity-10': !isSelected,
                    'text-gray-500 hover:text-gray-750 bg-transparent': !isSelected && hasSelectedSiblings,
                    'bg-gray-800 text-gray-150 cp-option-selected': isSelected
                })}
            >
                {name}
            </span>
        </EmulatedButton>
    );
};

type OptionRowProps = {
    title: string;
    options: Array<{ name: string }>;
    selectedIndex: number | null;
    onSelect: (index: number) => void;
    ButtonComponent?: FC<OptionButtonProps>
}

const OptionRow: FC<OptionRowProps> = ({title, options, selectedIndex, onSelect, ButtonComponent}) => {
    return (
        <div className="flex flex-col items-center space-y-2">
            <h2 className="text-6x text-gray-750 font-medium">{title}</h2>
            <div className="flex flex-wrap items-center gap-1 justify-center --border-b-px --border-gray-200">
                {options.map((option, index) => (
                    <OptionButton
                        key={index}
                        name={option.name}
                        isSelected={selectedIndex === index}
                        hasSelectedSiblings={selectedIndex !== null}
                        onClick={() => onSelect(index)}
                    />
                ))}
            </div>
        </div>
    );
};

export const GuidedPresets: FC<GuidedPresetsProps> = ({onBack}) => {
    const [selectionPath, setSelectionPath] = useState<SelectionPath[]>([]);
    const [finalPresets, setFinalPresets] = useState<Preset[] | null>(null);
    const [selectedRootIndex, setSelectedRootIndex] = useState<number | null>(null);
    const isMobile = useIsMobile();

    const {data, isLoading, error} = useQuery<RootOptions>({
        queryKey: ['guided-presets'],
        queryFn: async () => {
            const url = (window as any).CouponsPlus.urls.rest.presets.steps;

            const res = await fetch(url, {
                headers: {
                    'X-WP-Nonce': (window as any).CouponsPlus.security.nonces.rest
                }
            });
            if (!res.ok) {
                throw new Error(`HTTP error! status: ${res.status}`);
            }

            // WordPress REST API returns JSON object, we need to convert it back to string
            return res.json();
        }
    })

    if (isLoading) {
        return <div className={'h-full flex items-center justify-center'}>
            <motion.div
                key="loading-spinner"
                initial={{scale: 2.4, opacity: 0}}
                animate={{scale: 1, opacity: 1}}
                exit={{scale: 0, opacity: 0}}
                transition={{
                    duration: 0.8,
                    ease: [0.175, 0.885, 0.32, 1.275],
                    type: "spring",
                    stiffness: 260,
                    damping: 20
                }}
            >
                <Quantum size={73} speed={1.6} color={colors.gray.get(50).source}/>
            </motion.div>
        </div>
    } else if (error) {
        return <div>{__('Error loading presets')}</div>
    }

    const handleRootSelection = (step: PresetStep, index: number) => {
        setSelectedRootIndex(index);
        setSelectionPath([{
            options: step.next,
            selectedIndex: null
        }]);
        setFinalPresets(null);
    };

    const handleOptionSelection = (rowIndex: number, optionIndex: number, option: PresetOption) => {
        // Update selection for this row
        const newPath = selectionPath.slice(0, rowIndex + 1);
        newPath[rowIndex] = {
            ...newPath[rowIndex],
            selectedIndex: optionIndex
        };

        // Check if this option has presets (terminal) or next options
        if (option.presets) {
            setFinalPresets(option.presets);
            setSelectionPath(newPath);
        } else if (option.next) {
            newPath.push({
                options: option.next,
                selectedIndex: null
            });
            setFinalPresets(null);
            setSelectionPath(newPath);
        }
    };

    const hasNotSelectedAnPath = (typeof selectedRootIndex !== 'number' || !selectionPath.length)

    return <div className="relative --max-w-[720px] h-full --py-20 overflow-y-auto overflow-x-visible">
        {false && hasNotSelectedAnPath && <div className="grid grid-cols-2 gap-2 min-h-40">
            <FeaturedPreset preset={{
                id: 'preset-1',
                name: 'Buy One, Get One FREE (Specific Product) (Buy X, Get X)',
                description: 'Buy one specific product and get another of the same type for free.',
                example: 'Buy one T-shirt, get another T-shirt free',
                source: '{"version":1,"grove":[{"testable":{"type":"AND","mode":"filter","children":[{"type":"context","mode":"filter","children":[{"parentType":"filters","type":"Products","options":{"mode":"short","ids":[],"inclusionType":"allowed"},"testableType":"filter"},{"parentType":"filters","type":"NumberOfItems","options":{"quantity":{"type":"equals","amount":1,"range":{"minimum":1,"maxmimum":2}}},"testableType":"filter"}]}]},"branch":{"type":"offers","children":[{"parentType":"offers","type":"BuyXGetX","options":{"quantity":1,"discount":{"type":"free","amount":0}}}]}}]}'
            }}/>
            <FeaturedPreset preset={{
                id: 'preset-2',
                name: 'Buy Product A, Get Product B FREE (Buy X, Get Y)',
                description: 'Buy one specific product and get a different specific product for free.',
                example: 'Buy one Hoddie, get one T-shirt free',
                source: '{"version":1,"grove":[{"testable":{"type":"AND","mode":"filter","children":[{"type":"context","mode":"filter","children":[{"parentType":"filters","type":"Products","options":{"mode":"short","ids":[],"inclusionType":"allowed"},"testableType":"filter"},{"parentType":"filters","type":"NumberOfItems","options":{"quantity":{"type":"equals","amount":1,"range":{"minimum":1,"maxmimum":2}}},"testableType":"filter"}]}]},"branch":{"type":"offers","children":[{"parentType":"offers","type":"BuyXGetY","options":{"mode":"products","data":[],"whenNotInCart":{"actions":[],"notification":{"message":"You\'ve unlocked an exclusive offer!","button":{"text":"Select Reward","url":{"type":"smart","value":""}}}}}}]}}]}'
            }}/>
        </div>}
        <div className={classNames("flex flex-col items-center space-y-10 py-10 overflow-x-visible", {
            "px-2": isMobile,
            "px-8": !isMobile,
        })}>
            {/* Root row - "What kind of Deal?" */}
            {data && (
                <motion.div
                    key="first-row"
                    initial={{opacity: 0.5, scale: 0.96, y: -8}}
                    animate={{opacity: 1, scale: 1, y: 0}}
                    transition={{
                        duration: 0.20,
                        ease: [0.21, 1.02, 0.73, 1]
                    }}
                    className="space-y-6"
                >
                    <div className="relative">
                        <div className="absolute left-0 top-1">
                            {onBack && <Button onClick={onBack} preset={'gray'} size={'small'}>
                                <div className={'flex items-center gap-1'}>
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                         className="min-w-4 min-h-4 max-w-4 max-h-4">
                                        <path fillRule="evenodd"
                                              d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-4.28 9.22a.75.75 0 0 0 0 1.06l3 3a.75.75 0 1 0 1.06-1.06l-1.72-1.72h5.69a.75.75 0 0 0 0-1.5h-5.69l1.72-1.72a.75.75 0 0 0-1.06-1.06l-3 3Z"
                                              clipRule="evenodd"/>
                                    </svg>
                                    <span>{__('Back')}</span>
                                </div>
                            </Button>}
                        </div>
                        <h2 className="text-7x text-gray-750 font-medium text-center">What kind of Deal?</h2>
                    </div>
                    {false && <OptionRow
                        title={__('What kind of Deal?')}
                        options={data}
                        selectedIndex={selectedRootIndex}
                        onSelect={(index) => handleRootSelection(data[index], index)}
                    />}
                    <div className={classNames("gap-3 items-stretch", {
                        "grid grid-cols-2": isMobile,
                        "flex flex-row gap-2": !isMobile,
                    })}>
                        {data.map((option, index) => (
                            <EmulatedButton onClick={() => handleRootSelection(option, index)} key={index}
                                            className={classNames('relative w-full text-left rounded-1 flex flex-col justify-between gap-y-2 z-[100000] group hover:bg-opacity-40 transition-all hover:scale-[1.02] active:scale-[0.98]', {
                                                'bg-gray-750 bg-opacity-[0.60] border-gray-400 border-px ring-[2px] ring-gray-100 ring-opacity-60 ring-offset-1 hover:bg-opacity-40 text-gray-100': true,
                                                'opacity-20 hover:!opacity-60 hover:!bg-opacity-80': selectedRootIndex !== null && selectedRootIndex !== index,
                                                'p-3': isMobile,
                                                'p-4 --h-[98%]': !isMobile,
                                            })}
                                            style={{
                                                /*
                                                            background: 'linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0.1) 55%, rgba(0,0,0,0) 100%)',
                                                */
                                                backdropFilter: 'blur(1px)',
                                            }}>
                                <div className="space-y-3 h-full flex flex-col justify-between">
                                    <div className="space-y-4">
                                        <div className="flex items-center space-x-2">
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
                                                 fill="currentColor"
                                                 className="min-w-7 min-h-7 max-w-7 max-h-7">
                                                <path fillRule="evenodd"
                                                      d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-.53 14.03a.75.75 0 0 0 1.06 0l3-3a.75.75 0 1 0-1.06-1.06l-1.72 1.72V8.25a.75.75 0 0 0-1.5 0v5.69l-1.72-1.72a.75.75 0 0 0-1.06 1.06l3 3Z"
                                                      clipRule="evenodd"/>
                                            </svg>
                                            <span
                                                className={'-translate-x-1/4 opacity-0 group-hover:translate-x-0 group-hover:opacity-100 transition-all transition-duration-150 '}>{__('Import')}</span>
                                        </div>
                                        <h1 className="text-3x text-current font-medium leading-5">
                                            {option.name}
                                        </h1></div>
                                    <div className="space-y-4">
                                        <div className="space-y-0">
                                            {option.examples && option.examples.map((example, exIndex) => (
                                                <p key={exIndex} className="text-smaller-2 flex items-center gap-2 text-gray-100 text-opacity-70">
                                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="min-w-3 min-h-3 max-w-3 max-h-3">
                                                        <path d="M10.464 8.746c.227-.18.497-.311.786-.394v2.795a2.252 2.252 0 0 1-.786-.393c-.394-.313-.546-.681-.546-1.004 0-.323.152-.691.546-1.004ZM12.75 15.662v-2.824c.347.085.664.228.921.421.427.32.579.686.579.991 0 .305-.152.671-.579.991a2.534 2.534 0 0 1-.921.42Z" />
                                                        <path fillRule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25ZM12.75 6a.75.75 0 0 0-1.5 0v.816a3.836 3.836 0 0 0-1.72.756c-.712.566-1.112 1.35-1.112 2.178 0 .829.4 1.612 1.113 2.178.502.4 1.102.647 1.719.756v2.978a2.536 2.536 0 0 1-.921-.421l-.879-.66a.75.75 0 0 0-.9 1.2l.879.66c.533.4 1.169.645 1.821.75V18a.75.75 0 0 0 1.5 0v-.81a4.124 4.124 0 0 0 1.821-.749c.745-.559 1.179-1.344 1.179-2.191 0-.847-.434-1.632-1.179-2.191a4.122 4.122 0 0 0-1.821-.75V8.354c.29.082.559.213.786.393l.415.33a.75.75 0 0 0 .933-1.175l-.415-.33a3.836 3.836 0 0 0-1.719-.755V6Z" clipRule="evenodd" />
                                                    </svg>
                                                    <span className="leading-4">{example}</span>
                                                </p>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            </EmulatedButton>
                        ))}</div>
                </motion.div>
            )}

            <div className="space-y-4">
                {/* Progressive rows based on selections */}
                {selectionPath.map((pathItem, rowIndex) => (
                    <motion.div
                        key={rowIndex}
                        initial={{opacity: 0.5, scale: 0.96, y: -8}}
                        animate={{opacity: 1, scale: 1, y: 0}}
                        transition={{
                            duration: 0.20,
                            ease: [0.21, 1.02, 0.73, 1]
                        }}
                    >
                        <OptionRow
                            title={pathItem.options.name}
                            options={pathItem.options.options}
                            selectedIndex={pathItem.selectedIndex}
                            onSelect={(optionIndex) => handleOptionSelection(rowIndex, optionIndex, pathItem.options.options[optionIndex])}
                        />
                    </motion.div>
                ))}

                {/* Show final presets */}
                {finalPresets && (
                    <div className="flex flex-col items-center space-y-2 mt-4 self-stretch">
                        <h2 className="text-lg text-gray-800 font-medium">{__('Available Presets')}</h2>
                        <div className="flex flex-col gap-2 w-full">
                            <AnimatePresence mode="popLayout">
                                {finalPresets.map((preset, index) => (
                                    <motion.div
                                        key={`${preset.name}-${index}`}
                                        initial={{scale: 0.86, opacity: 0}}
                                        animate={{scale: 1, opacity: 1}}
                                        exit={{scale: 0.86, opacity: 0}}
                                        transition={{
                                            duration: 0.18,
                                            delay: index * 0.09,
                                            ease: [0.34, 1.56, 0.64, 1]
                                        }}
                                    >
                                        <FeaturedPreset preset={preset}/>
                                    </motion.div>
                                ))}
                            </AnimatePresence>
                        </div>
                    </div>
                )}</div>
        </div>
    </div>;
}
