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

export default function ClassifiedsPage() {
  const [ads, setAds] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // Search filters
  const [searchFilters, setSearchFilters] = useState({
    category: '',
    location: '',
    searchText: '',
    minPrice: '',
    maxPrice: '',
    condition: '',
    type: '',
    sortBy: 'newest'
  });


  //dummy ads
  const dummyADS = [
  {
    id: "1",
    createdAt: "2026-01-10T14:30:00Z",
    city: "New York",
    price: "850",
    condition: "Like New",
    title: "iPhone 15 Pro Max 256GB - Space Black",
    image: "https://images.unsplash.com/photo-1695048133142-1a20484d2569?w=500&q=80"
  },
  {
    id: "2",
    createdAt: "2026-01-09T10:15:00Z",
    city: "Los Angeles",
    price: "1200",
    condition: "Good",
    title: "MacBook Air M2 2023 - 8GB RAM 256GB SSD",
    image: "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=500&q=80"
  },
  {
    id: "3",
    createdAt: "2026-01-08T16:45:00Z",
    city: "Chicago",
    price: "15000",
    condition: "Good",
    title: "2018 Honda Civic EX - Low Mileage",
    image: "https://images.unsplash.com/photo-1619767886558-efdc259cde1a?w=500&q=80"
  },
  {
    id: "4",
    createdAt: "2026-01-08T09:20:00Z",
    city: "Houston",
    price: "450",
    condition: "New",
    title: "Samsung 55\" 4K Smart TV - Unopened Box",
    image: "https://images.unsplash.com/photo-1593359677879-a4bb92f829d1?w=500&q=80"
  },
  {
    id: "5",
    createdAt: "2026-01-07T12:00:00Z",
    city: "Phoenix",
    price: "2500",
    condition: "Fair",
    title: "Vintage Leather Sofa Set - 3 Seater + 2 Seater",
    image: "https://images.unsplash.com/photo-1555041469-a586c61ea9bc?w=500&q=80"
  },
  {
    id: "6",
    createdAt: "2026-01-06T18:30:00Z",
    city: "Philadelphia",
    price: "180",
    condition: "Like New",
    title: "Canon EOS Rebel T7 DSLR Camera with Lens",
    image: "https://images.unsplash.com/photo-1606980707496-eee6c67e0ad2?w=500&q=80"
  },
  {
    id: "7",
    createdAt: "2026-01-06T08:45:00Z",
    city: "San Antonio",
    price: "75",
    condition: "Good",
    title: "Mountain Bike - 21 Speed Shimano Gears",
    image: "https://images.unsplash.com/photo-1576435728678-68d0fbf94e91?w=500&q=80"
  },
  {
    id: "8",
    createdAt: "2026-01-05T15:10:00Z",
    city: "San Diego",
    price: "3200",
    condition: "New",
    title: "Gaming PC - RTX 4070, i7 13th Gen, 32GB RAM",
    image: "https://images.unsplash.com/photo-1587202372634-32705e3bf49c?w=500&q=80"
  },
  {
    id: "9",
    createdAt: "2026-01-05T11:25:00Z",
    city: "Dallas",
    price: "600",
    condition: "Good",
    title: "Queen Size Mattress with Box Spring - Memory Foam",
    image: "https://images.unsplash.com/photo-1631049307264-da0ec9d70304?w=500&q=80"
  },
  {
    id: "10",
    createdAt: "2026-01-04T13:50:00Z",
    city: "San Jose",
    price: "250",
    condition: "Like New",
    title: "PlayStation 5 Console with 2 Controllers",
    image: "https://images.unsplash.com/photo-1606144042614-b2417e99c4e3?w=500&q=80"
  }
];

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

  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    fetchAds();
  }, [searchFilters, currentPage]);

  const fetchCategories = async () => {
    try {
      const response = await fetch('/api/categories?module=classifieds');
      const data = await response.json();
      setCategories(data.categories || [
        { id: '2', value: 'matrimonial', name: 'Matrimonial' },
        { id: '3', value: 'electronics', name: 'Electronics' },
        { id: '4', value: 'vehicles', name: 'Vehicles' },
        { id: '5', value: 'property', name: 'Property' },
        { id: '6', value: 'jobs', name: 'Jobs' },
        { id: '7', value: 'services', name: 'Services' },
        { id: '8', value: 'events', name: 'Event Services' },
      ]);
    } catch (error) {
      console.error('Error fetching categories:', error);
    }
  };

  const fetchAds = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        categoryId: searchFilters.category,
        location: searchFilters.location,
        searchText: searchFilters.searchText,
        minPrice: searchFilters.minPrice,
        maxPrice: searchFilters.maxPrice,
        condition: searchFilters.condition,
        type: searchFilters.type,
        sortBy: searchFilters.sortBy,
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });

      const response = await fetch(`/api/classifieds/ads?${params}`);
      const data = await response.json();
      setAds(data.ads || dummyADS);
      setTotalPages(Math.ceil((data.total || dummyADS.length) / itemsPerPage));
    } catch (error) {
      console.error('Error fetching ads:', error);
      setAds([]);
    } finally {
      setLoading(false);
    }
  };

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

  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">Classified Ads</h1>
          <p className="text-gray-600 mb-6">Buy, sell, or trade items</p>

          {/* Search Bar */}
          <form onSubmit={handleSearchSubmit} className="flex flex-col md:flex-row gap-3">
            <div className="flex-1 relative">
              <select
                value={searchFilters.category}
                onChange={(e) => handleSearchInputChange('category', 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 Categories</option>
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {cat.name}
                  </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 ads..."
                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>

              {/* Condition */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Condition</h3>
                <select
                  value={searchFilters.condition}
                  onChange={(e) => handleFilterChange('condition', 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 Conditions</option>
                  <option value="new">New</option>
                  <option value="like-new">Like New</option>
                  <option value="good">Good</option>
                  <option value="fair">Fair</option>
                  <option value="poor">Poor</option>
                </select>
              </div>

              {/* Type */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Type</h3>
                <select
                  value={searchFilters.type}
                  onChange={(e) => handleFilterChange('type', 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 Types</option>
                  <option value="offer">Offer</option>
                  <option value="wanted">Wanted</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="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({
                    category: '',
                    location: '',
                    searchText: '',
                    minPrice: '',
                    maxPrice: '',
                    condition: '',
                    type: '',
                    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 - Ads Grid */}
          <main className="flex-1">
            {/* Results Info */}
            <div className="mb-4 flex items-center justify-between">
              <p className="text-gray-600">
                {loading ? 'Loading...' : `${ads.length} ads found`}
              </p>
            </div>

            {/* Ads 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>
            ) : ads.length === 0 ? (
              <div className="bg-white rounded-lg shadow-sm p-12 text-center">
                <p className="text-gray-500 text-lg">No ads 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">
                  {ads.map((ad) => (
                    <AdCard key={ad.id} ad={ad} />
                  ))}
                </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 hover:bg-gray-50 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 AdCard({ ad }) {
  return (
    <Link href={`/classifieds/${ad.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">
          {ad.image && (
            <img
              src={ad.image}
              alt={ad.title}
              className="w-full h-full object-cover"
            />
          )}
          {ad.condition && (
            <span className="absolute top-2 right-2 px-2 py-1 text-gray-700 bg-green-100 text-xs font-medium rounded-full shadow">
              {ad.condition}
            </span>
          )}
        </div>
        <div className="p-4">
          <h3 className="font-bold mb-2 line-clamp-2 text-gray-800">{ad.title}</h3>
          <p className="text-2xl font-bold text-blue-600 mb-2">
            ${ad.price}
          </p>
          <div className="flex items-center text-sm text-gray-600">
            <MapPin className="w-4 h-4 mr-1" />
            <span>{ad.city || 'Location not specified'}</span>
          </div>
          {ad.createdAt && (
            <p className="text-xs text-gray-400 mt-2">
              {new Date(ad.createdAt).toLocaleDateString()}
            </p>
          )}
        </div>
      </div>
    </Link>
  );
}