'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { ChevronRight, Layers } from 'lucide-react';

interface Category {
  id: string;
  name: string;
  slug: string;
  children?: Category[];
}

export default function CategorySidebar() {
  const pathname = usePathname();
  const locale = pathname.startsWith('/en') ? 'en' : 'vi';

  const { data: categories = [] } = useQuery<Category[]>({
    queryKey: ['categories'],
    queryFn: async () => (await api.get('/categories')).data,
  });

  return (
    <aside className="w-56 shrink-0">
      <div className="rounded-xl border border-white/10 bg-white/5 p-3">
        <div className="flex items-center gap-2 px-2 py-1.5 mb-2">
          <Layers className="h-4 w-4 text-violet-400" />
          <span className="text-sm font-semibold text-white">
            {locale === 'vi' ? 'Danh mục' : 'Categories'}
          </span>
        </div>
        <ul className="space-y-0.5">
          {categories.map((cat) => (
            <li key={cat.id}>
              <Link
                href={`/${locale}/search?categoryId=${cat.id}`}
                className="flex items-center justify-between rounded-lg px-3 py-2 text-sm text-gray-300 hover:bg-white/10 hover:text-white transition-colors"
              >
                <span>{cat.name}</span>
                {cat.children && cat.children.length > 0 && (
                  <ChevronRight className="h-3 w-3 text-gray-500" />
                )}
              </Link>
              {cat.children && cat.children.length > 0 && (
                <ul className="ml-3 border-l border-white/10 pl-2 mt-0.5 space-y-0.5">
                  {cat.children.map((child) => (
                    <li key={child.id}>
                      <Link
                        href={`/${locale}/search?categoryId=${child.id}`}
                        className="block rounded-lg px-3 py-1.5 text-xs text-gray-400 hover:bg-white/10 hover:text-white transition-colors"
                      >
                        {child.name}
                      </Link>
                    </li>
                  ))}
                </ul>
              )}
            </li>
          ))}
        </ul>
      </div>
    </aside>
  );
}
