// app/students/components/SearchFilters.jsx
import React, { useEffect } from 'react';
import { Search, Globe, GraduationCap, DollarSign, Filter, CheckCircle } from 'lucide-react';

const SearchFilters = ({ searchQuery, onSearch, filters, onFilterChange, countries }) => {
  // Auto-apply filters on change
  useEffect(() => {
    const timer = setTimeout(() => {
      // Trigger search when filters change (except for initial load)
      if (searchQuery !== '' || Object.values(filters).some(val => val !== '' && val !== 'all')) {
        onSearch(searchQuery);
      }
    }, 300);

    return () => clearTimeout(timer);
  }, [filters, searchQuery]);

  const handleSearchChange = (e) => {
    onSearch(e.target.value);
  };

  const handleFilterChange = (key, value) => {
    onFilterChange({ ...filters, [key]: value });
  };

  const clearFilters = () => {
    onFilterChange({
      country: '',
      education: '',
      gender: '',
      minRate: '',
      maxRate: '',
      is_verified: 'all'
    });
    onSearch('');
  };

  const hasActiveFilters = Object.values(filters).some(val => 
    (val !== '' && val !== 'all' && val !== true) || searchQuery
  );

  return (
    <div className="w-full">
      {/* Active Filters Tags */}
      {hasActiveFilters && (
        <div className="mb-6 p-4 bg-gray-50 rounded-xl">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2">
              <Filter className="w-4 h-4" />
              Active Filters
            </h3>
            <button
              onClick={clearFilters}
              className="text-sm text-red-600 hover:text-red-800 font-medium"
            >
              Clear All
            </button>
          </div>
          <div className="flex flex-wrap gap-2">
            {searchQuery && (
              <span className="inline-flex items-center gap-1 bg-teal-100 text-teal-800 px-3 py-1.5 rounded-full text-sm">
                <Search className="w-3 h-3" />
                Search: {searchQuery}
                <button
                  onClick={() => onSearch('')}
                  className="ml-1 text-teal-600 hover:text-teal-800"
                >
                  ✕
                </button>
              </span>
            )}
            {filters.country && (
              <span className="inline-flex items-center gap-1 bg-blue-100 text-blue-800 px-3 py-1.5 rounded-full text-sm">
                <Globe className="w-3 h-3" />
                {countries.find(c => c.id == filters.country)?.name || filters.country}
                <button
                  onClick={() => handleFilterChange('country', '')}
                  className="ml-1 text-blue-600 hover:text-blue-800"
                >
                  ✕
                </button>
              </span>
            )}
            {filters.education && (
              <span className="inline-flex items-center gap-1 bg-amber-100 text-amber-800 px-3 py-1.5 rounded-full text-sm">
                <GraduationCap className="w-3 h-3" />
                {filters.education.replace('_', ' ').toUpperCase()}
                <button
                  onClick={() => handleFilterChange('education', '')}
                  className="ml-1 text-amber-600 hover:text-amber-800"
                >
                  ✕
                </button>
              </span>
            )}
            {(filters.minRate || filters.maxRate) && (
              <span className="inline-flex items-center gap-1 bg-green-100 text-green-800 px-3 py-1.5 rounded-full text-sm">
                <DollarSign className="w-3 h-3" />
                ${filters.minRate || '0'} - ${filters.maxRate || '∞'}
                <button
                  onClick={() => {
                    handleFilterChange('minRate', '');
                    handleFilterChange('maxRate', '');
                  }}
                  className="ml-1 text-green-600 hover:text-green-800"
                >
                  ✕
                </button>
              </span>
            )}
            {filters.is_verified !== 'all' && (
              <span className="inline-flex items-center gap-1 bg-indigo-100 text-indigo-800 px-3 py-1.5 rounded-full text-sm">
                <CheckCircle className="w-3 h-3" />
                Verified: {filters.is_verified === '1' ? 'Yes' : 'No'}
                <button
                  onClick={() => handleFilterChange('is_verified', 'all')}
                  className="ml-1 text-indigo-600 hover:text-indigo-800"
                >
                  ✕
                </button>
              </span>
            )}
          </div>
        </div>
      )}

      {/* Search Input */}
      <div className="mb-6">
        <div className="relative">
          <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={handleSearchChange}
            placeholder="Type to search students..."
            className="w-full rounded-xl border border-gray-300 bg-white pl-12 pr-4 py-3 text-gray-900 focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500"
          />
        </div>
      </div>

      {/* Filters Section */}
      <div className="space-y-6">
        {/* Country Filter */}
        <div>
          <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <Globe className="w-4 h-4" />
            Country
            {countries.length > 0 && (
              <span className="text-xs text-gray-500 ml-auto">
                ({countries.length} countries)
              </span>
            )}
          </h3>
          <select
            className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all duration-200"
            value={filters.country}
            onChange={(e) => handleFilterChange('country', e.target.value)}
          >
            <option value="">All Countries</option>
            {countries.map((country) => (
              <option key={country.id} value={country.id}>
                {country.name} ({country.student_count || 0})
              </option>
            ))}
          </select>
        </div>

        {/* Education Filter */}
        <div>
          <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <GraduationCap className="w-4 h-4" />
            Education Level
          </h3>
          <select
            className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all duration-200"
            value={filters.education}
            onChange={(e) => handleFilterChange('education', e.target.value)}
          >
            <option value="">All Levels</option>
            <option value="high_school">High School</option>
            <option value="bachelors">Bachelor's</option>
            <option value="masters">Master's</option>
            <option value="phd">PhD</option>
            <option value="diploma">Diploma</option>
            <option value="certificate">Certificate</option>
          </select>
        </div>

        {/* Hour Rate Range */}
        <div>
          <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <DollarSign className="w-4 h-4" />
            Hour Rate Range ($)
          </h3>
          <div className="space-y-3">
            <div>
              <label className="block text-xs text-gray-600 mb-1">Minimum</label>
              <input
                type="number"
                placeholder="0"
                className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all duration-200"
                value={filters.minRate}
                onChange={(e) => handleFilterChange('minRate', e.target.value)}
                min="0"
                step="5"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-600 mb-1">Maximum</label>
              <input
                type="number"
                placeholder="100"
                className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all duration-200"
                value={filters.maxRate}
                onChange={(e) => handleFilterChange('maxRate', e.target.value)}
                min="0"
                step="5"
              />
            </div>
          </div>
        </div>

        {/* Verified Status Filter - Full Width */}
        <div>
          <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <CheckCircle className="w-4 h-4" />
            Verification Status
          </h3>
          <select
            className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all duration-200"
            value={filters.is_verified}
            onChange={(e) => handleFilterChange('is_verified', e.target.value)}
          >
            <option value="all">All Verification Status</option>
            <option value="1">Verified Only</option>
            <option value="0">Not Verified</option>
          </select>
        </div>
      </div>
    </div>
  );
};

export default SearchFilters;