import React, {FC} from "react";
import {__, CouponsPlus, hasProInstalled} from "../../globals";
import {EmulatedButton} from "../EmulatedButton";
import {AppImporter} from "../export/AppImporter";
import {GroveActions} from "../GroveActions";
import {useNodesStore} from "../store";
import {TreeNodeFactory} from "../TreeNodeFactory";
import {Offers} from "../Offers";
import {useSetAtom} from "jotai";
import {CurrentDashboardSectionIdAtom} from "../atoms";
import {TreeDashboardSection} from "../TreeDashboardSections";
import classNames from "classnames";
import {ProBadge} from "../../ProBadge";
import {useQuery} from "@tanstack/react-query";
import {Superballs} from 'ldrs/react'

import 'ldrs/react/Superballs.css'
import toast from "react-hot-toast";

export type Preset = {
    id: string
    name: string
    description: string
    example: string,
    isPro?: boolean,
    source?: string
};
export type FeaturedPresetProps = {
    preset: Preset,
    style?: 'light' | 'dark-light'
}

export const FeaturedPreset: FC<FeaturedPresetProps> = ({preset, style = 'dark-light'}) => {
    const importFromSource = useNodesStore(store => store.importFromSource)
    const setSection = useSetAtom(CurrentDashboardSectionIdAtom);
    const reset = CouponsPlus.implementations.engine.trees === false
    const [imported, setImported] = React.useState(false);
    const {data, error, isLoading, refetch} = useQuery<Preset['source']>({
        queryKey: ['import-preset', preset.id],
        queryFn: async () => {
            const url = `${(window as any).CouponsPlus.urls.rest.presets.byId}${preset.id}`;
            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
            const jsonData = await res.json();
            const source = JSON.stringify(jsonData);
            
            // Verify it's valid JSON (it should be since we just stringified it)
            try {
                JSON.parse(source);
            } catch (e) {
                throw new Error('Invalid JSON response');
            }

            importFromSource(source, reset, () => {
                // switch to the main offers section
                setSection(TreeDashboardSection.Offers)
            })

            return source;
        },
        enabled: false,
        retry: false,
        gcTime: 0, // Don't cache the result
    });

    React.useEffect(() => {
        if (error) {
            toast.custom((t) => (
                <div className={`relative bg-gray-550 text-white flex items-center gap-3 rounded-2 px-4 py-2 z-[10000000] min-w-35 transition-all duration-300 ease-in-out transform ${
                    t.visible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-95'
                }`}>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="min-w-6 min-h-6 max-w-6 max-h-6">
                        <path fillRule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z" clipRule="evenodd" />
                    </svg>
                    <span>{__('Error loading preset. Please try again.')}</span>
                </div>
            ), {
                id: 'preset-error-' + preset.id,
                duration: 3000,
                position: 'bottom-center'
            })
        }
    }, [error, preset.id]);

    return <EmulatedButton onClick={ () => {
                                if (preset.isPro && !hasProInstalled) {
                                    toast.custom((t) => (
                                        <div className={`relative bg-gray-550 text-white flex items-center gap-3 rounded-2 px-4 py-2 z-[10000000] min-w-35 transition-all duration-300 ease-in-out transform ${
                                            t.visible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-95'
                                        }`}>
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="min-w-6 min-h-6 max-w-6 max-h-6">
                                                <path fillRule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z" clipRule="evenodd" />
                                            </svg>
                                            <span>{__('This preset has features only available on Coupons+ Pro')}</span>
                                        </div>
                                    ), {
                                        id: 'preset-error-' + preset.id,
                                        duration: 3000,
                                        position: 'bottom-center'
                                    })
                                    return
                                }
                                refetch()
                           }}
                           className={classNames('relative w-full text-left rounded-1 flex flex-col justify-between gap-y-2   z-[100000] --h-[98%] p-4  group hover:bg-opacity-40 transition-all hover:scale-[1.02] active:scale-[0.98] overflow-hidden', {
                               'bg-gray-750 bg-opacity-[0.60] border-gray-400 border-px ring-[2px] ring-gray-100 ring-opacity-30 ring-offset-0 hover:bg-opacity-40 text-gray-100': style === 'dark-light',
                               'bg-gray-150 text-gray-700': style === 'light',
                           })}
                           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(30px)',
                           }}>
        {isLoading && <div
            className="absolute z-1000 w-full h-full top-0 left-0 flex items-center justify-center pointer-events-none bg-gray-400">
            <Superballs size="22"
                        speed="1.20"
                        color="white"/>
        </div>}
        <div className="space-y-3">
            <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 group-hover:flex">
                    <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 9a.75.75 0 0 0-1.5 0v2.25H9a.75.75 0 0 0 0 1.5h2.25V15a.75.75 0 0 0 1.5 0v-2.25H15a.75.75 0 0 0 0-1.5h-2.25V9Z"
                          clipRule="evenodd"/>
                </svg>
                {preset.isPro && !hasProInstalled && <ProBadge /> }
                <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>
            <div>
                <h1 className="text-4x text-current font-medium">
                    {preset.name}
                </h1>
                <p className="text-base opacity-90">{preset.description}</p>
            </div>
        </div>
        <div className="mt-2">
            <p className="text-smaller-3 opacity-60">{__('Example')}</p>
            <p className="text-smaller-1  opacity-60">{preset.example}</p>
        </div>
    </EmulatedButton>;
}