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

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

export default function Services() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [services, setServices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState(searchParams.get('category') || 'All');
  const [searchQuery, setSearchQuery] = useState(searchParams.get('search') || '');
  const [priceRange, setPriceRange] = useState([0, 500]);
  const [filtersOpen, setFiltersOpen] = useState(false);

  useEffect(() => {
    const params = new URLSearchParams();
    if (selectedCategory !== 'All') params.set('category', selectedCategory.toLowerCase());
    if (searchQuery) params.set('search', searchQuery);
    params.set('page', page);
    params.set('minPrice', priceRange[0]);
    params.set('maxPrice', priceRange[1]);
    setLoading(true);
    api.get(`/services?${params}`).then(res => {
      setServices(res.data.services);
      setTotal(res.data.total);
      setPages(res.data.pages);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [selectedCategory, searchQuery, page, priceRange]);

  const handleSearch = (e) => {
    e.preventDefault();
    setPage(1);
    setSearchParams({ search: searchQuery, category: selectedCategory !== 'All' ? selectedCategory.toLowerCase() : '' });
  };

  const clearFilters = () => {
    setSelectedCategory('All');
    setSearchQuery('');
    setPriceRange([0, 500]);
    setPage(1);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-white border-b border-gray-200 sticky top-16 z-40">
        <div className="container py-4">
          <form onSubmit={handleSearch} className="flex flex-col sm:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="search"
                placeholder="Search services..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                className="input pl-10"
              />
            </div>
            <div className="flex gap-2">
              <select
                value={selectedCategory}
                onChange={e => { setSelectedCategory(e.target.value); setPage(1); }}
                className="input w-auto min-w-[150px]"
              >
                {categories.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
              <button type="button" onClick={() => setFiltersOpen(!filtersOpen)} className="btn-secondary flex items-center gap-2">
                <Filter className="w-4 h-4" />
                Filters
              </button>
            </div>
          </form>

          {filtersOpen && (
            <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">Price Range</h3>
                <button onClick={clearFilters} className="text-sm text-primary-600 hover:underline">Clear all</button>
              </div>
              <div className="flex items-center gap-4">
                <input type="range" min="0" max="500" value={priceRange[0]} onChange={e => setPriceRange([Number(e.target.value), priceRange[1]])} className="flex-1" />
                <span className="text-sm text-gray-600 w-20">${priceRange[0]}</span>
                <input type="range" min="0" max="500" value={priceRange[1]} onChange={e => setPriceRange([priceRange[0], Number(e.target.value)])} className="flex-1" />
                <span className="text-sm text-gray-600 w-20">${priceRange[1]}</span>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="container py-8">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold">{selectedCategory !== 'All' ? selectedCategory : 'All'} Services</h1>
            <p className="text-gray-600">{total} services found</p>
          </div>
        </div>

        {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>
        ) : services.length === 0 ? (
          <div className="text-center py-16">
            <Search 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 adjusting your search or filters</p>
            <button onClick={clearFilters} className="mt-4 btn-outline">Clear Filters</button>
          </div>
        ) : (
          <>
            <div className="grid md:grid-cols-3 gap-6">
              {services.map(service => (
                <Link key={service._id} to={`/services/${service._id}`} className="card hover:shadow-lg transition-shadow overflow-hidden group">
                  <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 group-hover:scale-105 transition-transform duration-300" />
                    ) : (
                      <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>
                    {service.priceType === 'hourly' && (
                      <span className="absolute bottom-2 left-2 badge bg-white/90 backdrop-blur">Hourly</span>
                    )}
                  </div>
                  <div className="p-4">
                    <h3 className="font-semibold text-gray-900 line-clamp-1 group-hover:text-primary-600 transition-colors">{service.title}</h3>
                    <p className="text-sm text-gray-500 mt-1 line-clamp-2">{service.description}</p>
                    <div className="flex items-center gap-2 mt-2 text-xs text-gray-500">
                      {service.provider?.avatar && <img src={service.provider.avatar} alt="" className="w-5 h-5 rounded-full" />}
                      <span>{service.provider?.name || 'Provider'}</span>
                      <Star className="w-3 h-3 text-yellow-500 fill-current" />
                      <span>{service.rating?.toFixed(1) || '4.5'}</span>
                    </div>
                    <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
                      <div>
                        <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>
                      {service.duration && (
                        <div className="flex items-center gap-1 text-xs text-gray-500">
                          <Clock className="w-3 h-3" />
                          <span>{service.duration} hr</span>
                        </div>
                      )}
                    </div>
                  </div>
                </Link>
              ))}
            </div>

            {pages > 1 && (
              <div className="flex items-center justify-center gap-2 mt-8">
                <button
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className="btn-secondary"
                >
                  Previous
                </button>
                <span className="px-4 text-sm text-gray-600">Page {page} of {pages}</span>
                <button
                  onClick={() => setPage(p => Math.min(pages, p + 1))}
                  disabled={page === pages}
                  className="btn-secondary"
                >
                  Next
                </button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}