import React, {FC, useEffect, useRef, useState} from "react";
import {TreePreconditions} from "./TreePreconditions";
import {useAtom, useAtomValue, useSetAtom} from "jotai/index";
import {
    AddNewTreePopupWindowIsOpen,
    MobileOptionsPanelOpenAtom,
    rightSidebarWidthAtom,
    sidebarEdgeOffsetAtom
} from "./atoms";
import {useCopyToClipboard, useMeasure} from "react-use";
import {__, CouponsPlus} from "../globals";
import {Button} from "./cards/Button";
import {GroveExporter} from "./export/GroveExporter";
import {useNodesStore} from "./store";
import {ExportableDataFormatPreset} from "./export/AppImporter";
import {TreePredates} from "./TreePredates";
import {NewTreeButton} from "./NewTreeButton";
import {AppExporter} from "./export/AppExporter";
import {ExportImportTarget} from "./export/Exporters";
import {SaveButton} from "./SaveButton";
import {AutoApplyButton} from "./AutoApplyButton";
import {GoToStoreButton} from "./GoToStoreButton";
import toast from "react-hot-toast";
import {useIsMobile} from "./hooks";
import classNames from "classnames";
import {nanoid} from "nanoid";
import AutosizeInput from 'react-input-autosize';

export type TreeSidebarRightProps = {}

export const TreeSidebarRight: FC<TreeSidebarRightProps> = ({}) => {
    const [sidebarWidth, setSidebarWidth] = useAtom(rightSidebarWidthAtom)
    const edgeOffset = useAtomValue(sidebarEdgeOffsetAtom)
    const [ref, {width}] = useMeasure<HTMLDivElement>()
    const isMobile = useIsMobile()
    const [isOptionsPanelOpen, setIsOptionsPanelOpen] = useAtom(MobileOptionsPanelOpenAtom)
    const hasSelectedPreconditions = useNodesStore(({preconditionsID, testableRelations}) => {
        if (!preconditionsID) {
            return false
        }

        return (testableRelations.find(({id}) => id === preconditionsID)?.children?.length || 0) > 0
    })
    const hasSelectedPredates = useNodesStore(({predatesID, testableRelations}) => {
        if (!predatesID) {
            return false
        }

        return (testableRelations.find(({id}) => id === predatesID)?.children?.length || 0) > 0
    })
    const shouldRenderPredatesFirst = hasSelectedPredates && !hasSelectedPreconditions
    const preconditionAndPredateSections = shouldRenderPredatesFirst
        ? [<TreePredates key="predates"/>, <TreePreconditions key="preconditions"/>]
        : [<TreePreconditions key="preconditions"/>, <TreePredates key="predates"/>]
    const desktopPreconditionsPredatesMaxHeight = `calc(100vh - ${edgeOffset * 2 + (CouponsPlus.environment === 'development' ? 190 : 152)}px)`

    useEffect(() => {
        if (width !== sidebarWidth) {
            setSidebarWidth(width)
        }
    }, [width, setSidebarWidth])

    // Mobile: Top floating controls with coupon code
    if (isMobile) {
        return (
            <MobileTopBar
                isOptionsPanelOpen={isOptionsPanelOpen}
                setIsOptionsPanelOpen={setIsOptionsPanelOpen}
                shouldRenderPredatesFirst={shouldRenderPredatesFirst}
            />
        )
    }

    // Desktop: Original sidebar
    return <div ref={ref}
                className={'absolute z-[100000] flex flex-col gap-3 bg-transparent'}
                style={{
                    // dont set the width here or else it will never resize
                    top: edgeOffset,
                    right: edgeOffset,
                }}>
        <div className="relative">
            <div className="absolute left-0 top-0 translate-x-[calc(-100%-12px)] flex items-center min-w-[max-content] gap-2 ">
                {CouponsPlus.implementations.engine.trees && <NewTreeButton/>}
                <GoToStoreButton />
            </div>
            <div className="space-y-1">
                <SaveButton/>
                <AutoApplyButton />
            </div>
        </div>
        {CouponsPlus.environment === 'development' && <div className="grid gap-2" style={{gridTemplateColumns: '3fr 1fr'}}>
            <Button preset={'gray'} onClick={(e) => exportGroveToConsole('preset', e.metaKey)}>
                Export
            </Button>
            <Button preset={'gray'} onClick={(e) => exportGroveToConsole('server', e.metaKey)}>
                S
            </Button>
        </div>}
        {false && <p className="text-smaller-1 text-gray-400">Add an action to save</p>}
        <ScrollableSidebarGroups maxHeight={desktopPreconditionsPredatesMaxHeight} className="grid grid-cols-1 gap-4">
            {preconditionAndPredateSections}
        </ScrollableSidebarGroups>
    </div>;
};

function exportGroveToConsole(target: ExportImportTarget = 'preset', exportInPieces: boolean = false) {
    const state = useNodesStore.getState();
    const appExporter = new AppExporter(state, new GroveExporter(state))
    let exportedData = appExporter.export(target) as ExportableDataFormatPreset;

    console.log(`exported [${target}]:`)

    if (exportInPieces) {
        console.log('Exporting in pieces:')
        Object.keys(exportedData).forEach(key => {
            console.log(`${key}:`, JSON.stringify(exportedData[key as keyof typeof exportedData] || ''))
        })
    } else {
        const jsonString = JSON.stringify(exportedData);
        console.log(jsonString)
        console.log(exportedData)

        // Copy to clipboard
        navigator.clipboard.writeText(jsonString).then(() => {
            console.log('Copied to clipboard!')
            toast.success('Export copied to clipboard!')
        }).catch(err => {
            console.error('Failed to copy to clipboard:', err)
            toast.error('Failed to copy to clipboard')
        })
    }
}

// Mobile top bar component with all controls
type MobileTopBarProps = {
    isOptionsPanelOpen: boolean;
    setIsOptionsPanelOpen: (open: boolean) => void;
    shouldRenderPredatesFirst: boolean;
}

const MobileTopBar: FC<MobileTopBarProps> = ({isOptionsPanelOpen, setIsOptionsPanelOpen, shouldRenderPredatesFirst}) => {
    const [inputValue, setInputValue] = useState((CouponsPlus.state as any).code || '')
    const [, copyToClipboard] = useCopyToClipboard()
    const inputRef = useRef<HTMLInputElement>(null)
    const edgeOffset = useAtomValue(sidebarEdgeOffsetAtom)
    const openNewTreePopup = useSetAtom(AddNewTreePopupWindowIsOpen)
    const preconditionAndPredateSections = shouldRenderPredatesFirst
        ? [<TreePredates key="predates"/>, <TreePreconditions key="preconditions"/>]
        : [<TreePreconditions key="preconditions"/>, <TreePredates key="predates"/>]

    useEffect(() => {
        const wpInput = document.querySelector<HTMLInputElement>('input[name="post_title"]')
        if (wpInput) {
            wpInput.value = inputValue
        }
    }, [inputValue])

    const handleGenerate = () => {
        setInputValue(nanoid(8))
    }

    const handleCopy = () => {
        if (inputValue) {
            copyToClipboard(inputValue)
            toast.success(__('Copied!'))
        }
    }

    return (
        <>
            {/* Floating top controls - VisionOS-like dark blurred pills (mobile-only) */}
            <div
                className="absolute top-0 left-0 right-0 z-[100000] flex items-center justify-center px-3"
                style={{
                    paddingTop: edgeOffset + 8,
                }}
            >
                {/* Inner centered wrapper prevents overflow on narrow screens */}
                <div className="w-full" style={{width: 'calc(100% - 32px)', maxWidth: '980px'}}>
                    <div className="flex items-center justify-between gap-3 flex-nowrap overflow-x-auto" style={{WebkitOverflowScrolling: 'touch'}}>
                        {/* Left side - Coupon code pill (light bluish-gray blurred, no border) */}
                        <div
                            className="flex items-center gap-3 px-3 py-2 rounded-full flex-1 min-w-[64px] max-w-[30%]"
                            style={{
                                // Light bluish-gray frosted pill: translucent + blur, NO border or heavy shadow
                                background: 'rgba(235, 244, 250, 0.78)',
                                backdropFilter: 'saturate(120%) blur(14px)',
                                WebkitBackdropFilter: 'saturate(120%) blur(14px)',
                            }}
                        >
                            <AutosizeInput
                                ref={inputRef}
                                placeholder="CODE"
                                value={inputValue}
                                onChange={(e) => setInputValue(e.target.value)}
                                inputStyle={{
                                    backgroundColor: 'transparent',
                                    border: 'none',
                                    outline: 'none',
                                    fontSize: '13px',
                                    fontWeight: 600,
                                    letterSpacing: '0.02em',
                                    color: 'rgba(16, 40, 66, 0.95)',
                                    minWidth: '56px',
                                    maxWidth: '100px',
                                }}
                            />
                            <button onClick={handleGenerate} className="flex items-center justify-center w-8 h-8 rounded-full text-blue-600 hover:text-blue-700 transition-all cursor-pointer bg-transparent" aria-label="Generate code">
                                <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="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>
                            <button onClick={handleCopy} className="flex items-center justify-center w-8 h-8 rounded-full text-blue-600 hover:text-blue-700 transition-all cursor-pointer bg-transparent" disabled={!inputValue} aria-label="Copy code" style={{opacity: inputValue ? 1 : 0.45}}>
                                <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="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75"/>
                                </svg>
                            </button>
                        </div>

                        {/* Right side - Floating light bluish-gray pill controls (no borders/shadows) */}
                        <div
                            className="flex items-center gap-3 px-3 py-2 rounded-full flex-shrink-0"
                            style={{
                                background: 'rgba(235, 244, 250, 0.78)',
                                backdropFilter: 'saturate(120%) blur(14px)',
                                WebkitBackdropFilter: 'saturate(120%) blur(14px)',
                            }}
                        >
                            {/* New Tree + button */}
                            {CouponsPlus.implementations.engine.trees && <button
                                onClick={() => openNewTreePopup(true)}
                                className="flex items-center justify-center w-9 h-9 rounded-full text-blue-600 hover:text-blue-700 transition-all"
                                aria-label="Add new offer"
                                style={{background: 'transparent'}}
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
                                     className="w-5 h-5">
                                    <path
                                        d="M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z"/>
                                </svg>
                            </button>
                            }
                            {/* Options toggle button */}
                            <button
                                onClick={() => setIsOptionsPanelOpen(!isOptionsPanelOpen)}
                                className={classNames(
                                    "flex items-center justify-center w-9 h-9 rounded-full transition-all duration-200",
                                    {
                                        "bg-transparent text-blue-800": isOptionsPanelOpen,
                                        "text-blue-600 hover:text-blue-700": !isOptionsPanelOpen,
                                    }
                                )}
                                aria-label="Toggle options"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75" />
                                </svg>
                            </button>

                            {/* AutoApply button */}
                            <AutoApplyButton />
                        </div>

                        {/* Save button - separate floating pill (light bluish-gray blurred, no border/shadow) */}
                        <div
                            className="rounded-full overflow-hidden flex-shrink-0"
                            style={{
                                background: 'rgba(220, 235, 245, 0.9)',
                                backdropFilter: 'saturate(120%) blur(14px)',
                                WebkitBackdropFilter: 'saturate(120%) blur(14px)',
                                padding: '6px',
                                minWidth: '84px',
                                display: 'inline-flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}
                        >
                            <SaveButton compact />
                        </div>
                    </div>
                </div>
            </div>

            {/* Options panel */}
            {isOptionsPanelOpen && (
                <>
                    {/* Backdrop */}
                    <div
                        className="absolute inset-0 z-[99999]"
                        style={{
                            backgroundColor: 'rgba(0, 0, 0, 0.15)',
                            backdropFilter: 'blur(4px)',
                            WebkitBackdropFilter: 'blur(4px)'
                        }}
                        onClick={() => setIsOptionsPanelOpen(false)}
                    />
                    {/* Panel */}
                    <div
                        className="absolute top-14 right-3 left-3 z-[100001] rounded-3 overflow-hidden"
                        style={{
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            backdropFilter: 'blur(20px)',
                            WebkitBackdropFilter: 'blur(20px)',
                            boxShadow: '0 8px 40px rgba(0, 0, 0, 0.12)'
                        }}
                    >
                        <div className="flex items-center justify-between px-4 py-3 border-b border-black border-opacity-5">
                            <span className="text-gray-800 font-semibold text-1x">Options</span>
                            <button
                                onClick={() => setIsOptionsPanelOpen(false)}
                                className="flex items-center justify-center w-7 h-7 rounded-full bg-black bg-opacity-5 hover:bg-opacity-10"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor" className="w-3.5 h-3.5 text-gray-500">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="p-4">
                            <ScrollableSidebarGroups maxHeight={'calc(100vh - 220px)'} className="grid grid-cols-1 gap-3">
                                {preconditionAndPredateSections}
                            </ScrollableSidebarGroups>
                        </div>
                    </div>
                </>
            )}
        </>
    )
}

type ScrollableSidebarGroupsProps = {
    maxHeight: string;
    className?: string;
    children: React.ReactNode;
}

const ScrollableSidebarGroups: FC<ScrollableSidebarGroupsProps> = ({maxHeight, className, children}) => {
    const scrollableGroupsRef = useRef<HTMLDivElement>(null)
    const [showFade, setShowFade] = useState(false)

    const updateFadeVisibility = React.useCallback(() => {
        const container = scrollableGroupsRef.current
        if (!container) {
            return
        }

        const hasVerticalOverflow = container.scrollHeight > container.clientHeight + 1
        const hasMoreItemsBelow = container.scrollTop + container.clientHeight < container.scrollHeight - 1
        setShowFade(hasVerticalOverflow && hasMoreItemsBelow)
    }, [])

    useEffect(() => {
        updateFadeVisibility()
    }, [children, maxHeight, updateFadeVisibility])

    useEffect(() => {
        const container = scrollableGroupsRef.current
        if (!container) {
            return
        }

        updateFadeVisibility()
        container.addEventListener('scroll', updateFadeVisibility, {passive: true})
        window.addEventListener('resize', updateFadeVisibility)

        return () => {
            container.removeEventListener('scroll', updateFadeVisibility)
            window.removeEventListener('resize', updateFadeVisibility)
        }
    }, [updateFadeVisibility])

    return <div className="relative">
        <div ref={scrollableGroupsRef} className="overflow-y-auto overflow-x-hidden pb-8" style={{maxHeight}}>
            <div className={classNames('px-2', className)}>
                {children}
            </div>
        </div>
        {showFade && <div
            className="pointer-events-none absolute bottom-0 left-0 right-0 h-12"
            style={{
                background: 'linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0.95) 72%, rgba(255,255,255,1) 100%)',
            }}
        />}
    </div>
}
