'use client';

import { useStatsigClient } from '@statsig/react-bindings';
import { observer } from 'mobx-react-lite';
import { useSearchParams } from 'next/navigation';
import { useEffect } from 'react';
import { Tab, TabList, TabPanel, Tabs } from 'react-aria-components';

import { useStores } from '@/app/(root)/AppProviders';
import SearchInput from '@/components/textarea/SearchInput';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import usePageViewLog from '@/hooks/usePageViewLog';
import { SearchTypeEnum } from '@/state/searchStore';
import { REACT_ARIA_TABS_STYLE } from '@/utils/constants';

import GenreSearch from './GenreSearch';
import PersonaSearch from './PersonaSearch';
import PlaylistSearchNew from './PlaylistSearch';
import SearchSongList from './SearchSongList';
import SortingMenu from './SortingMenu';
import Users from './Users';
import {
  PLATFORM_GENRE,
  PLAYLIST,
  PUBLIC_PERSONA,
  PUBLIC_SONG,
  SEARCH_TERM_URL_KEY,
  SEARCH_TYPE_URL_KEY,
  USER,
} from './utils';

const SearchPage = observer(() => {
  const { search } = useStores();

  const isMobile = !useBreakpointMd();

  const statsigClient = useStatsigClient();
  const isPersonaSearchEnabled = statsigClient.checkGate('persona-search');
  const searchTerm = useSearchParams().get(SEARCH_TERM_URL_KEY);
  const searchType = useSearchParams().get(SEARCH_TYPE_URL_KEY);

  usePageViewLog({
    actionName: 'PageViewed',
    componentContext: 'search',
  });

  useEffect(() => {
    if (searchTerm) {
      search.searchTerm = searchTerm;
    }

    if (
      searchType &&
      [PLAYLIST, USER, PUBLIC_PERSONA, PLATFORM_GENRE].includes(searchType)
    ) {
      search.setSearchType(searchType as SearchTypeEnum);
    } else {
      search.setSearchType(PUBLIC_SONG);
    }
  }, []);

  useEffect(() => {
    if (search.searchTerm && search.searchTerm.length > 0) {
      window.history.pushState(
        {},
        '',
        `?${SEARCH_TYPE_URL_KEY}=${search.searchType}&${SEARCH_TERM_URL_KEY}=${search.searchTerm}`
      );
    } else {
      window.history.pushState(
        {},
        '',
        `?${SEARCH_TYPE_URL_KEY}=${search.searchType}`
      );
    }
  }, [search.searchTerm, isPersonaSearchEnabled, search.searchType]);

  return (
    <div className='mt-0 flex h-full w-full flex-col md:mt-8'>
      {!isMobile && (
        <div className='sticky top-0 z-10 bg-background-primary px-5 py-3'>
          <SearchInput />
        </div>
      )}
      <div className='justify-left w-full flex-1 overflow-y-auto bg-background-primary'>
        <Tabs
          defaultSelectedKey={searchType ?? PUBLIC_SONG}
          onSelectionChange={(key) => {
            search.setSearchType(key as SearchTypeEnum);
          }}
          keyboardActivation='manual'
          className='flex h-full flex-col'
        >
          <div className='flex w-full flex-row justify-between px-2 pb-4'>
            <TabList
              aria-label='Search type'
              className='flex flex-row gap-4 px-4 py-2 py-4 font-medium'
            >
              <Tab id={PUBLIC_SONG} className={REACT_ARIA_TABS_STYLE}>
                Songs
              </Tab>
              <Tab id={PLAYLIST} className={REACT_ARIA_TABS_STYLE}>
                Playlists
              </Tab>
              <Tab id={USER} className={REACT_ARIA_TABS_STYLE}>
                Users
              </Tab>
              <Tab id={PLATFORM_GENRE} className={REACT_ARIA_TABS_STYLE}>
                Genres
              </Tab>
              {isPersonaSearchEnabled && (
                <Tab id={PUBLIC_PERSONA} className={REACT_ARIA_TABS_STYLE}>
                  Personas
                </Tab>
              )}
            </TabList>
            {search.searchType !== USER &&
              search.searchType !== PLATFORM_GENRE && (
                <div className='flex flex-row items-center pr-4'>
                  <SortingMenu
                    onSwitchSorting={(selectionText) => {
                      search.setSearchRankingType(selectionText);
                    }}
                  />
                </div>
              )}
          </div>

          <TabPanel id={PUBLIC_SONG} className='flex min-h-0 flex-1 flex-col'>
            <div className='flex h-full w-full flex-col'>
              <SearchSongList />
            </div>
          </TabPanel>
          <TabPanel id={PLAYLIST}>
            <PlaylistSearchNew />
          </TabPanel>
          <TabPanel id={USER}>
            <Users />
          </TabPanel>
          <TabPanel id={PLATFORM_GENRE}>
            <GenreSearch />
          </TabPanel>
          {isPersonaSearchEnabled && (
            <TabPanel id={PUBLIC_PERSONA}>
              <PersonaSearch />
            </TabPanel>
          )}
        </Tabs>
      </div>
    </div>
  );
});

export default SearchPage;
