'use client';

import { cn } from '@/lib/utils';
import Image from 'next/image';
import { useHomeStore } from '../../store';
import { useQuery } from '@tanstack/react-query';
import { fetchCharacterTags } from '@/services/editor';
import { useRef } from 'react';
import { useTranslations } from 'next-intl';
import { TagListSelect } from './TagListSelect';
import { MoreFilter } from './MoreFilter';

const Filter = () => {
  const ref = useRef<HTMLDivElement>(null);
  const { tab, setTab, characterParams, novelParams, setCharacterParams, setNovelParams } =
    useHomeStore();
  const t = useTranslations('home');
  const currentTabTagIds = tab === 'character' ? characterParams.tagIds : novelParams.tagIds;

  const { data: tags = [] } = useQuery({
    queryKey: ['tags', tab],
    queryFn: async () => {
      if (tab === 'character') {
        const { data } = await fetchCharacterTags({ limit: 10 });
        return data.rows;
      }
      return [];
    },
  });

  const tabs = [
    {
      label: t('story'),
      value: 'story',
      icon: 'icon-story',
      activeIcon: 'icon-story-active',
    },
    {
      label: t('character'),
      value: 'character',
      icon: 'icon-character',
      activeIcon: 'icon-character-active',
    },
  ] as const;

  return (
    <div ref={ref}>
      <div className="flex justify-between items-center mb-3">
        <div className="flex items-center sm:mb-6 gap-5 sm:gap-12">
          {tabs.map((item) => {
            const active = tab === item.value;
            return (
              <div
                key={item.value}
                onClick={() => setTab(item.value)}
                className={cn(
                  'flex items-center cursor-pointer gap-1 sm:gap-2',
                  active ? 'text-txt-primary-normal' : 'text-txt-secondary-normal'
                )}
              >
                <Image
                  src={`/images/home/${active ? item.activeIcon : item.icon}.png`}
                  alt={item.label}
                  width={28}
                  height={28}
                  className="w-5 h-5 sm:w-7 sm:h-7"
                />
                <span className="txt-title-m sm:txt-title-l">{item.label}</span>
              </div>
            );
          })}
        </div>
        {tab === 'character' && <MoreFilter />}
      </div>
      <TagListSelect
        options={tags.map((tag: any) => ({ label: tag.name, value: tag.id }))}
        value={currentTabTagIds || []}
        onChange={(values) =>
          tab === 'character'
            ? setCharacterParams({ tagIds: values as string[] })
            : setNovelParams({ tagIds: values as string[] })
        }
      />
    </div>
  );
};

export default Filter;
