/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import React, { useMemo } from 'react';

import { useLocale, useTranslations } from 'next-intl';
import { usePathname } from 'next/navigation';

import { cn } from '@/lib/utils';

import { CreatorData } from '@/types/Creator';

import {
  CREATOR_PAGES_CONFIG,
  CreatorPageConfigItem,
  isCreatorPageVisible,
} from '@/config/creator-pages/creatorPagesConfig';
import { defaultLocale, isAppLocale } from '@/config/i18n';
import { Link } from '@/i18n/navigation';

interface CreatorMenuBarProps {
  creator: CreatorData;
}

const CreatorMenuBar: React.FC<CreatorMenuBarProps> = ({ creator }) => {
  const locale = useLocale();
  const resolvedLocale = isAppLocale(locale) ? locale : defaultLocale;
  const t = useTranslations('creatorPage.grid');

  const items = useMemo(
    () =>
      Object.values(CREATOR_PAGES_CONFIG).filter((item) =>
        isCreatorPageVisible(item, creator, resolvedLocale)
      ),
    [creator, resolvedLocale]
  );

  // Csoportok: ordering + szeparátorokhoz is használjuk
  const groupedConfig = useMemo(
    () => [
      {
        id: 'timeline',
        itemIds: ['alkotasok', 'eletut-esemenyek', 'alkotas-videok'],
      },
      {
        id: 'lexikon',
        itemIds: ['palyakep', 'dijak'], // excl motto
      },
      {
        id: 'connections',
        itemIds: ['lexikon', 'rola', 'mma-hirek'], // excl terkep
      },
    ],
    []
  );

  const groups = useMemo(() => {
    const byId = new Map(items.map((i) => [i.id, i] as const));
    return groupedConfig
      .map((g) => ({
        id: g.id,
        items: g.itemIds.map((id: any) => byId.get(id)).filter(Boolean) as CreatorPageConfigItem[],
      }))
      .filter((g) => g.items.length > 0);
  }, [items, groupedConfig]);

  const buildHref = (item: CreatorPageConfigItem) => ({
    pathname: item.route,
    params: {
      id: creator.alkotoAzonosito,
    },
  });

  const buildSelectionHref = () => ({
    pathname: CREATOR_PAGES_CONFIG.featuredCreations.route,
    params: {
      id: creator.alkotoAzonosito,
    },
  });

  const pathname = usePathname();
  const segments = useMemo(() => pathname.split('/').filter(Boolean), [pathname]);
  const getActiveSegment = (item: CreatorPageConfigItem) => {
    const route = locale === 'en' ? item.routeEn : item.route;
    const parts = route.split('/').filter(Boolean);
    return parts[parts.length - 1] || '';
  };

  const groupTheme: Record<
    string,
    {
      borderActive: string;
      accent: string;
      textInactive: string;
    }
  > = {
    timeline: {
      borderActive: 'border-mma-blue/60',
      accent: 'bg-mma-blue',
      textInactive: 'text-white/90 hover:text-white',
    },
    lexikon: {
      borderActive: 'border-mma-yellow/60',
      accent: 'bg-mma-yellow',
      textInactive: 'text-mma-blue hover:text-slate-900',
    },
    connections: {
      borderActive: 'border-mma-cyan/60',
      accent: 'bg-mma-cyan',
      textInactive: 'text-mma-blue hover:text-slate-900',
    },
  };

  const getItemLabel = (item: CreatorPageConfigItem) => {
    if (item.id === 'alkotasok' && typeof creator.contentCount === 'number') {
      return `${t(item.id)} (${creator.contentCount})`;
    }

    return t(item.id);
  };

  return (
    <nav className="sticky top-[calc(var(--header-h))] lg:top-[calc(var(--header-h)+2.75rem)] z-30 bg-white">
      <div className="flex items-end gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        {groups.map((group) => {
          const theme = groupTheme[group.id] ?? {
            borderActive: 'border-slate-900/30',
            accent: 'bg-slate-900',
            textInactive: 'text-white/90 hover:text-white',
          };

          return (
            <div key={group.id} className={cn('relative flex items-center py-1 gap-1')}>
              {group.items.map((item) => {
                // Stabilabb aktív logika: path szegmens egyezés
                // (pl. /hu/alkoto/123/dijak -> segments includes "dijak")
                const activeSegment = getActiveSegment(item);
                const isActive = Boolean(activeSegment && segments.includes(activeSegment));
                const href = isActive ? buildSelectionHref() : buildHref(item);

                return (
                  <Link
                    key={item.id}
                    href={href as never}
                    className={cn(
                      'group relative flex items-center whitespace-nowrap px-3 py-2',
                      'text-[11px] font-semibold uppercase tracking-[0.08em]',
                      'transition-[color,background]',
                      isActive
                        ? cn(
                            'text-mma-blue bg-white',
                            'z-10 border border-b-0 rounded-t-lg',
                            theme.borderActive
                          )
                        : cn('rounded-t-lg', theme.accent, theme.textInactive),
                      'hover:brightness-110'
                    )}
                  >
                    <span className="relative z-10">{getItemLabel(item)}</span>
                  </Link>
                );
              })}
            </div>
          );
        })}
      </div>
    </nav>
  );
};

export default CreatorMenuBar;
