'use client';

import { JSX, useEffect, useState } from 'react';

import { useTranslations } from 'next-intl';

import Modal from '@/components/Modal';
import { useCookieConsent } from '@/hooks/useCookieConsent';
import { cookieOptionsConfig, getAllCookies, getMandatoryCookies } from '@/utils/cookieHelpers';

import { CookieOption as CookieOptionType, CookieType } from '@/types/Cookies';

import CookieOption from './CookieOption';

export default function CookieModal(): JSX.Element | null {
  const { showModal, setShowModal, saveConsent } = useCookieConsent();
  const [isSettingsOpen, setIsSettingsOpen] = useState<boolean>(false);
  const [isActive, setIsActive] = useState<CookieType[]>([]);
  const t = useTranslations('cookies.modal');
  const tCategories = useTranslations('cookies.categories');

  const cookieLink: string = '/sutitajekoztato';

  useEffect(() => {
    setIsActive(getMandatoryCookies());
  }, []);

  const save = (keyList: CookieType[]): void => {
    saveConsent(keyList);
  };

  const handleActiveChange = (key: CookieType): void => {
    setIsActive((prev) =>
      prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key]
    );
  };

  const saveAll = (): void => {
    save(getAllCookies());
  };

  const saveSettings = (): void => {
    save(isActive);
  };

  const buttonClassName: string = 'py-4 text-mma-blue font-bold font-slab text-sm';

  const translationKeyMap: Record<CookieType, string> = {
    MANDATORY: 'mandatory',
    STATISTICS: 'statistics',
    MARKETING: 'marketing',
    FUNCTIONAL: 'functional',
  };

  const optionsForRender: CookieOptionType[] = cookieOptionsConfig.map((item) => ({
    ...item,
    title: tCategories(`${translationKeyMap[item.key]}.title`),
    description: tCategories(`${translationKeyMap[item.key]}.description`),
  }));

  if (!showModal) return null;

  return (
    <Modal
      className="flex flex-col gap-8 flex-1 overflow-y-auto"
      onClose={() => setShowModal(false)}
    >
      <div className="font-slab font-bold text-3xl text-mma-yellow">{t('title')}</div>

      <div className="flex flex-col gap-6 text-sm">
        <div>{t('description')}</div>
        <div>
          {t('learnMore')}{' '}
          <a href={cookieLink} className="font-bold text-accent hover:text-white transition-colors">
            {t('readNotice')}
          </a>
        </div>
      </div>

      {isSettingsOpen && (
        <div className="bg-white/10 p-8 -mx-8 flex flex-col gap-6">
          {optionsForRender.map((item) => (
            <CookieOption
              active={isActive.includes(item.key)}
              onActiveChange={() => handleActiveChange(item.key)}
              key={item.key}
              data={item}
            />
          ))}
        </div>
      )}

      <div className="w-full flex flex-col md:flex-row gap-4 md:gap-6">
        <button
          className={'flex-1 bg-mma-cyan ' + buttonClassName}
          onClick={() => (isSettingsOpen ? saveSettings() : setIsSettingsOpen(!isSettingsOpen))}
        >
          {isSettingsOpen ? t('saveSettings') : t('changeSettings')}
        </button>
        <button className={'flex-1 bg-mma-yellow ' + buttonClassName} onClick={() => saveAll()}>
          {t('acceptAll')}
        </button>
      </div>
    </Modal>
  );
}
