'use client';

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

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

import { ChevronsUpDown } from 'lucide-react';
import { IoHomeOutline } from 'react-icons/io5';
import { useMediaQuery } from 'react-responsive';

import type { ConnectionPerson } from '@/components/Interactive2DGraph';
import Breadcrumbs, { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import Modal from '@/components/common/Modal';
import CreatorAvatar from '@/components/creators/CreatorAvatar';
import { CREATOR_SEARCH_MIN_QUERY_LENGTH } from '@/components/creators/creatorSearchConfig';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { type CreatorSearchListItem, useCreatorSearch } from '@/hooks/useCreatorSearch';
import { getMetaAttribute110ByKey } from '@/utils/filterUtils';

import ConnectionsSectionClient from '@/app/[locale]/alkoto/[id]/(creator-layout)/[section]/(creator-page-sections)/(general-content)/ConnectionsSectionClient';
import { asHref } from '@/i18n/asHref';
import { Link, useRouter } from '@/i18n/navigation';

const INTRO_PROMPT_STORAGE_KEY = 'azopus.artNetwork.onboardingPrompt.seen';
const INTRO_PROMPT_DELAY_MS = 3000;
const INTRO_PROMPT_GIF = '/assets/onboarding/art-network-onboarding.mp4';

const MuveszetiHaloClient = ({
  connections,
  initialCreatorId,
  initialCreatorName,
  initialCreatorArtBranchEnum,
  initialCreatorArtBranchName,
}: {
  connections: ConnectionPerson[];
  initialCreatorId?: string;
  initialCreatorName?: string;
  initialCreatorArtBranchEnum?: string;
  initialCreatorArtBranchName?: string;
}) => {
  const t = useTranslations('connectionsGraph');
  const tParallel = useTranslations('parallelPathsPage');
  const tNav = useTranslations('navigation.menu');
  const locale = useLocale();
  const router = useRouter();
  const tSelector = useTranslations('connectionsGraph.originSelector');
  const entry = useMemo(() => {
    if (!initialCreatorId) return null;
    return {
      creatorId: initialCreatorId,
      creatorName: initialCreatorName || '',
    };
  }, [initialCreatorId, initialCreatorName]);
  const lastSelectedIdRef = useRef<string | null>(null);
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [showIntroPrompt, setShowIntroPrompt] = useState(false);
  const [showIntroModal, setShowIntroModal] = useState(false);
  const [hasMounted, setHasMounted] = useState(false);
  const isMobile = useMediaQuery({ maxWidth: 1023 });
  const { results, loading, isQueryTooShort } = useCreatorSearch<CreatorSearchListItem>({
    query,
    enabled: open,
    minQueryLength: CREATOR_SEARCH_MIN_QUERY_LENGTH,
  });

  useEffect(() => {
    // This page should always open from the top
    window.scrollTo(0, 0);
  }, [entry?.creatorId]);

  useEffect(() => {
    setHasMounted(true);
  }, []);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    if (!hasMounted || isMobile) return;
    const seen = window.sessionStorage.getItem(INTRO_PROMPT_STORAGE_KEY) === '1';
    if (seen) return;
    const timer = window.setTimeout(() => {
      setShowIntroPrompt(true);
    }, INTRO_PROMPT_DELAY_MS);

    return () => {
      window.clearTimeout(timer);
    };
  }, [hasMounted, isMobile]);

  const creatorName = entry?.creatorName?.trim() || t('unknownCreator');
  const artBranch = useMemo(() => {
    if (!initialCreatorArtBranchEnum && !initialCreatorArtBranchName) {
      return null;
    }
    const meta = initialCreatorArtBranchEnum
      ? getMetaAttribute110ByKey(initialCreatorArtBranchEnum)
      : null;
    const prettyKey = meta?.prettyKey;
    const label = initialCreatorArtBranchName || meta?.name || null;
    if (!prettyKey || !label) return null;
    return { prettyKey, label };
  }, [initialCreatorArtBranchEnum, initialCreatorArtBranchName]);
  const originSelector = (
    <Popover
      open={open}
      onOpenChange={(nextOpen) => {
        setOpen(nextOpen);
        if (!nextOpen) {
          setQuery('');
        }
      }}
    >
      <PopoverTrigger asChild>
        <button
          type="button"
          aria-expanded={open}
          aria-label={tSelector('label')}
          className="flex w-full min-w-0 max-w-full items-center gap-2 border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 shadow transition hover:bg-slate-100 sm:w-auto sm:min-w-[220px] sm:max-w-[280px]"
        >
          <span className="whitespace-nowrap text-[10px] font-semibold uppercase tracking-[0.12em] text-slate-400">
            {tSelector('label')}
          </span>
          <span className="min-w-0 flex-1 truncate text-mma-blue">
            {entry?.creatorName ? creatorName : tSelector('placeholder')}
          </span>
          <ChevronsUpDown size={16} className="ml-auto text-slate-400" />
        </button>
      </PopoverTrigger>
      <PopoverContent align="start" sideOffset={8} className="z-[1100] w-[min(92vw,280px)] p-0">
        <Command shouldFilter={false}>
          <CommandInput
            value={query}
            onValueChange={setQuery}
            placeholder={tSelector('placeholder')}
            aria-label={tSelector('label')}
          />
          <CommandList>
            {!isQueryTooShort && <CommandEmpty>{loading ? '...' : t('panel.empty')}</CommandEmpty>}
            <CommandGroup>
              {results.map((item) => {
                const label = item.nev || '';
                const subtitle = item.szakma || '';
                const targetId = item.alkotoAzonosito?.trim();
                return (
                  <CommandItem
                    key={`${item.alkotoAzonosito ?? label}`}
                    value={label}
                    onSelect={() => {
                      if (!targetId) return;
                      if (targetId === entry?.creatorId || targetId === lastSelectedIdRef.current) {
                        setOpen(false);
                        return;
                      }
                      lastSelectedIdRef.current = targetId;
                      setQuery('');
                      setOpen(false);
                      router.push({
                        pathname: '/alkoto/[id]/muveszeti-halo',
                        params: { id: targetId },
                      } as never);
                    }}
                    className="gap-3 px-3 py-2"
                  >
                    <CreatorAvatar
                      imageKey={item.profilkep?.key || null}
                      name={label}
                      width={40}
                      height={40}
                      wrapperClassName="h-9 w-9 rounded-full"
                      imageClassName="rounded-full"
                    />
                    <span className="flex flex-col">
                      <span className="font-semibold">{label}</span>
                      {subtitle && <span className="text-xs text-slate-500">{subtitle}</span>}
                    </span>
                  </CommandItem>
                );
              })}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );

  const markIntroSeen = () => {
    if (typeof window === 'undefined') return;
    window.sessionStorage.setItem(INTRO_PROMPT_STORAGE_KEY, '1');
  };

  const handleIntroInterested = () => {
    markIntroSeen();
    setShowIntroPrompt(false);
    setShowIntroModal(true);
  };

  const handleIntroNotInterested = () => {
    markIntroSeen();
    setShowIntroPrompt(false);
  };

  const breadcrumbs = useMemo(() => {
    const homeLabel = locale === 'en' ? 'Home' : 'Főoldal';
    const items: BreadcrumbItem[] = [
      {
        label: homeLabel,
        href: { pathname: '/' },
        icon: <IoHomeOutline />,
        ariaLabel: homeLabel,
      },
    ];

    if (entry?.creatorId) {
      items.push({
        label: tNav('creators'),
        href: { pathname: '/alkotok' },
      });
    }

    if (artBranch?.prettyKey && artBranch.label) {
      items.push({
        label: artBranch.label,
        href: asHref(`/alkotok/${artBranch.prettyKey}`),
        hideBelow: 'lg',
      });
    }

    if (entry?.creatorId && creatorName) {
      items.push({
        label: creatorName,
        href: {
          pathname: '/alkoto/[id]',
          params: { id: entry.creatorId },
        },
        hideBelow: 'lg',
      });
    }

    items.push({
      label: t('title'),
    });

    return items;
  }, [artBranch?.label, artBranch?.prettyKey, creatorName, entry?.creatorId, locale, t, tNav]);

  const introPromptCard = showIntroPrompt ? (
    <div className="w-full max-w-[420px] border border-slate-200 bg-white/95 px-5 py-4 text-left shadow-xl">
      <p className="text-base sm:text-lg font-semibold uppercase tracking-[0.06em] text-[#151720]">
        {t('onboardingPrompt.question')}
      </p>
      <div className="mt-4 flex flex-wrap justify-start gap-3">
        <button
          type="button"
          onClick={handleIntroInterested}
          className="border border-mma-blue bg-mma-blue px-5 py-2 text-[11px] font-semibold uppercase tracking-[0.28em] text-white transition hover:bg-mma-blue/90"
        >
          {t('onboardingPrompt.interested')}
        </button>
        <button
          type="button"
          onClick={handleIntroNotInterested}
          className="border border-slate-300 bg-white px-5 py-2 text-[11px] font-semibold uppercase tracking-[0.28em] text-slate-600 transition hover:border-slate-400 hover:text-slate-800"
        >
          {t('onboardingPrompt.notInterested')}
        </button>
      </div>
    </div>
  ) : null;

  if (!entry?.creatorId) {
    return (
      <section className="px-site py-12">
        <div className="mx-auto max-w-boxed">
          <div className="flex flex-col items-center gap-4 border border-slate-200 bg-white p-6 text-center shadow-sm">
            <div className="text-sm font-semibold text-slate-600">{tParallel('selectCreator')}</div>
            <Link
              href="/alkotok"
              className="inline-flex items-center justify-center border border-mma-blue bg-mma-blue px-4 py-2 text-xs font-semibold uppercase tracking-wide text-white transition hover:bg-mma-blue/90"
            >
              {tNav('creators')}
            </Link>
          </div>
        </div>
      </section>
    );
  }

  if (!hasMounted) {
    return (
      <section className="px-site pb-8 min-h-[55vh]">
        <div className="mx-auto max-w-boxed flex flex-col gap-2">
          <Breadcrumbs items={breadcrumbs} sticky />
          <div className="w-full rounded-lg border border-slate-200 bg-slate-100 min-h-[55vh]" />
        </div>
      </section>
    );
  }

  if (isMobile) {
    return (
      <section className="px-site pb-8 min-h-[55vh]">
        <div className="mx-auto max-w-boxed flex flex-col gap-2">
          <Breadcrumbs items={breadcrumbs} sticky />
          <div className="border border-slate-200 bg-white p-6 text-center shadow-sm">
            <div className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">
              {t('mobile.title')}
            </div>
            <p className="mt-3 text-sm text-slate-600">{t('mobile.body')}</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="px-site pb-8">
      <div className="mx-auto max-w-boxed flex flex-col gap-2">
        <Breadcrumbs items={breadcrumbs} sticky />

        <Modal
          isOpen={showIntroModal}
          onClose={() => setShowIntroModal(false)}
          title={t('onboardingPrompt.modalTitle')}
          className="w-full max-w-5xl"
        >
          <div className="flex flex-col gap-4 p-6">
            <p className="text-sm sm:text-base text-slate-700">
              {t.rich('onboardingPrompt.modalBody', {
                strong: (chunks) => (
                  <span className="font-semibold text-base sm:text-lg text-slate-900">
                    {chunks}
                  </span>
                ),
              })}
            </p>
            <div className="overflow-hidden border border-slate-200 bg-white shadow-sm">
              <video
                className="h-auto w-full"
                src={INTRO_PROMPT_GIF}
                autoPlay
                loop
                muted
                playsInline
                aria-label={t('onboardingPrompt.gifAlt')}
              />
            </div>
          </div>
        </Modal>

        <ConnectionsSectionClient
          creatorId={entry.creatorId}
          name={creatorName}
          connections={connections}
          heightClassName="min-h-[75vh] h-[75vh]"
          controlsSlot={originSelector}
          overlaySlot={introPromptCard}
        />
      </div>
    </section>
  );
};

export default MuveszetiHaloClient;
