'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { useState, useTransition } from 'react';

interface BlogFiltersProps {
  categories?: string[];
  totalCount: number;
  baseUrl?: string;
  hideCategoryFilter?: boolean;
}

export function BlogFilters({ categories = [], totalCount, baseUrl = '/blogs', hideCategoryFilter = false }: BlogFiltersProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  const [searchQuery, setSearchQuery] = useState(searchParams.get('search') || '');
  const currentCategory = searchParams.get('category') || '';
  const currentSort = searchParams.get('sort') || 'desc';

  const updateFilters = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString());
    
    if (value) {
      params.set(key, value);
    } else {
      params.delete(key);
    }
    
    // Reset to page 1 when filters change
    params.delete('page');
    
    startTransition(() => {
      router.push(`${baseUrl}?${params.toString()}`);
    });
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchQuery(value);
    
    // Debounce search
    const timeoutId = setTimeout(() => {
      updateFilters('search', value);
    }, 500);
    
    return () => clearTimeout(timeoutId);
  };

  const handleCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    updateFilters('category', e.target.value);
  };

  const handleSortChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    updateFilters('sort', e.target.value);
  };

  return (
    <div className="mb-8">
      {/* Filters Row */}
      <div className="flex flex-col md:flex-row gap-4">
        {/* Search Bar */}
        <div className="flex-1 relative">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-[#B8B8C0]"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
          </div>
          <input
            type="search"
            value={searchQuery}
            onChange={handleSearchChange}
            placeholder="タイトルで検索..."
            className="w-full pl-10 pr-4 py-2.5 rounded-lg border border-[#2A2A33] bg-[#202026] text-white placeholder-[#B8B8C0] focus:outline-none focus:ring-2 focus:ring-[#E60023] focus:border-transparent transition-all"
          />
        </div>

        {/* Category Filter - Only show if not hidden */}
        {!hideCategoryFilter && (
          <select
            value={currentCategory}
            onChange={handleCategoryChange}
            className="px-4 py-2.5 rounded-lg border border-[#2A2A33] bg-[#202026] text-white focus:outline-none focus:ring-2 focus:ring-[#E60023] focus:border-transparent transition-all cursor-pointer min-w-[200px]"
          >
            <option value="">すべてのカテゴリー</option>
            {categories.map((category) => (
              <option key={category} value={category}>
                {category}
              </option>
            ))}
          </select>
        )}

        {/* Sort Order */}
        <select
          value={currentSort}
          onChange={handleSortChange}
          className="px-4 py-2.5 rounded-lg border border-[#2A2A33] bg-[#202026] text-white focus:outline-none focus:ring-2 focus:ring-[#E60023] focus:border-transparent transition-all cursor-pointer min-w-[150px]"
        >
          <option value="desc">新しい順</option>
          <option value="asc">古い順</option>
        </select>
      </div>

      {/* Active Filters Display */}
      {(searchQuery || (currentCategory && !hideCategoryFilter) || currentSort !== 'desc') && (
        <div className="mt-4 flex flex-wrap gap-2">
          {searchQuery && (
            <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-[#202026] border border-[#E60023] text-[#E60023] text-sm">
              検索: {searchQuery}
              <button
                onClick={() => {
                  setSearchQuery('');
                  updateFilters('search', '');
                }}
                className="hover:text-[#FF2A3D] transition-colors"
              >
                ×
              </button>
            </span>
          )}
          {currentCategory && !hideCategoryFilter && (
            <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-[#202026] border border-[#E60023] text-[#E60023] text-sm">
              {currentCategory}
              <button
                onClick={() => updateFilters('category', '')}
                className="hover:text-[#FF2A3D] transition-colors"
              >
                ×
              </button>
            </span>
          )}
          {currentSort === 'asc' && (
            <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-[#202026] border border-[#E60023] text-[#E60023] text-sm">
              古い順
              <button
                onClick={() => updateFilters('sort', 'desc')}
                className="hover:text-[#FF2A3D] transition-colors"
              >
                ×
              </button>
            </span>
          )}
        </div>
      )}

      {/* Loading Indicator */}
      {isPending && (
        <div className="mt-4 text-center text-[#B8B8C0] text-sm">
          読み込み中...
        </div>
      )}
    </div>
  );
}
