﻿'use client';

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

import { useTranslations } from 'next-intl';

import { Loader2 } from 'lucide-react';

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

import Section from '@/components/common/Section';
import CreatorCard from '@/components/creators/CreatorCard';
import CreatorCombobox from '@/components/creators/CreatorCombobox';
import SectionHeader from '@/components/home/components/SectionHeader';

import type { CreatorListData } from '@/types/Creator';

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

interface HomepageParallelPathsTeaserClientProps {
  creatorOptions: CreatorListData[];
  textFields?: HomepageCollectionTextFields | null;
}

const CREATION_CATEGORY_KEY = 'alkotas';
type CreatorSide = 'left' | 'right';

function CreatorSelect({
  value,
  options,
  disabledCreatorId,
  placeholder,
  ariaLabel,
  onChange,
  className,
}: {
  value: string | null;
  options: CreatorListData[];
  disabledCreatorId: string | null;
  placeholder: string;
  ariaLabel: string;
  onChange: (id: string) => void;
  className?: string;
}) {
  return (
    <CreatorCombobox
      options={options}
      value={value}
      variant="inline"
      placeholder={placeholder}
      ariaLabel={ariaLabel}
      emptyLabel={placeholder}
      onSelect={(item) => onChange(item.alkotoAzonosito)}
      disabledCreatorId={disabledCreatorId}
      className={className}
    />
  );
}

function CreatorCardPanel({
  creator,
  placeholder,
  selectAriaLabel,
  options,
  selectedId,
  disabledCreatorId,
  onSelect,
}: {
  creator: CreatorListData | null;
  placeholder: string;
  selectAriaLabel: string;
  options: CreatorListData[];
  selectedId: string | null;
  disabledCreatorId: string | null;
  onSelect: (id: string) => void;
}) {
  return (
    <article className="w-full max-w-[340px]">
      <CreatorCard
        creator={creator}
        variant="selected"
        placeholder={placeholder}
        editorSlot={
          <CreatorSelect
            value={selectedId}
            options={options}
            disabledCreatorId={disabledCreatorId}
            placeholder={placeholder}
            ariaLabel={selectAriaLabel}
            onChange={onSelect}
          />
        }
      />
    </article>
  );
}

const HomepageParallelPathsTeaserClient = ({
  creatorOptions,
  textFields,
}: HomepageParallelPathsTeaserClientProps) => {
  const t = useTranslations('home.parallelPathsTeaser');
  const tParallelParams = useTranslations('parallelPathsPage.urlParams');
  const router = useRouter();
  const [isNavigating, startTransition] = useTransition();
  const [leftCreatorId, setLeftCreatorId] = useState<string | null>(null);
  const [rightCreatorId, setRightCreatorId] = useState<string | null>(null);
  const hasAutoRandomizedRef = useRef(false);

  const creatorsById = useMemo(() => {
    const map = new Map<string, CreatorListData>();
    creatorOptions.forEach((item) => map.set(item.alkotoAzonosito, item));
    return map;
  }, [creatorOptions]);

  const leftCreator = leftCreatorId ? creatorsById.get(leftCreatorId) || null : null;
  const rightCreator = rightCreatorId ? creatorsById.get(rightCreatorId) || null : null;

  const hasDuplicateSelection =
    Boolean(leftCreatorId) && Boolean(rightCreatorId) && leftCreatorId === rightCreatorId;
  const canNavigate =
    Boolean(leftCreatorId) && Boolean(rightCreatorId) && !hasDuplicateSelection && !isNavigating;

  const handleCreatorSelect = (side: CreatorSide, id: string) => {
    if (side === 'left') {
      setLeftCreatorId(id);
    } else {
      setRightCreatorId(id);
    }
  };

  const pickRandomPair = useCallback((): [string | null, string | null] => {
    if (creatorOptions.length < 2) {
      return [creatorOptions[0]?.alkotoAzonosito ?? null, null];
    }

    const firstIndex = Math.floor(Math.random() * creatorOptions.length);
    let secondIndex = Math.floor(Math.random() * creatorOptions.length);

    while (secondIndex === firstIndex) {
      secondIndex = Math.floor(Math.random() * creatorOptions.length);
    }

    return [
      creatorOptions[firstIndex]?.alkotoAzonosito ?? null,
      creatorOptions[secondIndex]?.alkotoAzonosito ?? null,
    ];
  }, [creatorOptions]);

  useEffect(() => {
    if (hasAutoRandomizedRef.current) return;
    hasAutoRandomizedRef.current = true;

    if (!creatorOptions.length) {
      setLeftCreatorId(null);
      setRightCreatorId(null);
      return;
    }

    const [nextLeft, nextRight] = pickRandomPair();
    setLeftCreatorId(nextLeft);
    setRightCreatorId(nextRight);
  }, [creatorOptions, pickRandomPair]);

  const navigateToParallelPaths = () => {
    if (!leftCreatorId || !rightCreatorId || hasDuplicateSelection) return;

    const leftParam = tParallelParams('left');
    const rightParam = tParallelParams('right');
    const categoryParam = tParallelParams('category');

    startTransition(() => {
      router.push({
        pathname: '/parhuzamos-eletutak',
        query: {
          [leftParam]: leftCreatorId,
          [rightParam]: rightCreatorId,
          [categoryParam]: CREATION_CATEGORY_KEY,
        },
      });
    });
  };

  return (
    <Section surface="white" clip>
      <SectionHeader
        eyebrow={textFields?.blockLabel || ''}
        eyebrowUrl="/parhuzamos-eletutak"
        title={textFields?.blockTitle || ''}
        description={textFields?.blockSubtitle || ''}
        maxWidth
      />

      <div className="py-4 sm:py-6">
        <div className="mx-auto grid max-w-5xl grid-cols-1 items-start gap-8 md:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] md:gap-8">
          <div className="flex justify-center md:justify-end">
            <CreatorCardPanel
              creator={leftCreator}
              placeholder={t('selector.placeholder')}
              selectAriaLabel={t('selector.leftLabel')}
              options={creatorOptions}
              selectedId={leftCreatorId}
              disabledCreatorId={rightCreatorId}
              onSelect={(id) => handleCreatorSelect('left', id)}
            />
          </div>

          <button
            type="button"
            onClick={navigateToParallelPaths}
            disabled={!canNavigate}
            className="order-last inline-flex h-11 w-full items-center justify-center gap-2 bg-[#151720] px-7 text-sm font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-[#0d1020] disabled:cursor-not-allowed disabled:bg-[#151720]/35 md:order-none md:mt-[6.75rem] md:w-auto md:whitespace-nowrap"
          >
            {isNavigating ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
            <span>{isNavigating ? t('states.loading') : t('cta')}</span>
          </button>

          <div className="flex justify-center md:justify-start">
            <CreatorCardPanel
              creator={rightCreator}
              placeholder={t('selector.placeholder')}
              selectAriaLabel={t('selector.rightLabel')}
              options={creatorOptions}
              selectedId={rightCreatorId}
              disabledCreatorId={leftCreatorId}
              onSelect={(id) => handleCreatorSelect('right', id)}
            />
          </div>
        </div>
      </div>
    </Section>
  );
};

export default HomepageParallelPathsTeaserClient;
