import {type FC, useEffect, useRef, useState} from "react";
import {LogoDark} from "@/LogoDark.tsx";
import {__} from "@/Ulititlies.ts";
import {MorphingPopover, MorphingPopoverContent, MorphingPopoverTrigger} from "@/components/ui/morphing-popover.tsx";
import * as motion from 'motion/react-client';
import classNames from "classnames";
import {GlowEffect} from "../components/motion-primitives/glow-effect.tsx";
import {TextShimmer} from "../components/motion-primitives/text-shimmer.tsx";
import {activateLicense, deactivateLicense, loadLicenseData} from "@/licensing.ts";
import {useAtom} from "jotai";
import {
    hasLoadedLicenseAtom, isActivatingAtom, isDeactivatingAtom,
    licenseDataAtom,
    licenseErrorAtom,
    loadingActivationDataAtom
} from "@/store/licenseStore.ts";

export type LicenseProps = {
}

/**
 * This component handles the license functionality, but it's not enabled currently as server-side licensing is not deployed yet.
 * This is only for internal testing currently.
 */
export const License: FC<LicenseProps> = ({}) => {
    const [loadingActivationData, setLoadingActivationData] = useAtom(loadingActivationDataAtom);
    const [licenseData, setLicenseData] = useAtom(licenseDataAtom);
    const [hasLoaded, setHasLoaded] = useAtom(hasLoadedLicenseAtom);
    const [isActivating, setIsActivating] = useAtom(isActivatingAtom);
    const licenseKeyRef = useRef<string>(CouponsPlusWelcome.licenseKey || '')
    const [error, setError] = useAtom(licenseErrorAtom);
    const [isDeactivating, setIsDeactivating] = useAtom(isDeactivatingAtom);

    useEffect(() => {
        // Initialize license data from window object if not already set
        if (licenseData === undefined) {
            setLicenseData(CouponsPlusWelcome.licenseKey);
        }
    }, []);

    useEffect(() => {
        if (typeof licenseData === 'string' && licenseData.length > 0 && !hasLoaded) {
            setHasLoaded(true);
            setLoadingActivationData(true);
            // load the data
            const fetchData = async () => {
                try {
                    const data = await loadLicenseData()
                    setLicenseData(data);
                } catch (e) {
                    setError(e as Error);
                } finally {
                    setLoadingActivationData(false);
                }
            }
            fetchData();
        }

    }, [licenseData, hasLoaded, setLicenseData, setLoadingActivationData, setError, setHasLoaded])

    const handleActivate = () => {
        if (!licenseKeyRef.current) {
            return;
        }
        setIsActivating(true);
        setError(null);
        /**
         * Let's give it two seconds to make sure the transition looks smooth and to make the user feel like something is happening
         * we don't want it to be instant
         */
        setTimeout(async () => {
            // now can we make the call
            try {
                const response = await activateLicense(licenseKeyRef.current);
                setLicenseData(licenseKeyRef.current);
                console.log('response', response);
            } catch (e) {
                console.log('Error activating license:', e);
                setError(e as Error);
            } finally {
                setIsActivating(false);
            }
        }, 2 * 1000);
    };

    const handleDeactivate = () => {
        if (!licenseKeyRef.current) {
            return;
        }
        setIsDeactivating(true);
        setError(null);
        /**
         * Let's give it two seconds to make sure the transition looks smooth and to make the user feel like something is happening
         * we don't want it to be instant
         */
        setTimeout(async () => {
            // now can we make the call
            try {
                const response = await deactivateLicense();
                console.log('response', response);
                setLicenseData(undefined);
                licenseKeyRef.current = ''
                setHasLoaded(false)
            } catch (e) {
                console.log('Error deactivating license:', e);
                setError(e as Error);
            } finally {
                setIsDeactivating(false)
            }
        }, 100);
    };

    const showInput = !licenseData

    return <div className="space-y-3">
        <MorphingPopover open={isActivating || loadingActivationData} onOpenChange={(open) => !open && setIsActivating(false)}>
            <MorphingPopoverTrigger asChild>
                <motion.div
                    className={classNames('flex flex-col items-center gap-4 bg-gray-100/10 backdrop-blur-[4px] border-[1px] border-gray-150 rounded-1 px-6 py-3 w-90')}
                >
                    <motion.div layoutId="logo-section" className="flex items-center gap-2">
                        <LogoDark/>
                        <span
                            className="font-semibold text-smaller-2 uppercase inline-flex py-1 px-2 rounded-4 bg-gray-850 text-white mt-[2px]">{('PRO')}</span>
                    </motion.div>
                    {showInput && <>
                        <input
                            type="text"
                            onChange={(e) => {
                                licenseKeyRef.current = e.target.value
                            }}
                            onPointerDown={(e) => e.stopPropagation()}
                            onClick={(e) => e.stopPropagation()}
                            className="m-0 !px-4 py-0 w-full !h-10 flex items-center border-[1px] !border-gray-200 !rounded-3 !bg-gray-100/50 text-gray-800 placeholder:text-gray-350 active:!shadow-none focus:!shadow-none focus:!border-gray-350 focus:!ring-[2px] focus:!ring-offset-2 focus:!ring-gray-200"
                            placeholder={__('Enter your license key')}
                        />
                        <p className="text-smaller-1 text-gray-450 leading-3">{__('Do not share your license key. Improper use (abuse) of your license key might result in the suspension of your account.')}</p>
                        <button
                            onClick={handleActivate}
                            className="relative px-5 h-9 flex items-center justify-center gap-2 text-base bg-blue-normal text-blue-10 rounded-full hover:cursor-pointer hover:scale-[1.01] hover:bg-blue-90 active:scale-[.98] transition-all duration-200 m-0 w-full"
                        >
                            <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">
                                <path fillRule="evenodd"
                                      d="M12 3.75a6.715 6.715 0 0 0-3.722 1.118.75.75 0 1 1-.828-1.25 8.25 8.25 0 0 1 12.8 6.883c0 3.014-.574 5.897-1.62 8.543a.75.75 0 0 1-1.395-.551A21.69 21.69 0 0 0 18.75 10.5 6.75 6.75 0 0 0 12 3.75ZM6.157 5.739a.75.75 0 0 1 .21 1.04A6.715 6.715 0 0 0 5.25 10.5c0 1.613-.463 3.12-1.265 4.393a.75.75 0 0 1-1.27-.8A6.715 6.715 0 0 0 3.75 10.5c0-1.68.503-3.246 1.367-4.55a.75.75 0 0 1 1.04-.211ZM12 7.5a3 3 0 0 0-3 3c0 3.1-1.176 5.927-3.105 8.056a.75.75 0 1 1-1.112-1.008A10.459 10.459 0 0 0 7.5 10.5a4.5 4.5 0 1 1 9 0c0 .547-.022 1.09-.067 1.626a.75.75 0 0 1-1.495-.123c.041-.495.062-.996.062-1.503a3 3 0 0 0-3-3Zm0 2.25a.75.75 0 0 1 .75.75c0 3.908-1.424 7.485-3.781 10.238a.75.75 0 0 1-1.14-.975A14.19 14.19 0 0 0 11.25 10.5a.75.75 0 0 1 .75-.75Zm3.239 5.183a.75.75 0 0 1 .515.927 19.417 19.417 0 0 1-2.585 5.544.75.75 0 0 1-1.243-.84 17.915 17.915 0 0 0 2.386-5.116.75.75 0 0 1 .927-.515Z"
                                      clipRule="evenodd"/>
                            </svg>
                            <span>{__('Activate License')}</span>
                        </button>
                    </>}
                    {!showInput && !isDeactivating && licenseData && typeof licenseData !== 'string' && <div className="flex flex-col items-center gap-2 py-4">
                        <div className="flex flex-col items-center gap-2">
                            {licenseData.is_activated ?
                            <motion.svg
                                key="activated-icon"
                                xmlns="http://www.w3.org/2000/svg"
                                viewBox="0 0 24 24"
                                fill="currentColor"
                                className="min-w-12 min-h-12 max-w-12 max-h-12"
                                initial={{ scale: 0 }}
                                animate={{ scale: 1 }}
                                transition={{
                                    type: "spring",
                                    stiffness: 260,
                                    damping: 20,
                                    duration: 0.6,
                                    delay: 0.4
                                }}
                            >
                                <path fillRule="evenodd"
                                      d="M8.603 3.799A4.49 4.49 0 0 1 12 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 0 1 3.498 1.307 4.491 4.491 0 0 1 1.307 3.497A4.49 4.49 0 0 1 21.75 12a4.49 4.49 0 0 1-1.549 3.397 4.491 4.491 0 0 1-1.307 3.497 4.491 4.491 0 0 1-3.497 1.307A4.49 4.49 0 0 1 12 21.75a4.49 4.49 0 0 1-3.397-1.549 4.49 4.49 0 0 1-3.498-1.306 4.491 4.491 0 0 1-1.307-3.498A4.49 4.49 0 0 1 2.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 0 1 1.307-3.497 4.49 4.49 0 0 1 3.497-1.307Zm7.007 6.387a.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"/>
                            </motion.svg> : <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                          className="min-w-12 min-h-12 max-w-12 max-h-12">
                                <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-2.625 6c-.54 0-.828.419-.936.634a1.96 1.96 0 0 0-.189.866c0 .298.059.605.189.866.108.215.395.634.936.634.54 0 .828-.419.936-.634.13-.26.189-.568.189-.866 0-.298-.059-.605-.189-.866-.108-.215-.395-.634-.936-.634Zm4.314.634c.108-.215.395-.634.936-.634.54 0 .828.419.936.634.13.26.189.568.189.866 0 .298-.059.605-.189.866-.108.215-.395.634-.936.634-.54 0-.828-.419-.936-.634a1.96 1.96 0 0 1-.189-.866c0-.298.059-.605.189-.866Zm-4.34 7.964a.75.75 0 0 1-1.061-1.06 5.236 5.236 0 0 1 3.73-1.538 5.236 5.236 0 0 1 3.695 1.538.75.75 0 1 1-1.061 1.06 3.736 3.736 0 0 0-2.639-1.098 3.736 3.736 0 0 0-2.664 1.098Z"
                                      clipRule="evenodd"/>
                            </svg>}
                            <h2 className={classNames('m-0 text-2x font-semibold text-gray-800')}>
                                {licenseData.is_activated ? __('License Activated. Enjoy.') : __('License Inactive')}
                            </h2>
                        </div>
                        <div className="space-y-1">
                            <div
                                className="text-base font-semibold flex items-center rounded-2 py-2 px-3 bg-gray-150/80 text-gray-600 border-[1px] border-gray-150">
                                {licenseData.data.key}
                            </div>
                            <p className="text-smaller-2 text-gray-400 m-0">{__('License key')}</p>
                        </div>
                    </div>}
                </motion.div>
            </MorphingPopoverTrigger>

            <MorphingPopoverContent
                className="bg-gray-100/10 backdrop-blur-[4px] !border-[1px] !border-gray-150 !rounded-1 px-6 pt-2 pb-4 !shadow-none">
                <GlowEffect
                    colors={['#0894FF', '#C959DD', '#FF2E54', '#FF9004']}
                    mode='breathe'
                    blur='medium'
                    scale={1}
                    duration={2} className={'opacity-10'}
                >
                    <div className="flex flex-col items-center gap-3">
                        <motion.div layoutId="logo-section" className="flex items-center gap-2">
                            <LogoDark/>
                            <span
                                className="font-semibold text-smaller-2 uppercase inline-flex py-1 px-2 rounded-4 bg-gray-850 text-white mt-[2px]">{('PRO')}</span>
                        </motion.div>
                        <TextShimmer
                            className='text-base [--base-color:var(--color-gray-800)] [--base-gradient-color:var(--color-blue-20)]'
                            duration={3}
                            spread={4}
                        >
                            {licenseKeyRef.current && (
                                licenseKeyRef.current
                            )}
                        </TextShimmer>
                        {false && <div className="flex items-center gap-2 text-gray-600">
                            <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none"
                                 viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                        strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor"
                                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span className="text-sm">Activating...</span>
                        </div>}

                    </div>
                </GlowEffect>
            </MorphingPopoverContent>
        </MorphingPopover>
        {licenseData  && (typeof licenseData === 'string' ? !loadingActivationData : !isActivating) && <button className="w-90 h-9 flex items-center gap-2 justify-center bg-gray-350 text-gray-100 rounded-full   text-base font-medium hover:cursor-pointer active:scale-[.98] transition" onClick={handleDeactivate}>
            <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">
                <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
            </svg>
            {!isDeactivating? __('Deactivate site') : __('Deactivating site...')}
        </button>}
        {error && <div className="flex items-start gap-4 bg-gray-700/100 backdrop-blur-[8px] text-gray-100 w-90 rounded-1 px-5 py-4">
            <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 mt-[2px]">
                <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>
            <div className="flex flex-col gap-1 text-left">
                <h1 className="!text-3x m-0 text-gray-100">{__('Cannot process license!')}</h1>
                <p className="text-smaller-1 opacity-70 m-0">
                    {error.message}
                </p>
            </div>
        </div>}
    </div>
}
