'use client';

import { cn } from '@/lib/utils';
import { useHomeStore } from '../../store';
import React, { useMemo } from 'react';
import { useTranslations } from 'next-intl';
import IconFont from '@/components/ui/iconFont';
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popver';
import omit from 'lodash/omit';
import { TagListSelect } from './TagListSelect';

export const MoreFilter = React.memo(() => {
  const characterParams = useHomeStore((state) => state.characterParams);
  const setCharacterParams = useHomeStore((state) => state.setCharacterParams);
  const t = useTranslations('common');

  // 计算筛选条件数量
  const queryKeyNum = useMemo(() => {
    const currentParams = omit(characterParams, ['tagIds']);
    return Object.values(currentParams).reduce((acc, curr) => {
      const count = Array.isArray(curr) ? curr.length : 1;
      return acc + count;
    }, 0);
  }, [characterParams]);

  const genderOptions = [
    {
      label: t('gender_0'),
      value: 0,
    },
    {
      label: t('gender_1'),
      value: 1,
    },
    {
      label: t('gender_2'),
      value: 2,
    },
  ];

  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          className={cn(
            'flex cursor-pointer items-center gap-1 hover:text-white/80 transition-colors',
            queryKeyNum > 0 ? 'text-white' : 'text-white/60'
          )}
        >
          <IconFont type="icon-filter-fill" />
          <span className="txt-bodySemibold-m">
            {t('filter')} {queryKeyNum > 0 ? `(${queryKeyNum})` : ''}
          </span>
        </button>
      </PopoverTrigger>
      <PopoverContent className="w-70 p-4" align="end" sideOffset={8}>
        <div className="text-white txt-title-s mb-2">{t('gender')}</div>
        <TagListSelect
          options={genderOptions}
          value={characterParams.genders || []}
          onChange={(values) => setCharacterParams({ genders: values as number[] })}
        />
      </PopoverContent>
    </Popover>
  );
});

MoreFilter.displayName = 'MoreFilter';
