'use client';
import Link from 'next/link';
import { useRef, useState } from 'react';
import clsx from 'clsx';
import Icon from '@/components/Icon';
import { useClickOutside } from '@/hooks/useClickOutside';
import { links } from './constants';

const StatisticsSidebar = () => {
  const [activeMenuUrl, setActiveMenuUrl] = useState<string | null>(null);
  const wrapperRef = useRef<HTMLUListElement>(null);

  useClickOutside(wrapperRef, () => setActiveMenuUrl(null));

  return (
    <aside>
      <ul ref={wrapperRef}>
        {links.map((link) => {
          const isActive = activeMenuUrl === link.url;
          return (
            <li
              key={link.url}
              className={clsx(
                'py-[15px] px-4 flex items-center justify-between relative border-b border-light_gray last:border-0 transition-colors duration-300',
                {
                  'bg-white text-[navColor]': !isActive,
                  'bg-[#15223C] text-white': isActive,
                },
              )}
              role='button'
              onClick={() => setActiveMenuUrl((prev) => (prev === link.url ? null : link.url))}
            >
              <span className='text-16 leading-5'>{link.name}</span>
              <Icon
                src='images/icons/icon-chevron-right.svg'
                className={clsx('w-[12px] h-[6px] transition-transform duration-300', {
                  'rotate-0': !isActive,
                  'rotate-180': isActive,
                })}
              />

              {isActive && (
                <div className='absolute z-50 bg-white top-0 right-[calc(-100%-20px)] flex flex-col w-[300px] min-w-[300px]'>
                  {link.children?.map((child) => (
                    <Link
                      key={`${link.url}${child.url}`}
                      href={`${link.url}${child.url}`}
                      className='px-4 py-[15px] !text-[#011844] border-b border-l border-light_gray transition-colors duration-300 bg-white hover:bg-[#E3F6FE]'
                    >
                      <span className='text-16 leading-5 '>{child.name}</span>
                    </Link>
                  ))}
                </div>
              )}
            </li>
          );
        })}
      </ul>
    </aside>
  );
};

export default StatisticsSidebar;
