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

/* eslint jsx-a11y/no-static-element-interactions: warn */
import { useOutsideClick } from '@chakra-ui/react';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState } from 'react';
import ReactDOM from 'react-dom';

import {
  CoverCreateIcon,
  ExtendRightIcon,
  FilterIcon,
  FourStarIcon,
  GlobeIcon,
  PersonaSmileIcon,
  StemsIcon,
  ThumbsDownIcon,
  ThumbsUpIcon,
  UploadIcon,
  VideoIcon,
  VinylIcon,
} from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { LibraryStore } from '@/state/libraryStore';

import { AvatarMaskShape } from '../image/Avatar';

interface LibraryFilterOption {
  key: string;
  name: string;
  icon: React.ReactNode;
  type: string;
}

const LIBRARY_FILTER_OPTIONS: LibraryFilterOption[] = [
  {
    key: 'liked',
    name: 'Liked',
    icon: <ThumbsUpIcon className='h-3 w-3' />,
    type: 'checkbox',
  },
  {
    key: 'hide_disliked',
    name: 'Hide Disliked',
    icon: <ThumbsDownIcon className='h-3 w-3' />,
    type: 'checkbox',
  },
  {
    key: 'hide_gen_stems',
    name: 'Hide Stems',
    icon: <StemsIcon className='h-3 w-3' />,
    type: 'checkbox',
  },
  {
    key: 'hide_studio_clips',
    name: 'Hide Clips from Edit Mode',
    icon: <StemsIcon className='h-3 w-3' />,
    type: 'checkbox',
  },
  {
    key: 'public',
    name: 'Public',
    icon: <GlobeIcon className='h-3 w-3' />,
    type: 'checkbox',
  },
  {
    key: 'is_suno_short',
    name: 'Scenes',
    icon: <VideoIcon className='h-3 w-3' />,
    type: 'checkbox',
  },
  {
    key: 'is_uploaded_audio',
    name: 'Uploads',
    icon: <UploadIcon className='h-3 w-3' />,
    type: 'radio',
  },
  {
    key: 'full_song',
    name: 'Full Songs',
    icon: <VinylIcon className='h-3 w-3' />,
    type: 'radio',
  },
  {
    key: 'is_extend',
    name: 'Extensions',
    icon: <ExtendRightIcon className='h-3 w-3' />,
    type: 'radio',
  },
  {
    key: 'is_cover',
    name: 'Covers',
    icon: <CoverCreateIcon className='h-3 w-3' />,
    type: 'radio',
  },
  {
    key: 'is_persona',
    name: 'Personas',
    icon: (
      <span className='inline-flex h-3 w-3 items-center justify-center'>
        <div className='relative h-full w-full'>
          <div
            className='absolute inset-0 bg-current'
            style={AvatarMaskShape.Persona}
          />
          <PersonaSmileIcon className='absolute inset-0 top-[5%] left-[5%] h-[90%] w-[90%] text-dumbo-50' />
        </div>
      </span>
    ),
    type: 'radio',
  },
  {
    key: 'is_upsample',
    name: 'Remasters',
    icon: <FourStarIcon className='h-3 w-3' />,
    type: 'radio',
  },
];

interface LibraryMultiSelectDropdownProps {
  library: LibraryStore;
}

const LibraryMultiSelectDropdown: React.FC<LibraryMultiSelectDropdownProps> =
  observer(({ library }) => {
    const [isOpen, setIsOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const buttonRef = useRef<HTMLDivElement>(null);

    useOutsideClick({
      ref: dropdownRef as React.RefObject<HTMLDivElement>,
      handler: (e) => {
        if (!buttonRef.current?.contains(e.target as any)) {
          setIsOpen(false);
        }
      },
    });

    const activeFilterCount = Object.entries(library.filters.clips).filter(
      ([key, value]) => value === true && key !== 'page' && key !== 'query'
    ).length;

    const handleFilterToggle = (filterKey: string) => {
      const option = LIBRARY_FILTER_OPTIONS.find(
        (opt) => opt.key === filterKey
      );
      if (option?.type === 'checkbox') {
        library.updateFilters({
          [filterKey]:
            !library.filters.clips[
              filterKey as keyof typeof library.filters.clips
            ],
        });
      } else {
        const value =
          !library.filters.clips[
            filterKey as keyof typeof library.filters.clips
          ];
        if (value) {
          const updatedFilters = {
            is_cover: false,
            is_extend: false,
            is_upsample: false,
            is_persona: false,
            full_song: false,
            is_uploaded_audio: false,
            [filterKey]: true,
          };
          library.updateFilters(updatedFilters);
        } else {
          library.updateFilters({ [filterKey]: false });
        }
      }

      logWebUserEvent({
        actionName: 'LibraryMultiSelectDropdownClicked',
        context: {
          type: 'filter-toggle',
          active: library.filters.clips[
            filterKey as keyof typeof library.filters.clips
          ] as boolean,
          filter: filterKey,
          filters: library.filters.clips,
        } as any,
      });
    };

    const clearAllFilters = () => {
      logWebUserEvent({
        actionName: 'LibraryMultiSelectDropdownClicked',
        context: {
          type: 'clear-all-filters',
          filters: library.filters.clips,
        } as any,
      });
      library.clearFilters();
      library.updateFilters({});
      setIsOpen(false);
    };

    const rect = buttonRef.current?.getBoundingClientRect();
    const position = {
      top: rect ? rect.bottom + window.scrollY : 0,
      left: rect ? rect.left : 0,
    };

    return (
      <div className='relative inline-block text-left font-sans'>
        <div
          ref={buttonRef}
          className={`flex aspect-square h-10 cursor-pointer flex-row items-center justify-center gap-2 rounded-full border border-quaternary px-3 font-sans text-sm whitespace-nowrap md:aspect-auto md:px-4 ${
            activeFilterCount > 0
              ? 'bg-primary text-dumbo-50'
              : 'bg-transparent text-primary hover:bg-primary/10'
          }`}
          onClick={() => setIsOpen(!isOpen)}
        >
          <FilterIcon
            className={`h-3 w-3 ${
              activeFilterCount > 0 ? 'text-dumbo-50' : 'text-primary'
            }`}
          />
          <span className='line-clamp-1 hidden font-medium break-all md:inline'>
            Filters {activeFilterCount > 0 && `(${activeFilterCount})`}
          </span>
        </div>

        {isOpen &&
          ReactDOM.createPortal(
            <div
              className='absolute z-10000 mt-2 max-h-[445px] w-48 overflow-y-auto rounded-lg shadow-lg'
              style={{
                top: position.top,
                left: position.left,
                background: '#252020',
                padding: '4px',
                fontSize: '14px',
                fontWeight: '500',
                cursor: 'pointer',
                transition: 'opacity 0.2s ease',
                border: '1px solid rgba(255, 255, 255, 0.2)',
              }}
              ref={dropdownRef}
            >
              <div className='py-1'>
                {LIBRARY_FILTER_OPTIONS.map((option, index) => (
                  <React.Fragment key={option.key}>
                    {index === 6 && (
                      <div
                        style={{
                          borderBottom: '1px solid rgba(255, 255, 255, 0.2)',
                          margin: '8px 0 8px 0',
                        }}
                      />
                    )}
                    <div
                      className={`my-1 flex cursor-pointer items-center justify-between rounded-lg px-3 py-2 font-sans text-sm hover:bg-quaternary`}
                      style={{
                        transition: 'background-color 0.3s ease',
                        outline: 'none',
                        fontFamily: 'Neue Montreal, sans-serif',
                      }}
                      onClick={() => handleFilterToggle(option.key)}
                    >
                      <div className='flex items-center gap-2'>
                        {React.cloneElement(
                          option.icon as React.ReactElement<{
                            className: string;
                          }>,
                          {
                            className: 'w-3 h-3 text-primary',
                          }
                        )}
                        <span>{option.name}</span>
                      </div>
                      {option.type === 'checkbox' ? (
                        <div
                          className={`h-4 w-4 rounded border-2 ${
                            library.filters.clips[
                              option.key as keyof typeof library.filters.clips
                            ]
                              ? 'border-[#C73D66] bg-[#C73D66]'
                              : 'border-quaternary'
                          } flex items-center justify-center`}
                        >
                          {library.filters.clips[
                            option.key as keyof typeof library.filters.clips
                          ] && (
                            <svg
                              className='h-3 w-3 text-white'
                              fill='none'
                              stroke='currentColor'
                              viewBox='0 0 24 24'
                            >
                              <path
                                strokeLinecap='round'
                                strokeLinejoin='round'
                                strokeWidth={4}
                                d='M5 13l4 4L19 7'
                              />
                            </svg>
                          )}
                        </div>
                      ) : (
                        <div
                          className={`h-4 w-4 rounded-full border-2 ${
                            library.filters.clips[
                              option.key as keyof typeof library.filters.clips
                            ]
                              ? 'border-[#C73D66] bg-[#C73D66]'
                              : 'border-quaternary'
                          } flex items-center justify-center`}
                        >
                          {library.filters.clips[
                            option.key as keyof typeof library.filters.clips
                          ] && (
                            <div className='h-2 w-2 rounded-full bg-white' />
                          )}
                        </div>
                      )}
                    </div>
                  </React.Fragment>
                ))}
                {activeFilterCount > 0 && (
                  <>
                    <div
                      style={{
                        borderBottom: '1px solid rgba(255, 255, 255, 0.2)',
                        margin: '8px 0 8px 0',
                      }}
                    />
                    <div
                      className='flex cursor-pointer rounded-lg px-3 py-2 font-sans text-sm text-primary hover:bg-quaternary'
                      style={{
                        transition: 'background-color 0.3s ease',
                        outline: 'none',
                        fontFamily: 'Neue Montreal, sans-serif',
                      }}
                      onClick={clearAllFilters}
                    >
                      Clear all ({activeFilterCount})
                    </div>
                  </>
                )}
              </div>
            </div>,
            document.body
          )}
      </div>
    );
  });

export default LibraryMultiSelectDropdown;
