'use client';

import * as React from 'react';
import clsx from 'clsx';
import { Transition } from '@headlessui/react';
import NextLink from 'next/link';
import { useRouter } from 'next/navigation';
import { WEBSITE_COOKIE_POLICY } from '@/constant/url';

import { create, reset } from '@/app/action';
import { updateGTMConsent } from '@/components/GTM';

export const GEO_API = 'https://get.geojs.io/v1/ip/geo.json';

export default function CookieModal(props: {
  cookiePolicyAccepted?: 'accepted' | 'rejectedAll' | 'unknown';
}) {
  const { cookiePolicyAccepted = 'unknown' } = props;

  const [show, setShow] = React.useState(false);
  const [accepted, setAccepted] = React.useState(
    cookiePolicyAccepted !== 'rejectedAll',
  );

  const router = useRouter();

  React.useEffect(() => {
    // show modal if cookie policy is not accepted and in the EU or UK
    const getCountry = async () => {
      const res = await fetch(GEO_API);
      const data = await res.json();
      setShow(
        ['EU', 'UK'].includes(data?.continent_code) &&
          cookiePolicyAccepted === 'unknown',
      );
    };
    getCountry();
  }, [cookiePolicyAccepted]);

  const handleAccept = async () => {
    setAccepted(true);
    await create({
      cookiePolicy: 'accepted',
    });
    setShow(false);
    updateGTMConsent('granted');
  };

  const handleRejectAll = async () => {
    setAccepted(false);
    await create({
      cookiePolicy: 'rejectedAll',
    });
    setShow(false);
    updateGTMConsent('denied');
  };

  const handleReset = async () => {
    await reset();
    setShow(true);
    updateGTMConsent('granted');
  };

  return (
    <>
      <div
        aria-live="assertive"
        className="pointer-events-none fixed inset-0 z-[5] flex items-end"
      >
        <div className="flex w-full flex-col items-center space-y-4 p-0 sm:items-end md:p-4">
          {/* Notification panel, dynamically insert this into the live region when it needs to be displayed */}
          <Transition
            show={show}
            as={React.Fragment}
          >
            <div
              className={clsx(
                'pointer-events-auto w-full bg-background text-white md:max-w-sm md:rounded-3xl',
                'transform ease-out duration-300 transition',
                'data-[closed]:translate-y-2 data-[closed]:opacity-0 data-[closed]:sm:translate-y-0 data-[closed]:sm:translate-x-2',
                'data-[leave]:ease-in data-[leave]:duration-100',
                'data-[leave]:data-[closed]:opacity-0'
              )}
            >
              <div
                className="border border-[#0CA6F21A] p-3 md:rounded-3xl"
                style={{
                  background:
                    'linear-gradient(90deg, rgba(19, 54, 125, 0.50) -1.46%, rgba(15, 49, 65, 0.50) 37.65%, rgba(0, 111, 93, 0.50) 100%)',
                }}
              >
                <div className="flex">
                  <div className="flex w-full flex-row gap-2 sm:flex-col sm:gap-0">
                    <p className="font-mono text-xs leading-tight text-darkgrey-400 sm:pr-2">
                      {cookiePolicy}
                      {` `}
                      <NextLink
                        href={WEBSITE_COOKIE_POLICY}
                        target="_blank"
                        className="text-action underline"
                      >
                        More
                      </NextLink>
                    </p>
                    <div className="dm:mt-4 flex items-center justify-end gap-4">
                      <button
                        type="button"
                        className="mx-1 inline-flex items-center justify-center text-xs text-darkgrey-500 hover:border-darkgrey-600 hover:text-darkgrey-300"
                        onClick={handleRejectAll}
                      >
                        Reject
                      </button>
                      <button
                        type="button"
                        className="inline-flex min-w-[80px] items-center justify-center whitespace-nowrap rounded-[1.5625rem] border border-[#173E43] bg-[#173E43] px-2 py-2 text-xs text-darkgrey-300 hover:opacity-90"
                        onClick={handleAccept}
                      >
                        Allow Cookies
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Transition>
        </div>
      </div>
    </>
  );
}

const cookiePolicy = `The website uses cookies to ensure the best experience.`;
