import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Search, MapPin, ChevronDown, SlidersHorizontal, Briefcase, Phone, Star } from 'lucide-react';

export default function EventServicesPage() {
  const [services, setServices] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Search filters
  const [searchFilters, setSearchFilters] = useState({
    serviceType: '',
    location: '',
    searchText: '',
    minPrice: '',
    maxPrice: '',
    experience: '',
    rating: '',
    availability: '',
    sortBy: 'newest'
  });

  //dummy services
  const dummyServices = [
    {
      id: "1",
      createdAt: "2026-01-10T14:30:00Z",
      businessName: "Elegant Weddings & Events",
      serviceType: "Wedding Planner",
      contact: "+1 (555) 123-4567",
      email: "contact@elegantweddings.com",
      city: "New York",
      address: "123 Park Avenue, Manhattan",
      priceRange: "5000-15000",
      experience: "10+ years",
      rating: 4.8,
      reviews: 156,
      availability: "Available",
      specialties: ["Wedding Planning", "Destination Weddings", "Corporate Events"],
      description: "Full-service wedding and event planning with personalized attention to detail",
      image: "https://images.unsplash.com/photo-1519225421980-715cb0215aed?w=500&q=80"
    },
    {
      id: "2",
      createdAt: "2026-01-09T10:15:00Z",
      businessName: "Gourmet Catering Co.",
      serviceType: "Caterer",
      contact: "+1 (555) 234-5678",
      email: "info@gourmetcatering.com",
      city: "Los Angeles",
      address: "456 Sunset Blvd, Hollywood",
      priceRange: "2000-8000",
      experience: "8 years",
      rating: 4.9,
      reviews: 203,
      availability: "Available",
      specialties: ["Wedding Catering", "Corporate Events", "Private Parties"],
      description: "Premium catering services with diverse menu options and exceptional presentation",
      image: "https://images.unsplash.com/photo-1555244162-803834f70033?w=500&q=80"
    },
    {
      id: "3",
      createdAt: "2026-01-08T16:45:00Z",
      businessName: "Blooms & Decor Studio",
      serviceType: "Decorator",
      contact: "+1 (555) 345-6789",
      email: "hello@bloomsdecor.com",
      city: "Chicago",
      address: "789 Michigan Ave, Downtown",
      priceRange: "3000-12000",
      experience: "12 years",
      rating: 4.7,
      reviews: 187,
      availability: "Booked",
      specialties: ["Floral Design", "Stage Decoration", "Theme Decor"],
      description: "Creative event decoration and floral arrangements for memorable occasions",
      image: "https://images.unsplash.com/photo-1478146896981-b80fe463b330?w=500&q=80"
    },
    {
      id: "4",
      createdAt: "2026-01-08T09:20:00Z",
      businessName: "Memories Photography",
      serviceType: "Photographer",
      contact: "+1 (555) 456-7890",
      email: "bookings@memoriesphotography.com",
      city: "Houston",
      address: "321 Main Street, Downtown",
      priceRange: "1500-5000",
      experience: "7 years",
      rating: 4.9,
      reviews: 241,
      availability: "Available",
      specialties: ["Wedding Photography", "Event Coverage", "Candid Shots"],
      description: "Professional photography services capturing your special moments beautifully",
      image: "https://images.unsplash.com/photo-1606216794074-735e91aa2c92?w=500&q=80"
    },
    {
      id: "5",
      createdAt: "2026-01-07T12:00:00Z",
      businessName: "Dream Venues & Halls",
      serviceType: "Venue Provider",
      contact: "+1 (555) 567-8901",
      email: "reservations@dreamvenues.com",
      city: "Phoenix",
      address: "555 Convention Center Dr",
      priceRange: "8000-25000",
      experience: "15+ years",
      rating: 4.6,
      reviews: 98,
      availability: "Available",
      specialties: ["Wedding Venues", "Conference Halls", "Banquet Halls"],
      description: "Luxurious event venues with state-of-the-art facilities and flexible layouts",
      image: "https://images.unsplash.com/photo-1464366400600-7168b8af9bc3?w=500&q=80"
    },
    {
      id: "6",
      createdAt: "2026-01-06T18:30:00Z",
      businessName: "Beats & Melodies DJ",
      serviceType: "DJ & Entertainment",
      contact: "+1 (555) 678-9012",
      email: "bookings@beatsmelodies.com",
      city: "Philadelphia",
      address: "987 Music Row, Center City",
      priceRange: "800-3000",
      experience: "6 years",
      rating: 4.8,
      reviews: 167,
      availability: "Available",
      specialties: ["Wedding DJ", "Corporate Events", "Live Music"],
      description: "Professional DJ and entertainment services to keep your guests dancing all night",
      image: "https://images.unsplash.com/photo-1470229722913-7c0e2dbbafd3?w=500&q=80"
    },
    {
      id: "7",
      createdAt: "2026-01-06T08:45:00Z",
      businessName: "Sweet Celebrations Bakery",
      serviceType: "Cake Designer",
      contact: "+1 (555) 789-0123",
      email: "orders@sweetcelebrations.com",
      city: "San Antonio",
      address: "654 Baker Street, Old Town",
      priceRange: "500-3000",
      experience: "9 years",
      rating: 5.0,
      reviews: 289,
      availability: "Available",
      specialties: ["Wedding Cakes", "Custom Designs", "Dessert Tables"],
      description: "Custom cake designs and dessert services for unforgettable celebrations",
      image: "https://images.unsplash.com/photo-1535254973040-607b474cb50d?w=500&q=80"
    },
    {
      id: "8",
      createdAt: "2026-01-05T15:10:00Z",
      businessName: "Elite Event Coordinators",
      serviceType: "Event Designer",
      contact: "+1 (555) 890-1234",
      email: "info@eliteevents.com",
      city: "San Diego",
      address: "147 Harbor Drive, Gaslamp",
      priceRange: "4000-18000",
      experience: "11 years",
      rating: 4.7,
      reviews: 134,
      availability: "Booked",
      specialties: ["Event Design", "Theme Creation", "Luxury Events"],
      description: "Innovative event design and coordination for sophisticated celebrations",
      image: "https://images.unsplash.com/photo-1511795409834-ef04bbd61622?w=500&q=80"
    },
    {
      id: "9",
      createdAt: "2026-01-05T11:25:00Z",
      businessName: "Party Rental Paradise",
      serviceType: "Equipment Rental",
      contact: "+1 (555) 901-2345",
      email: "rentals@partyparadise.com",
      city: "Dallas",
      address: "258 Industrial Blvd, East Dallas",
      priceRange: "1000-6000",
      experience: "5 years",
      rating: 4.5,
      reviews: 112,
      availability: "Available",
      specialties: ["Furniture Rental", "Audio/Visual Equipment", "Tent & Canopy"],
      description: "Complete party and event equipment rental with delivery and setup services",
      image: "https://images.unsplash.com/photo-1530023367847-a683933f4172?w=500&q=80"
    },
    {
      id: "10",
      createdAt: "2026-01-04T13:50:00Z",
      businessName: "Makeup & Glam Studio",
      serviceType: "Makeup Artist",
      contact: "+1 (555) 012-3456",
      email: "bookings@makeupglam.com",
      city: "San Jose",
      address: "369 Beauty Lane, Downtown",
      priceRange: "300-1500",
      experience: "8 years",
      rating: 4.9,
      reviews: 276,
      availability: "Available",
      specialties: ["Bridal Makeup", "Party Makeup", "Hair Styling"],
      description: "Professional makeup and hair styling services for weddings and special events",
      image: "https://images.unsplash.com/photo-1487412947147-5cebf100ffc2?w=500&q=80"
    }
  ];

  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const itemsPerPage = 5;

  useEffect(() => {
    // Initialize with dummy data first
    setServices(dummyServices);
    setTotalPages(Math.ceil(dummyServices.length / itemsPerPage));
    setLoading(false);
    
    // Then try to fetch from API
    fetchServices();
  }, [searchFilters, currentPage]);

  const fetchServices = async () => {
    setLoading(true);
    
    // Always show dummy data while loading
    setServices(dummyServices);
    setTotalPages(Math.ceil(dummyServices.length / itemsPerPage));
    
    try {
      const params = new URLSearchParams({
        serviceType: searchFilters.serviceType,
        location: searchFilters.location,
        searchText: searchFilters.searchText,
        minPrice: searchFilters.minPrice,
        maxPrice: searchFilters.maxPrice,
        experience: searchFilters.experience,
        rating: searchFilters.rating,
        availability: searchFilters.availability,
        sortBy: searchFilters.sortBy,
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });

      const response = await fetch(`/api/event-services?${params}`);
      
      // Only process if we get a valid JSON response
      if (response.ok) {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          const data = await response.json();
          if (data.services && data.services.length > 0) {
            setServices(data.services);
            setTotalPages(Math.ceil((data.total || data.services.length) / itemsPerPage));
          }
        }
      }
    } catch (error) {
      // Silently fail and keep dummy data
      console.log('Using dummy data - API endpoint not yet implemented');
    } finally {
      setLoading(false);
    }
  };

  const handleSearchSubmit = (e) => {
    e.preventDefault();
    setCurrentPage(1);
  };

  const handleFilterChange = (filterName, value) => {
    setSearchFilters(prev => ({
      ...prev,
      [filterName]: value
    }));
    setCurrentPage(1);
  };

  const handleSearchInputChange = (filterName, value) => {
    setSearchFilters(prev => ({
      ...prev,
      [filterName]: value
    }));
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm mb-6">
        <div className="container-full mx-auto px-4 py-6">
          <h1 className="text-3xl font-bold mb-2 text-brand-green-dark">Event Services</h1>
          <p className="text-gray-600 mb-6">Find the best event management professionals for your celebration</p>

          {/* Search Bar */}
          <form onSubmit={handleSearchSubmit} className="flex flex-col md:flex-row gap-3">
            <div className="flex-1 relative">
              <select
                value={searchFilters.serviceType}
                onChange={(e) => handleSearchInputChange('serviceType', e.target.value)}
                className="w-full text-gray-500 px-4 py-3 border border-gray-400 rounded-lg appearance-none bg-white pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">All Services</option>
                <option value="Wedding Planner">Wedding Planner</option>
                <option value="Caterer">Caterer</option>
                <option value="Decorator">Decorator</option>
                <option value="Photographer">Photographer</option>
                <option value="Venue Provider">Venue Provider</option>
                <option value="DJ & Entertainment">DJ & Entertainment</option>
                <option value="Cake Designer">Cake Designer</option>
                <option value="Event Designer">Event Designer</option>
                <option value="Equipment Rental">Equipment Rental</option>
                <option value="Makeup Artist">Makeup Artist</option>
              </select>
              <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
            </div>

            <div className="flex-1 relative">
              <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Location"
                value={searchFilters.location}
                onChange={(e) => handleSearchInputChange('location', e.target.value)}
                className="w-full text-gray-500 pl-10 pr-4 py-3 border border-gray-400 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search services..."
                value={searchFilters.searchText}
                onChange={(e) => handleSearchInputChange('searchText', e.target.value)}
                className="w-full text-gray-500 pl-10 pr-4 py-3 border border-gray-400 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            <button
              type="submit"
              className="px-8 py-3 bg-brand-green cursor-pointer text-white rounded-lg hover:bg-brand-green-dark transition-colors font-medium flex items-center justify-center gap-2"
            >
              <Search className="w-5 h-5" />
              Search
            </button>
          </form>
        </div>
      </header>

      {/* Main Content */}
      <div className="container-full mx-auto px-4">
        <div className="flex flex-col lg:flex-row gap-6">
          {/* Left Sidebar - Filters */}
          <aside className="lg:w-64 flex-shrink-0">
            <div className="bg-white rounded-lg shadow-sm p-6 sticky top-4">
              <div className="flex items-center gap-2 mb-6">
                <SlidersHorizontal className="w-5 h-5 text-gray-700" />
                <h2 className="text-lg text-gray-700 font-bold">Filters</h2>
              </div>

              {/* Price Range */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Price Range ($)</h3>
                <div className="flex gap-2">
                  <input
                    type="number"
                    placeholder="Min"
                    value={searchFilters.minPrice}
                    onChange={(e) => handleFilterChange('minPrice', e.target.value)}
                    className="w-1/2 text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  <input
                    type="number"
                    placeholder="Max"
                    value={searchFilters.maxPrice}
                    onChange={(e) => handleFilterChange('maxPrice', e.target.value)}
                    className="w-1/2 text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* Experience */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Experience</h3>
                <select
                  value={searchFilters.experience}
                  onChange={(e) => handleFilterChange('experience', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Experience Levels</option>
                  <option value="1-3 years">1-3 years</option>
                  <option value="3-5 years">3-5 years</option>
                  <option value="5-10 years">5-10 years</option>
                  <option value="10+ years">10+ years</option>
                </select>
              </div>

              {/* Rating */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Minimum Rating</h3>
                <select
                  value={searchFilters.rating}
                  onChange={(e) => handleFilterChange('rating', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Ratings</option>
                  <option value="4.5">4.5+ Stars</option>
                  <option value="4.0">4.0+ Stars</option>
                  <option value="3.5">3.5+ Stars</option>
                  <option value="3.0">3.0+ Stars</option>
                </select>
              </div>

              {/* Availability */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Availability</h3>
                <select
                  value={searchFilters.availability}
                  onChange={(e) => handleFilterChange('availability', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All</option>
                  <option value="Available">Available Now</option>
                  <option value="Booked">Currently Booked</option>
                </select>
              </div>

              {/* Sort By */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Sort By</h3>
                <select
                  value={searchFilters.sortBy}
                  onChange={(e) => handleFilterChange('sortBy', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="newest">Newest First</option>
                  <option value="oldest">Oldest First</option>
                  <option value="rating-high">Highest Rated</option>
                  <option value="rating-low">Lowest Rated</option>
                  <option value="price-low">Price: Low to High</option>
                  <option value="price-high">Price: High to Low</option>
                  <option value="popular">Most Popular</option>
                </select>
              </div>

              {/* Reset Filters */}
              <button
                onClick={() => {
                  setSearchFilters({
                    serviceType: '',
                    location: '',
                    searchText: '',
                    minPrice: '',
                    maxPrice: '',
                    experience: '',
                    rating: '',
                    availability: '',
                    sortBy: 'newest'
                  });
                  setCurrentPage(1);
                }}
                className="w-full px-4 py-2 text-sm text-green-600 border border-green-600 rounded-lg hover:bg-green-50 transition-colors"
              >
                Reset All Filters
              </button>
            </div>
          </aside>

          {/* Right Content - Services Grid */}
          <main className="flex-1">
            {/* Results Info */}
            <div className="mb-4 flex items-center justify-between">
              <p className="text-gray-600">
                {loading ? 'Loading...' : `${services.length} services found`}
              </p>
            </div>

            {/* Services Grid */}
            {loading ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {[...Array(6)].map((_, i) => (
                  <div key={i} className="bg-white rounded-lg shadow animate-pulse">
                    <div className="h-48 bg-gray-200 rounded-t-lg"></div>
                    <div className="p-4">
                      <div className="h-4 bg-gray-200 rounded mb-2"></div>
                      <div className="h-6 bg-gray-200 rounded w-1/2 mb-2"></div>
                      <div className="h-3 bg-gray-200 rounded w-1/3"></div>
                    </div>
                  </div>
                ))}
              </div>
            ) : services.length === 0 ? (
              <div className="bg-white rounded-lg shadow-sm p-12 text-center">
                <p className="text-gray-500 text-lg">No services found matching your criteria</p>
                <p className="text-gray-400 text-sm mt-2">Try adjusting your filters or search terms</p>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {services.map((service) => (
                    <ServiceCard key={service.id} service={service} />
                  ))}
                </div>

                {/* Pagination */}
                {totalPages > 1 && (
                  <div className="mt-8 flex justify-center items-center gap-2 mb-8">
                    <button
                      onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                      disabled={currentPage === 1}
                      className="px-4 py-2 border text-green-600 border border-green-600 hover:bg-green-50 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Previous
                    </button>

                    <div className="flex gap-2">
                      {[...Array(totalPages)].map((_, i) => {
                        const page = i + 1;
                        if (
                          page === 1 ||
                          page === totalPages ||
                          (page >= currentPage - 1 && page <= currentPage + 1)
                        ) {
                          return (
                            <button
                              key={page}
                              onClick={() => setCurrentPage(page)}
                              className={`px-4 py-2 rounded-lg ${
                                currentPage === page
                                  ? 'bg-green-600 text-white border border-green-600'
                                  : 'border text-green-600 border border-green-600 hover:bg-green-50'
                              }`}
                            >
                              {page}
                            </button>
                          );
                        } else if (page === currentPage - 2 || page === currentPage + 2) {
                          return <span key={page} className="px-2 py-2">...</span>;
                        }
                        return null;
                      })}
                    </div>

                    <button
                      onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                      disabled={currentPage === totalPages}
                      className="px-4 py-2 border text-green-600 border border-green-600 hover:bg-green-50 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Next
                    </button>
                  </div>
                )}
              </>
            )}
          </main>
        </div>
      </div>
    </div>
  );
}

function ServiceCard({ service }) {
  return (
    <Link href={`/events/${service.id}`}>
      <div className="bg-white rounded-lg shadow hover:shadow-lg transition-shadow cursor-pointer overflow-hidden">
        <div className="h-48 bg-gray-200 relative">
          {service.image ? (
            <img
              src={service.image}
              alt={service.businessName}
              className="w-full h-full object-cover"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gray-300">
              <Briefcase className="w-20 h-20 text-gray-400" />
            </div>
          )}
          <span className="absolute top-2 left-2 px-3 py-1 text-white bg-blue-600 text-xs font-medium rounded-full shadow">
            {service.serviceType}
          </span>
          <span className={`absolute top-2 right-2 px-3 py-1 text-xs font-medium rounded-full shadow ${
            service.availability === 'Available' 
              ? 'bg-green-100 text-green-700' 
              : 'bg-red-100 text-red-700'
          }`}>
            {service.availability}
          </span>
        </div>
        <div className="p-4">
          <h3 className="font-bold text-lg mb-1 text-gray-800 line-clamp-1">{service.businessName}</h3>
          
          <div className="flex items-center mb-2">
            <Star className="w-4 h-4 text-yellow-500 fill-yellow-500 mr-1" />
            <span className="text-sm font-semibold text-gray-700">{service.rating}</span>
            <span className="text-xs text-gray-500 ml-1">({service.reviews} reviews)</span>
          </div>

          <div className="flex items-center text-sm text-gray-600 mb-1">
            <MapPin className="w-4 h-4 mr-1" />
            <span className="line-clamp-1">{service.city}</span>
          </div>
          
          <div className="flex items-center text-sm text-gray-600 mb-2">
            <Phone className="w-4 h-4 mr-1" />
            <span>{service.contact}</span>
          </div>

          <p className="text-sm text-gray-600 mb-2 line-clamp-2">
            {service.description}
          </p>

          <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-200">
            <div>
              <p className="text-xs text-gray-500">Price Range</p>
              <p className="text-sm font-bold text-green-600">
                ${service.priceRange.split('-')[0]} - ${service.priceRange.split('-')[1]}
              </p>
            </div>
            <div className="text-right">
              <p className="text-xs text-gray-500">Experience</p>
              <p className="text-sm font-semibold text-gray-700">{service.experience}</p>
            </div>
          </div>
        </div>
      </div>
    </Link>
  );
}