import dynamic from 'next/dynamic';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useEffect, useState, useRef } from 'react';

import { useProductContext } from '@/contexts/ProductContext';
import odooApi from '@/core/api/odooApi';
import whatsappUrl from '@/core/utils/whatsappUrl';
import Navbar from '../elements/Navbar/Navbar';
import styles from './BasicLayout.module.css'; // Import modul CSS

const AnimationLayout = dynamic(() => import('./AnimationLayout'), {
  ssr: false,
});
const BasicFooter = dynamic(() => import('../elements/Footer/BasicFooter'), {
  ssr: false,
});

const BasicLayout = ({ children }) => {
  const [templateWA, setTemplateWA] = useState(null);
  const [payloadWA, setPayloadWa] = useState(null);
  const [urlPath, setUrlPath] = useState(null);
  const [highlight, setHighlight] = useState(false);
  const [buttonPosition, setButtonPosition] = useState(null);

  const router = useRouter();
  const buttonRef = useRef(null);

  const { product } = useProductContext();

  useEffect(() => {
    if (
      router.pathname === '/shop/product/[slug]' ||
      router.pathname === '/shop/product/variant/[slug]'
    ) {
      setPayloadWa({
        name: product?.name,
        manufacture: product?.manufacture.name,
        url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath,
      });
      setTemplateWA('product');

      setUrlPath(router.asPath);
    }
  }, [product, router]);

  useEffect(() => {
    const handleMouseOut = (event) => {
      const rect = buttonRef.current.getBoundingClientRect();
      console.log("rect",rect)
      if (event.clientY <= 0) {
        console.log("ini pindah")
        setHighlight(true);
      } else {
        setHighlight(false);
      }
    };

    window.addEventListener('mouseout', handleMouseOut);

    return () => {
      window.removeEventListener('mouseout', handleMouseOut);
    };
  }, []);

  const recordActivity = async (pathname) => {
    const ONLY_ON_PATH = false;
    const recordedPath = [];
    if (ONLY_ON_PATH && !recordedPath.includes(pathname)) return;

    const ip = await odooApi('GET', '/api/ip-address');
    const data = new URLSearchParams({
      page_title: document.title,
      url: window.location.href,
      ip,
    });

    fetch(`/api/user-activity?${data.toString()}`);
  };

  useEffect(() => {
    recordActivity(router.pathname);
  }, [router.pathname]);

  return (
    <>
      <Navbar />
      <AnimationLayout>
        {children}
        {highlight && buttonPosition && (
          <div
            className={styles['overlay-highlight']}
            style={{
              '--button-x': `${buttonPosition.x + buttonPosition.width / 2}px`,
              '--button-y': `${buttonPosition.y + buttonPosition.height / 2}px`,
              '--button-radius': `${Math.max(buttonPosition.width, buttonPosition.height) / 2}px`
            }}
            onAnimationEnd={() => setHighlight(false)}
          />
        )}
        <div className='fixed bottom-4 right-4 sm:bottom-14 sm:right-10 z-50'>
          <a
            href={whatsappUrl(templateWA, payloadWA, urlPath)}
            className='py-2 pl-3 pr-4 rounded-full bg-[#4FB84A] border border-green-300 flex items-center'
            rel='noopener noreferrer'
            target='_blank'
            ref={buttonRef}
          >
            <Image
              src='/images/socials/WHATSAPP.svg'
              alt='Whatsapp'
              className='block sm:hidden'
              width={36}
              height={36}
            />
            <Image
              src='/images/socials/WHATSAPP.svg'
              alt='Whatsapp'
              className='hidden sm:block'
              width={44}
              height={44}
            />
            <span className='text-white font-bold ml-1.5'>Whatsapp</span>
          </a>
        </div>
      </AnimationLayout>
      <BasicFooter />
    </>
  );
};

export default BasicLayout;