import React, {FC, useEffect, useRef, useState} from "react";
import {useAtomValue} from "jotai/index";
import {FloatingHeaderHeightAtom, sidebarEdgeOffsetAtom} from "./atoms";
import AutosizeInput from 'react-input-autosize';
import {useCopyToClipboard} from 'react-use';
import toast from 'react-hot-toast';
import {motion} from 'motion/react';
import {__, CouponsPlus} from "../globals";
import classNames from "classnames";
import {nanoid} from "nanoid";
import {useIsMobile} from "./hooks";

export type TreeHeaderProps = {
}

export const TreeHeader: FC<TreeHeaderProps> = ({}) => {
    const edgeOffset = useAtomValue(sidebarEdgeOffsetAtom)
    const [inputValue, setInputValue] = useState((CouponsPlus.state as any).code || '')
    const [, copyToClipboard] = useCopyToClipboard()
    const [isFocused, setIsFocused] = useState(false)
    const height = useAtomValue(FloatingHeaderHeightAtom)
    const inputRef = useRef<HTMLInputElement>(null);
    const isMobile = useIsMobile()

    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.custom(() => (
                <motion.div
                    initial={{ opacity: 0, y: -50, scale: 0.95 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={{ opacity: 0, y: -20, scale: 0.95 }}
                    transition={{
                        type: "spring",
                        stiffness: 500,
                        damping: 30,
                        mass: 1
                    }}
                    className="relative bg-gray-450 text-white flex items-center gap-3 rounded-2 px-4 py-2 z-[10000000] min-w-35"
                >
                    <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 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z" clipRule="evenodd" />
                    </svg>
                    <span>{__('Copied to clipboard!')}</span>
                </motion.div>
            ), {
                duration: 3000,
            })
        }
    }

    // Hide on mobile - the mobile view is handled in TreeSidebarRight
    if (isMobile) {
        return null
    }



    return <div className="absolute z-[1000000000]  left-1/2 translate-x-[-50%]" style={{
        top: edgeOffset,
        height
    }}>
        <div className={classNames("bg-gray-200 bg-opacity-30 hover:bg-gray-150 hover:bg-opacity-40  h-full px-2 flex items-center gap-2 rounded-1 transition-all hover:scale-105", {
            'scale-100': !isFocused,
            '!scale-110  ring-[2px] !bg-gray-100 !bg-opacity-80 ring-gray-150 ring-opacity-50 ring-offset-2': isFocused
        })} style={{backdropFilter: 'blur(6px)',}} onClick={() => inputRef.current?.focus()}>
            <AutosizeInput
                ref={inputRef}
                className="pl-2"
                placeholder={isFocused? __('CODE.') : '5572-ABC'}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                inputStyle={{
                    backgroundColor: 'transparent',
                    border: 'none',
                    outline: 'none',
                    fontSize: '14px',
                    color: 'rgba(55, 65, 81, 0.8)',
                }}
                placeholderStyle={{
                    color: 'rgba(55, 65, 81, 0.4)',
                }}
                onFocus={() => setIsFocused(true)}
                onBlur={() => setIsFocused(false)}
            />
            <div className="flex items-center gap-2 rounded-2 bg-gray-200 bg-opacity-50 px-2 py-1">
                <button
                    onClick={handleGenerate}
                    className="text-gray-700 hover:text-gray-900 transition-colors cursor-pointer"
                >
                    <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="text-gray-700 hover:text-gray-900 transition-colors cursor-pointer"
                    disabled={!inputValue}
                    style={{
                        opacity: inputValue ? 1 : 0.3,
                    }}
                >
                    <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="M7.5 3.75H6A2.25 2.25 0 0 0 3.75 6v1.5M16.5 3.75H18A2.25 2.25 0 0 1 20.25 6v1.5m0 9V18A2.25 2.25 0 0 1 18 20.25h-1.5m-9 0H6A2.25 2.25 0 0 1 3.75 18v-1.5M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/>
                    </svg>
                </button>
            </div>
        </div>
    </div>;
}
