'use client';

import { observer } from 'mobx-react-lite';
import { useInView } from 'react-intersection-observer';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { HooksFeedType } from '@/components/hooksPlayer/constants';
import { useVideoHooksContextualFeed } from '@/components/hooksPlayer/useVideoHooks';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { PlusIcon } from '@/icons';
import { logHookWebGeneralEvent } from '@/logging/logWebUserEvent';

import { LibraryHookCard } from '../LibraryHooks';

const LibraryV2Hooks: React.FC = observer(() => {
  const { session } = useStores();

  const { hooks, query: hooksQuery } = useVideoHooksContextualFeed({
    feedId: HooksFeedType.Profile,
    userHandle: session.user?.handle,
    enabled: !!session.user?.handle,
  });

  const [paginationRef] = useInView({
    onChange: async (inView) => {
      if (inView && !hooksQuery.isFetchingNextPage) {
        hooksQuery.fetchNextPage();
      }
    },
  });

  if (!hooksQuery.isFetched) {
    return (
      <div className='flex h-full items-center justify-center'>
        <SpinnerSVG />
      </div>
    );
  }

  if (!hooks.length) {
    return (
      <div className='flex flex-col items-stretch justify-center gap-4 p-6'>
        <p className='text-center text-foreground-tertiary'>
          You have not created any hooks yet. Try it out!
        </p>
        <Button
          className='mx-auto'
          icon={PlusIcon}
          size={ButtonSize.Small}
          variant={ButtonVariant.Primary}
          shape={ButtonShape.Pill}
          href='/hooks/create'
          onClick={() => {
            logHookWebGeneralEvent({
              actionName: 'CreateHookClicked',
              context: {
                hookId: '',
                recommendationItemId: '',
                entryPoint: 'library',
              },
            });
          }}
        >
          Create hook
        </Button>
      </div>
    );
  }

  return (
    <div className='px-6 py-4'>
      <ul className='grid grid-cols-[repeat(auto-fill,minmax(10rem,1fr))] gap-4 max-xs:grid-cols-1'>
        {hooks.map((hook, i) => (
          <li key={hook.id} className='max-w-60 max-xs:max-w-full'>
            <LibraryHookCard index={i} hook={hook} />
          </li>
        ))}
      </ul>
      {!hooksQuery.hasNextPage || hooksQuery.isFetchingNextPage ? null : (
        <div ref={paginationRef} />
      )}
    </div>
  );
});

export default LibraryV2Hooks;
