'use client';

import { cn } from '@/lib/utils';
import Image from 'next/image';
import { Chip } from '@/components/ui/chip';
import { useHomeStore } from '../store';
import { useQuery } from '@tanstack/react-query';
import { fetchCharacterTags } from '@/services/editor';

const Filter = () => {
  const tab = useHomeStore((state) => state.tab);
  const setTab = useHomeStore((state) => state.setTab);
  const selectedTags = useHomeStore((state) => state.selectedTags);
  const setSelectedTags = useHomeStore((state) => state.setSelectedTags);

  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: 'Story',
      value: 'story',
      icon: 'icon-story',
      activeIcon: 'icon-story-active',
    },
    {
      label: 'Character',
      value: 'character',
      icon: 'icon-character',
      activeIcon: 'icon-character-active',
    },
  ] as const;

  return (
    <div className="sticky top-0 z-10">
      <div className="flex mb-6 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-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}
              />
              <span className="txt-headline-s">{item.label}</span>
            </div>
          );
        })}
      </div>
      <div className="flex flex-wrap gap-2">
        {tags?.map((tag: any) => (
          <Chip
            key={tag.id}
            size="small"
            className="px-4"
            state={selectedTags.includes(tag.id) ? 'active' : 'inactive'}
            onClick={() => setSelectedTags([tag.id])}
          >
            # {tag.name}
          </Chip>
        ))}
      </div>
    </div>
  );
};

export default Filter;
