/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState } from 'react';
import { twMerge } from 'tailwind-merge';

import { useStores } from '@/app/(root)/AppProviders';
// import ProjectMultiSelectDropdown from '@/components/select/ProjectMultiSelectDropdown';
import Pagination from '@/components/tab/Pagination';
import { usePreviewContext } from '@/context/PreviewContext';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import {
  BookmarkIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  SearchIcon,
  ThumbsUpIcon,
} from '@/icons';
import { ContextType } from '@/logging/contextTypes';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';
import { ProjectStore } from '@/state/projectStore';
import { DEFAULT_PROJECT_ID, SEARCH_DEBOUNCE_DELAY } from '@/utils/constants';

import ProjectMultiSelectDropdownV2 from '../select/ProjectMultiSelectDropdownV2';
import SongRow from '../song/SongRow';
import SpinnerSVG from '../svg/SpinnerSVG';

type ProjectHeaderProps = {
  project: ProjectStore;
  currentPage: number;
  maxPages: number;
  handlePageChange: (newPage: number) => void;
  isPinnedEnabled: boolean;
  setIsPinnedEnabled: (enabled: boolean) => void;
  isPinnedExpanded: boolean;
  setIsPinnedExpanded: (expanded: boolean) => void;
};

const ProjectHeader: React.FC<ProjectHeaderProps> = observer(
  ({
    project,
    currentPage,
    maxPages,
    handlePageChange,
    isPinnedEnabled,
    setIsPinnedEnabled,
    isPinnedExpanded,
    setIsPinnedExpanded,
  }) => {
    const [isSearching, setIsSearching] = useState(false);
    const searchTimeout = useRef<NodeJS.Timeout | null>(null);
    const isMobile = !useBreakpointMd();
    const [searchQuery, setSearchQuery] = useState('');
    const { queue: queueStore, playbar } = useStores();
    const { setPreviewClip } = usePreviewContext();
    const debouncedProjectClipSearch = (query: string) => {
      if (searchTimeout.current !== null) {
        clearTimeout(searchTimeout.current);
        searchTimeout.current = null;
      }
      setIsSearching(true);
      searchTimeout.current = setTimeout(async () => {
        project.updateFilters({ query });
        setIsSearching(false);
      }, SEARCH_DEBOUNCE_DELAY);
    };

    return (
      <>
        <div className='mt-[24px] mb-[16px] flex items-center justify-between gap-2 px-4'>
          <div className='flex flex-1 items-center space-x-2'>
            <div className='shrink-0'>
              <ProjectMultiSelectDropdownV2 project={project} />
            </div>

            {project.userSelectedProjectId === DEFAULT_PROJECT_ID && (
              <div className='hidden shrink-0 md:flex'>
                <FilterButton
                  isActive={project.filters.liked}
                  onClick={() => {
                    logWebUserEvent({
                      actionName: 'ProjectHeaderFilterButton',
                      context: {
                        active: project.filters.liked,
                        filter: 'liked',
                        projectId: project.currentProject?.id,
                        filters: project.filters,
                      },
                    });
                    project.updateFilters({ liked: !project.filters.liked });
                  }}
                  icon={<ThumbsUpIcon className='size-3' />}
                  text='Liked'
                  hideOnMobile={false}
                />
              </div>
            )}

            {project.userSelectedProjectId !== DEFAULT_PROJECT_ID && (
              <div className='flex shrink-0'>
                <FilterButton
                  isActive={isPinnedEnabled}
                  onClick={() => {
                    logWebUserEvent({
                      actionName: 'ProjectHeaderFilterButton',
                      context: {
                        active: isPinnedEnabled,
                        filter: 'pinned',
                        projectId: project.currentProject?.id,
                        filters: project.filters,
                      },
                    });
                    setIsPinnedEnabled(!isPinnedEnabled);
                  }}
                  icon={<BookmarkIcon width={14} height={14} />}
                  text='Bookmarked'
                  iconOnly={isMobile}
                  hideOnMobile={false}
                />
              </div>
            )}

            <div className='min-w-0 flex-1'>
              <div className='relative flex max-w-[400px]'>
                <span className='absolute top-[12px] left-[20px]'>
                  <SearchIcon
                    className={clsx({
                      'text-foreground-primary': searchQuery.length > 0,
                      'text-foreground-tertiary': searchQuery.length === 0,
                    })}
                  />
                </span>
                <span className='absolute top-[10px] right-[7px] opacity-70'>
                  {(isSearching || project.loadingProjectClips) && (
                    <SpinnerSVG />
                  )}
                </span>
                <input
                  type='text'
                  placeholder='Title or Style'
                  className='placeholder-opacity-50 h-10 w-full max-w-[400px] rounded-full bg-background-secondary pl-12 font-sans outline-none md:hidden'
                  value={searchQuery}
                  onChange={(e: any) => {
                    setSearchQuery(e.target.value);
                    debouncedProjectClipSearch(e.target.value);
                  }}
                />
                <input
                  type='text'
                  placeholder='Search'
                  className='hidden h-10 w-full max-w-[400px] rounded-full bg-background-secondary pl-12 font-sans placeholder-foreground-primary/50 outline-none md:block'
                  value={searchQuery}
                  onChange={(e: any) => {
                    setSearchQuery(e.target.value);
                    debouncedProjectClipSearch(e.target.value);
                  }}
                />
              </div>
            </div>
          </div>
          <div className='shrink-0'>
            <Pagination
              page={currentPage}
              onDecrementPage={() => {
                if (currentPage > 1) {
                  handlePageChange(currentPage - 1);
                  logWebUserEvent({
                    actionName: 'ProjectHeaderPagination',
                    context: {
                      page: currentPage - 1,
                      projectId: project.currentProject?.id,
                      type: 'decrement',
                      filters: project.filters,
                    },
                  });
                }
              }}
              onIncrementPage={() => {
                if (currentPage < maxPages) {
                  handlePageChange(currentPage + 1);
                  logWebUserEvent({
                    actionName: 'ProjectHeaderPagination',
                    context: {
                      page: currentPage + 1,
                      projectId: project.currentProject?.id,
                      type: 'increment',
                      filters: project.filters,
                    },
                  });
                }
              }}
              setPageNumber={handlePageChange}
              maxPages={maxPages}
              disableLeft={currentPage === 1}
              disableRight={currentPage >= maxPages}
              zeroIndexed={false}
            />
          </div>
        </div>
        {project.pinnedClips?.length > 0 && (
          <div
            className='flex cursor-pointer items-center px-6 text-[12px] font-medium text-[#BAB4B1]'
            onClick={() => setIsPinnedExpanded(!isPinnedExpanded)}
          >
            <span>Bookmarked ({project.pinnedClips?.length})</span>
            {isPinnedExpanded ? (
              <ChevronDownIcon className='ml-1 h-3 w-3' />
            ) : (
              <ChevronRightIcon className='ml-1 h-3 w-3' />
            )}
          </div>
        )}
        {project.pinnedClips?.length > 0 && isPinnedExpanded && (
          <div className='custom-scrollbar-transparent mx-6 flex overflow-x-scroll overflow-y-hidden pt-2 pb-2 text-sm text-primary'>
            {project.pinnedClips.map((clip) => {
              return (
                <div className='w-[230px] shrink-0' key={clip.id}>
                  <SongRow
                    expanded={false}
                    showStats={false}
                    showActions={true}
                    mini={true}
                    enablePin={true}
                    showTags={false}
                    selected={false}
                    key={clip.id}
                    clip={clip}
                    contextType={ContextType.Workspace}
                    contextId={
                      project.currentProject?.id ||
                      'PROJECT_HEADER_MISSING_PROJECT_ID'
                    }
                    onPinClipToProject={() => {
                      if (
                        project.userSelectedProjectId &&
                        project.userSelectedProjectId !== DEFAULT_PROJECT_ID
                      ) {
                        project.pinClipToProject(
                          [clip],
                          project.userSelectedProjectId,
                          !project.isPinned(clip.id)
                        );
                      }
                    }}
                    onClick={() => {
                      setPreviewClip(clip);
                    }}
                    onPlay={() => {
                      if (
                        queueStore.contextType === ContextType.Workspace &&
                        queueStore.contextId ===
                          (project.currentProject?.id || '') &&
                        playbar.clip?.id === clip.id
                      ) {
                        playbar.togglePlay();
                        return;
                      }
                      queueStore.setPlayContext({
                        contextType: ContextType.Workspace,
                        contextId:
                          project.currentProject?.id ||
                          'PROJECT_HEADER_MISSING_PROJECT_ID',
                        currentIndex:
                          project.pinnedClips.findIndex(
                            (c: Clip) => c.id === clip.id
                          ) || 0,
                        clips: project.pinnedClips || [],
                      });
                      playbar.playClip(clip);
                    }}
                    isCreatePage
                  />
                </div>
              );
            })}
          </div>
        )}
      </>
    );
  }
);

interface FilterButtonProps {
  isActive: boolean;
  onClick: () => void;
  icon: React.ReactNode;
  text: string;
  hideOnMobile?: boolean;
  iconOnly?: boolean;
}

const FilterButton: React.FC<FilterButtonProps> = ({
  isActive,
  onClick,
  icon,
  text,
  hideOnMobile = true,
  iconOnly = false,
}) => (
  <button
    onClick={onClick}
    className={twMerge(
      clsx(
        'h-10 cursor-pointer flex-row items-center justify-center gap-2 font-sans text-sm whitespace-nowrap transition-colors',
        {
          'hidden md:flex': hideOnMobile,
          flex: !hideOnMobile,
          'w-10 rounded-full': iconOnly,
          'rounded-full px-3 md:px-4': !iconOnly,
          'bg-foreground-primary text-background-primary': isActive,
          'bg-background-secondary text-foreground-primary hover:bg-background-tertiary':
            !isActive,
        }
      )
    )}
  >
    {icon}
    {!iconOnly && <span className='hidden md:inline'>{text}</span>}
  </button>
);

export default ProjectHeader;
