'use client';

import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';

import { useTranslations } from 'next-intl';

import { Search } from 'lucide-react';
import { createPortal } from 'react-dom';
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';

import type { HomepageCollectionTextFields } from '@/services/homeCollections';

import CreatorAvatar from '@/components/creators/CreatorAvatar';
import CreatorCard, { type CreatorCardData } from '@/components/creators/CreatorCard';
import SectionHeader from '@/components/home/components/SectionHeader';

import { useRouter } from '@/i18n/navigation';

import { InteractiveCreatorPickerItem } from './HomepageInteractiveCreatorPicker';

interface HomepageInteractiveCreatorPickerClientProps {
  creators: InteractiveCreatorPickerItem[];
  textFields?: HomepageCollectionTextFields | null;
}

const normalize = (value: string) =>
  value
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .trim();

const RECOMMENDED_AVATAR_COUNT = 3;

const HomepageInteractiveCreatorPickerClient: React.FC<
  HomepageInteractiveCreatorPickerClientProps
> = ({ creators, textFields }) => {
  const t = useTranslations('home.interactivePicker');
  const router = useRouter();

  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const lastSelectedIdRef = useRef<string | null>(null);
  const wrapperRef = useRef<HTMLDivElement | null>(null);
  const dropdownRef = useRef<HTMLDivElement | null>(null);
  const virtuosoRef = useRef<VirtuosoHandle | null>(null);
  const listboxId = useId();
  const [dropdownLayout, setDropdownLayout] = useState<{
    top: number;
    left: number;
    width: number;
    height: number;
  } | null>(null);
  const [recommendedCreators, setRecommendedCreators] = useState<InteractiveCreatorPickerItem[]>(
    []
  );
  const normalizedQuery = useMemo(() => normalize(query), [query]);
  const recommendedCardCreators = useMemo<CreatorCardData[]>(
    () =>
      recommendedCreators.map((creator) => ({
        alkotoAzonosito: creator.alkotoAzonosito,
        nev: creator.nev,
        szakma: creator.szakma,
        elhalalozasIdeje: null,
        profilkep: creator.profilkepKey ? { key: creator.profilkepKey } : null,
      })),
    [recommendedCreators]
  );
  const displayedCreators = useMemo(() => {
    if (normalizedQuery.length === 0) {
      return creators;
    }

    return creators.filter((creator) => {
      const name = normalize(creator.nev);
      const profession = normalize(creator.szakma);
      const identifier = normalize(creator.alkotoAzonosito);

      return (
        name.includes(normalizedQuery) ||
        profession.includes(normalizedQuery) ||
        identifier.includes(normalizedQuery)
      );
    });
  }, [creators, normalizedQuery]);

  useEffect(() => {
    if (!creators.length) {
      setRecommendedCreators([]);
      return;
    }

    const basePool = creators.some((creator) => creator.profilkepKey)
      ? creators.filter((creator) => Boolean(creator.profilkepKey))
      : creators;

    const shuffled = [...basePool];
    for (let i = shuffled.length - 1; i > 0; i -= 1) {
      const randomIndex = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[i]];
    }

    setRecommendedCreators(shuffled.slice(0, Math.min(RECOMMENDED_AVATAR_COUNT, shuffled.length)));
  }, [creators]);

  const updateDropdownLayout = useCallback(() => {
    const wrapperElement = wrapperRef.current;
    if (!wrapperElement) return;

    const rect = wrapperElement.getBoundingClientRect();
    const margin = 8;
    const viewportBottomSpace = window.innerHeight - rect.bottom - margin;

    setDropdownLayout({
      top: rect.bottom + margin,
      left: rect.left,
      width: rect.width,
      height: Math.max(220, Math.min(420, viewportBottomSpace)),
    });
  }, []);

  useEffect(() => {
    const handlePointerDown = (event: PointerEvent) => {
      const targetNode = event.target as Node;
      const insideWrapper = wrapperRef.current?.contains(targetNode);
      const insideDropdown = dropdownRef.current?.contains(targetNode);
      if (!insideWrapper && !insideDropdown) {
        setOpen(false);
      }
    };

    document.addEventListener('pointerdown', handlePointerDown);
    return () => {
      document.removeEventListener('pointerdown', handlePointerDown);
    };
  }, []);

  useEffect(() => {
    if (displayedCreators.length === 0) {
      setActiveIndex(-1);
      return;
    }
    setActiveIndex(0);
  }, [query, displayedCreators.length]);

  useEffect(() => {
    if (!open) return;

    updateDropdownLayout();
    window.addEventListener('resize', updateDropdownLayout);
    window.addEventListener('scroll', updateDropdownLayout, true);

    return () => {
      window.removeEventListener('resize', updateDropdownLayout);
      window.removeEventListener('scroll', updateDropdownLayout, true);
    };
  }, [open, updateDropdownLayout]);

  useEffect(() => {
    if (!open || activeIndex < 0 || !virtuosoRef.current) return;

    virtuosoRef.current.scrollToIndex({
      index: activeIndex,
      align: 'center',
      behavior: 'auto',
    });
  }, [open, activeIndex]);

  const handleSelect = (creator: InteractiveCreatorPickerItem) => {
    const targetId = creator.alkotoAzonosito;
    if (!targetId) return;
    if (targetId === lastSelectedIdRef.current) {
      setOpen(false);
      return;
    }

    lastSelectedIdRef.current = targetId;
    setOpen(false);
    setQuery('');
    router.push({
      pathname: '/alkoto/[id]/muveszeti-halo',
      params: { id: targetId },
    } as never);
  };

  const handleInputKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
    if (!open && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
      if (!displayedCreators.length) return;
      event.preventDefault();
      setOpen(true);
      return;
    }

    if (event.key === 'ArrowDown') {
      event.preventDefault();
      if (!displayedCreators.length) return;
      setActiveIndex((previous) => Math.min(previous + 1, displayedCreators.length - 1));
      return;
    }

    if (event.key === 'ArrowUp') {
      event.preventDefault();
      if (!displayedCreators.length) return;
      setActiveIndex((previous) => Math.max(previous - 1, 0));
      return;
    }

    if (event.key === 'Enter') {
      if (!open) return;
      event.preventDefault();
      if (activeIndex < 0 || activeIndex >= displayedCreators.length) return;
      handleSelect(displayedCreators[activeIndex]);
      return;
    }

    if (event.key === 'Escape') {
      setOpen(false);
    }
  };

  return (
    <section className="relative z-20 hidden w-full overflow-visible bg-[#0f172a] px-site py-14 text-white sm:py-16 lg:py-20 md:block">
      <div
        className="pointer-events-none absolute inset-0"
        style={{
          background:
            'radial-gradient(52% 74% at 8% 0%, rgba(34,211,238,0.18) 0%, rgba(34,211,238,0) 70%), radial-gradient(40% 62% at 94% 8%, rgba(223,207,111,0.16) 0%, rgba(223,207,111,0) 72%)',
        }}
      />
      <div className="pointer-events-none absolute inset-0 opacity-20 bg-[linear-gradient(90deg,rgba(255,255,255,0.08)_1px,transparent_1px),linear-gradient(0deg,rgba(255,255,255,0.08)_1px,transparent_1px)] bg-[size:48px_48px]" />
      <div
        className="pointer-events-none absolute inset-y-0 right-0 hidden w-[48%] md:block"
        style={{
          WebkitMaskImage:
            'linear-gradient(270deg, rgba(0,0,0,1) 0%, rgba(0,0,0,0.95) 64%, rgba(0,0,0,0) 100%)',
          WebkitMaskRepeat: 'no-repeat',
          WebkitMaskSize: '100% 100%',
          maskImage:
            'linear-gradient(270deg, rgba(0,0,0,1) 0%, rgba(0,0,0,0.95) 64%, rgba(0,0,0,0) 100%)',
          maskRepeat: 'no-repeat',
          maskSize: '100% 100%',
        }}
      >
        <div
          className="h-full w-full"
          style={
            {
              backgroundColor: 'rgba(255, 255, 255, 0.38)',
              WebkitMaskImage: "url('/assets/images/connections-removebg-preview.png')",
              WebkitMaskPosition: 'center right',
              WebkitMaskSize: 'cover',
              WebkitMaskRepeat: 'no-repeat',
              maskImage: "url('/assets/images/connections-removebg-preview.png')",
              maskPosition: 'center right',
              maskSize: 'cover',
              maskRepeat: 'no-repeat',
              maskMode: 'alpha',
            } as React.CSSProperties
          }
        />
      </div>

      <div className="relative z-10 mx-auto max-w-boxed space-y-16">
        <SectionHeader
          eyebrow={textFields?.blockLabel || ''}
          title={textFields?.blockTitle || ''}
          description={textFields?.blockSubtitle || ''}
          tone="dark"
          maxWidth
        />

        <div className="mx-auto flex w-full max-w-[560px] justify-center">
          <div ref={wrapperRef} className="relative w-full">
            <div className="group relative flex w-full items-center gap-3 overflow-hidden rounded-full border border-white/80 bg-white px-3 py-4 text-left shadow-[0_24px_60px_-34px_rgba(0,0,0,0.65)] transition hover:border-white sm:px-6 sm:py-4">
              <Search size={18} className="relative z-10 shrink-0 text-[#151720]/55" />
              <input
                type="text"
                value={query}
                onChange={(event) => {
                  setQuery(event.target.value);
                  setOpen(true);
                }}
                onFocus={() => setOpen(true)}
                onClick={() => setOpen(true)}
                onKeyDown={handleInputKeyDown}
                placeholder={t('selector.placeholder')}
                aria-label={t('selector.label')}
                role="combobox"
                aria-expanded={open}
                aria-haspopup="listbox"
                aria-controls={listboxId}
                aria-autocomplete="list"
                aria-activedescendant={
                  open && activeIndex >= 0 && activeIndex < displayedCreators.length
                    ? `${listboxId}-option-${activeIndex}`
                    : undefined
                }
                className="relative z-10 min-w-0 flex-1 bg-transparent text-sm font-semibold text-[#151720] outline-none placeholder:text-[#151720]/55 sm:text-base"
              />
            </div>
          </div>
        </div>

        {recommendedCardCreators.length > 0 && (
          <div className="mx-auto mt-5 flex w-full max-w-[860px] flex-wrap items-start justify-center gap-x-4 gap-y-4">
            {recommendedCardCreators.map((creator) => (
              <div
                key={`recommended-${creator.alkotoAzonosito}`}
                className="w-[128px] sm:w-[166px]"
              >
                <CreatorCard creator={creator} pathname="/alkoto/[id]/muveszeti-halo" tone="dark" />
              </div>
            ))}
          </div>
        )}
      </div>

      {open &&
        dropdownLayout &&
        createPortal(
          <div
            ref={dropdownRef}
            id={listboxId}
            role="listbox"
            style={{
              position: 'fixed',
              top: dropdownLayout.top,
              left: dropdownLayout.left,
              width: dropdownLayout.width,
            }}
            className="z-[4000] overflow-hidden rounded-3xl border border-white/20 bg-[#0b1220] p-1 text-white shadow-xl"
          >
            {displayedCreators.length === 0 ? (
              <div className="px-4 py-3 text-sm text-white/60">{t('selector.empty')}</div>
            ) : (
              <Virtuoso
                ref={virtuosoRef}
                style={{ height: dropdownLayout.height }}
                totalCount={displayedCreators.length}
                computeItemKey={(index) =>
                  displayedCreators[index]?.alkotoAzonosito || String(index)
                }
                itemContent={(index) => {
                  const creator = displayedCreators[index];
                  const isActive = index === activeIndex;

                  return (
                    <button
                      id={`${listboxId}-option-${index}`}
                      role="option"
                      aria-selected={isActive}
                      type="button"
                      onMouseDown={(event) => {
                        event.preventDefault();
                      }}
                      onClick={() => handleSelect(creator)}
                      className={`flex w-full items-center gap-3 px-3 py-2.5 text-left transition ${
                        isActive ? 'bg-white/10' : 'hover:bg-white/5'
                      }`}
                    >
                      <CreatorAvatar
                        imageKey={creator.profilkepKey}
                        name={creator.nev}
                        width={48}
                        height={48}
                        wrapperClassName="h-10 w-10 rounded-full"
                        imageClassName="rounded-full"
                      />
                      <span className="flex min-w-0 flex-col">
                        <span className="truncate font-semibold text-white">{creator.nev}</span>
                        {creator.szakma && (
                          <span className="truncate text-xs text-white/65">{creator.szakma}</span>
                        )}
                      </span>
                    </button>
                  );
                }}
              />
            )}
          </div>,
          document.body
        )}
    </section>
  );
};

export default HomepageInteractiveCreatorPickerClient;
