import React, { useEffect, useRef, useState } from 'react';

import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { useParams } from 'next/navigation';

import { FaChevronDown } from 'react-icons/fa';
import { PiListBullets, PiMapPinFill } from 'react-icons/pi';

import CategoryDropdown from '@/components/header/CategoryDropdown';
import { cn } from '@/lib/utils';
import { metaAttributes110 } from '@/utils/filterUtils';

import { Link, usePathname } from '@/i18n/navigation';

interface StickyCategoryHeaderProps {
  title: string;
  showMapToggle?: boolean;
  className?: string;
}

const StickyCategoryHeader: React.FC<StickyCategoryHeaderProps> = ({
  title,
  showMapToggle,
  className,
}) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isMapView, setIsMapView] = useState(false);
  const t = useTranslations('mapViewPage');
  const tCategory = useTranslations('categories');
  const tNavigation = useTranslations('navigation');
  const pathname = usePathname();

  const dropdownRef = useRef<HTMLDivElement | null>(null);

  const params = useParams();
  const category = (params?.category as string) || '';

  // Determine base path from current pathname
  const getBasePath = (): '/alkotok' | '/alkotasok' | '/videok' => {
    if (pathname.includes('/alkotasok') || pathname.includes('/creations')) return '/alkotasok';
    if (pathname.includes('/videok') || pathname.includes('/videos')) return '/videok';
    return '/alkotok'; // default for /alkotok or /creators
  };

  const basePath = getBasePath();
  const listViewHref = `/alkotasok${category ? `/${category}` : ''}`;
  const mapViewHref = `/terkep${category ? `/${category}` : ''}`;

  const categoryInfo = metaAttributes110.find((cat) => cat.prettyKey === category);
  const categoryName = categoryInfo ? tCategory(categoryInfo.labelKey) : undefined;

  useEffect(() => {
    setIsMapView(pathname.includes('/terkep'));
  }, [pathname]);

  // dropdown handlers --->
  const toggleDropdown = () => {
    setIsDropdownOpen((prev) => !prev);
  };

  const handleClickOutside = (event: MouseEvent) => {
    if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
      setIsDropdownOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  // <--- dropdown handlers
  const hasAllOption = !basePath.includes('alkotasok');

  return (
    <div className={`sticky top-[var(--header-h)] bg-white z-10 py-4 ${className}`}>
      <div className="flex justify-between items-center">
        <div className="flex items-center gap-2">
          <h1 className="hidden sm:block text-mma-blue text-md sm:text-xl uppercase font-bold">
            {title + ' /'}
          </h1>
          <div className="relative" ref={dropdownRef}>
            <button
              className="text-mma-blue/85 transition flex flex-row items-center gap-2 px-4 py-1.5 md:py-2 border border-mma-blue/25 hover:border-mma-blue/60 hover:text-mma-blue"
              onClick={toggleDropdown}
            >
              {hasAllOption && !categoryName ? (
                <>
                  <span className="font-roboto text-sm lg:text-base text-left uppercase tracking-wide font-medium">
                    {basePath.includes('videok')
                      ? tNavigation('categoryDropdown.allVideos')
                      : tNavigation('categoryDropdown.everyone')}
                  </span>
                  <FaChevronDown
                    className={cn(
                      'transition-transform duration-300 ease-in-out text-mma-blue/70',
                      isDropdownOpen ? 'rotate-180' : 'rotate-0'
                    )}
                  />
                </>
              ) : (
                <>
                  <Image
                    className="aspect-square"
                    src={`/assets/images/icons/light/${categoryInfo?.icon}`}
                    alt={categoryInfo ? tCategory(categoryInfo.labelKey) : 'kategória ikon'}
                    width={24}
                    height={24}
                  />
                  <span className="font-roboto text-sm lg:text-base text-left uppercase tracking-wide font-medium">
                    {categoryName}
                  </span>
                  <FaChevronDown
                    className={cn(
                      'transition-transform duration-300 ease-in-out text-mma-blue/70',
                      isDropdownOpen ? 'rotate-180' : 'rotate-0'
                    )}
                  />
                </>
              )}
            </button>

            {isDropdownOpen && (
              <CategoryDropdown
                basePath={basePath}
                hasAllOption={hasAllOption}
                // posRight // tbd
              />
            )}
          </div>
        </div>

        {showMapToggle && (
          <div className="hidden md:flex items-center gap-4">
            <Link
              className="text-mma-blue/85 transition flex flex-row items-center gap-2 px-4 py-1.5 md:py-2 border border-mma-blue/25 hover:border-mma-blue/60 hover:text-mma-blue"
              href={(isMapView ? listViewHref : mapViewHref) as never}
            >
              {isMapView ? <PiListBullets size={24} /> : <PiMapPinFill size={24} />}

              <span className="font-roboto text-sm lg:text-base text-left uppercase tracking-wide font-medium">
                {isMapView ? t('listView') : t('mapView')}
              </span>
            </Link>
          </div>
        )}
      </div>
    </div>
  );
};

export default StickyCategoryHeader;
