import { useState, useEffect } from 'react';
import { useSearchParams, Link } from 'react-router-dom';
import { api } from '../context/AuthContext';
import { Search as SearchIcon, Filter, X, Star, MapPin, Clock, Loader2, Users, Award } from 'lucide-react';

const categories = ['All', 'Plumbing', 'Electrical', 'Carpentry', 'Cleaning', 'Painting', 'HVAC', 'Appliance Repair', 'Gardening'];

export default function Search() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [query, setQuery] = useState(searchParams.get('q') || '');
  const [results, setResults] = useState({ services: [], providers: [] });
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('services');
  const [filters, setFilters] = useState({ category: '', minPrice: 0, maxPrice: 500, rating: 0 });
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    if (!query.trim()) { setResults({ services: [], providers: [] }); return; }
    const params = new URLSearchParams({ search: query, limit: 20 });
    if (filters.category) params.set('category', filters.category);
    if (filters.minPrice > 0) params.set('minPrice', filters.minPrice);
    if (filters.maxPrice < 500) params.set('maxPrice', filters.maxPrice);
    if (filters.rating > 0) params.set('minRating', filters.rating);
    setLoading(true);
    Promise.all([
      api.get(`/services?${params}`),
      api.get(`/users/providers?${params}`)
    ]).then(([svcRes, provRes]) => {
      setResults({ services: svcRes.data.services, providers: provRes.data.providers });
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [query, filters]);

  const handleSearch = (e) => {
    e.preventDefault();
    setSearchParams({ q: query });
  };

  const clearFilters = () => setFilters({ category: '', minPrice: 0, maxPrice: 500, rating: 0 });

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <div className="container py-4">
          <form onSubmit={handleSearch} className="max-w-3xl mx-auto">
            <div className="relative">
              <SearchIcon className="absolute left-4 top-1/2 -translate-y-1/2 w-6 h-6 text-gray-400" />
              <input
                type="search"
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="Search services, providers..."
                className="input pl-12 pr-12 text-lg py-3"
                autoFocus
              />
              {query && (
                <button type="button" onClick={() => setQuery('')} className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                  <X className="w-5 h-5" />
                </button>
              )}
            </div>
          </form>
        </div>
        <div className="container px-4 pb-4">
          <div className="flex items-center justify-between">
            <div className="flex gap-2">
              <button onClick={() => setActiveTab('services')} className={`px-4 py-2 rounded-lg text-sm font-medium ${activeTab === 'services' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}>
                Services ({results.services?.length || 0})
              </button>
              <button onClick={() => setActiveTab('providers')} className={`px-4 py-2 rounded-lg text-sm font-medium ${activeTab === 'providers' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}>
                Providers ({results.providers?.length || 0})
              </button>
            </div>
            <button onClick={() => setShowFilters(!showFilters)} className="btn-secondary flex items-center gap-2">
              <Filter className="w-4 h-4" />
              Filters
            </button>
          </div>

          {showFilters && (
            <div className="mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200 animate-slide-down">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-semibold">Filters</h3>
                <button onClick={clearFilters} className="text-sm text-primary-600 hover:underline">Clear all</button>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                  <label className="label">Category</label>
                  <select value={filters.category} onChange={e => setFilters({...filters, category: e.target.value})} className="input">
                    <option value="">All Categories</option>
                    {categories.slice(1).map(c => <option key={c} value={c.toLowerCase()}>{c}</option>)}
                  </select>
                </div>
                <div>
                  <label className="label">Min Price</label>
                  <input type="number" value={filters.minPrice} onChange={e => setFilters({...filters, minPrice: Number(e.target.value)})} className="input" min="0" max="500" />
                </div>
                <div>
                  <label className="label">Max Price</label>
                  <input type="number" value={filters.maxPrice} onChange={e => setFilters({...filters, maxPrice: Number(e.target.value)})} className="input" min="0" max="500" />
                </div>
                <div>
                  <label className="label">Min Rating</label>
                  <select value={filters.rating} onChange={e => setFilters({...filters, rating: Number(e.target.value)})} className="input">
                    <option value={0}>Any</option>
                    <option value={4}>4+ Stars</option>
                    <option value={4.5}>4.5+ Stars</option>
                  </select>
                </div>
              </div>
            </div>
          )}
        </div>
      </header>

      <main className="container py-8">
        {query ? (
          <>
            <p className="text-gray-600 mb-6">Showing results for <span className="font-medium text-gray-900">"{query}"</span></p>

            {loading ? (
              <div className="grid md:grid-cols-3 gap-6">
                {[1,2,3,4,5,6].map(i => (
                  <div key={i} className="card animate-pulse">
                    <div className="aspect-video bg-gray-200" />
                    <div className="p-4 space-y-3">
                      <div className="h-4 bg-gray-200 rounded w-3/4" />
                      <div className="h-4 bg-gray-200 rounded w-1/2" />
                      <div className="h-6 bg-gray-200 rounded w-full" />
                    </div>
                  </div>
                ))}
              </div>
            ) : activeTab === 'services' ? (
              results.services.length === 0 ? (
                <div className="text-center py-16">
<SearchIcon className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900">No services found</h3>
                  <p className="text-gray-500 mt-1">Try different keywords or filters</p>
                </div>
              ) : (
                <div className="grid md:grid-cols-3 gap-6">
                  {results.services.map(service => (
                    <Link key={service._id} to={`/services/${service._id}`} className="card hover:shadow-lg transition-shadow overflow-hidden">
                      <div className="aspect-video bg-gray-100 relative">
                        {service.images?.[0] ? <img src={service.images[0]} alt={service.title} className="w-full h-full object-cover" /> : <div className="w-full h-full flex items-center justify-center text-4xl">🔧</div>}
                        <span className="absolute top-2 right-2 badge bg-white/90 backdrop-blur">{service.category}</span>
                      </div>
                      <div className="p-4">
                        <h3 className="font-semibold text-gray-900 line-clamp-1">{service.title}</h3>
                        <p className="text-sm text-gray-500 mt-1 line-clamp-2">{service.description}</p>
                        <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
                          <div className="flex items-center gap-2">
                            <Star className="w-4 h-4 text-yellow-500 fill-current" />
                            <span className="text-sm font-medium">{service.rating?.toFixed(1) || '4.5'}</span>
                          </div>
                          <div className="text-right">
                            <p className="text-lg font-bold text-primary-600">${service.price}</p>
                            <p className="text-xs text-gray-500">/{service.priceType === 'hourly' ? 'hr' : 'job'}</p>
                          </div>
                        </div>
                      </div>
                    </Link>
                  ))}
                </div>
              )
            ) : (
              results.providers.length === 0 ? (
                <div className="text-center py-16">
                  <Users className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900">No providers found</h3>
                  <p className="text-gray-500 mt-1">Try different keywords or filters</p>
                </div>
              ) : (
                <div className="grid md:grid-cols-3 gap-6">
                  {results.providers.map(provider => (
                    <Link key={provider._id} to={`/profile/${provider._id}`} className="card hover:shadow-lg transition-shadow p-6 text-center">
                      <div className="w-20 h-20 rounded-full bg-primary-100 flex items-center justify-center mx-auto mb-4">
                        {provider.avatar ? <img src={provider.avatar} alt="" className="w-20 h-20 rounded-full" /> : <span className="text-3xl font-bold text-primary-600">{provider.name?.[0]}</span>}
                      </div>
                      <h3 className="font-semibold text-gray-900">{provider.name}</h3>
                      <p className="text-sm text-gray-500 mt-1">{provider.reviewCount || 0} reviews</p>
                      <div className="flex items-center justify-center gap-2 mt-2">
                        <Star className="w-4 h-4 text-yellow-500 fill-current" />
                        <span className="font-medium">{provider.rating?.toFixed(1) || '4.5'}</span>
                      </div>
                      <div className="flex items-center justify-center gap-4 mt-3 text-sm text-gray-500">
                        <span className="flex items-center gap-1"><Award className="w-4 h-4" /> Verified</span>
                        <span className="flex items-center gap-1"><MapPinIcon className="w-4 h-4" /> {provider.address || 'Local'}</span>
                      </div>
                    </Link>
                  ))}
                </div>
              )
            )}
          </>
        ) : (
          <div className="text-center py-16">
            <Search className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h2 className="text-2xl font-bold text-gray-900">Search for Services</h2>
            <p className="text-gray-600 mt-2 max-w-xl mx-auto">Find trusted professionals for plumbing, electrical, cleaning, and more. Enter keywords above to get started.</p>
            <div className="mt-8 flex flex-wrap justify-center gap-2">
              {categories.slice(1, 7).map(cat => (
                <Link key={cat} to={`/services?category=${cat.toLowerCase()}`} className="badge bg-white border border-gray-200 hover:border-primary-300 hover:text-primary-600 transition-colors px-4 py-2">
                  {cat}
                </Link>
              ))}
            </div>
          </div>
        )}
      </main>
    </div>
  );
}