import { useState, useEffect, useCallback } from 'react';
import { Search, ChevronLeft, ChevronRight } from 'lucide-react';
import { RentalGrid } from '../components/rentals/RentalGrid';
import { RentalCategorySidebar } from '../components/rentals/RentalCategorySidebar';
import { api } from '../api/client';
import type { RentalListing } from '../types/rental';
import type { PaginatedResponse } from '../types';

type SortOption = 'newest' | 'price_asc' | 'price_desc' | 'popular';

export function RentalsPage() {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [sort, setSort] = useState<SortOption>('newest');
  const [rentals, setRentals] = useState<RentalListing[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 12;

  const fetchRentals = useCallback(async () => {
    setLoading(true);
    const params = new URLSearchParams({
      page: String(page),
      pageSize: String(pageSize),
      sort,
    });
    if (selectedCategory) params.set('category', selectedCategory as string);
    if (searchQuery) params.set('search', searchQuery);

    try {
      const res = await api.get<PaginatedResponse<RentalListing>>(`/rentals?${params}`);
      setRentals(res.data);
      setTotal(res.total);
      setTotalPages(res.totalPages);
    } catch {
      setRentals([]);
    } finally {
      setLoading(false);
    }
  }, [page, sort, selectedCategory, searchQuery]);

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

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(1);
  };

  const handleCategoryChange = (category: string | null) => {
    setSelectedCategory(category);
    setPage(1);
  };

  const handleSortChange = (value: string) => {
    setSort(value as SortOption);
    setPage(1);
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 py-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Browse Rentals</h1>

      <div className="flex gap-8">
        {/* Sidebar */}
        <aside className="hidden lg:block w-56 flex-shrink-0">
          <div className="sticky top-24">
            <RentalCategorySidebar selected={selectedCategory} onSelect={handleCategoryChange} />
          </div>
        </aside>

        {/* Main content */}
        <div className="flex-1">
          {/* Search and sort bar */}
          <div className="flex flex-col sm:flex-row gap-3 mb-6">
            <form onSubmit={handleSearch} className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search rentals..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2.5 rounded-xl border border-gray-200 bg-white text-sm
                    focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all"
                />
              </div>
            </form>
            <select
              value={sort}
              onChange={(e) => handleSortChange(e.target.value)}
              className="rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm text-gray-700
                focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none"
            >
              <option value="newest">Newest First</option>
              <option value="price_asc">Price: Low to High</option>
              <option value="price_desc">Price: High to Low</option>
              <option value="popular">Most Popular</option>
            </select>
          </div>

          {/* Results */}
          {loading ? (
            <p className="text-gray-500 text-center py-12">Loading rentals...</p>
          ) : rentals.length === 0 ? (
            <p className="text-gray-500 text-center py-12">No rentals found.</p>
          ) : (
            <RentalGrid rentals={rentals} />
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between mt-8">
              <p className="text-sm text-gray-500">
                Showing {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total}
              </p>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setPage(page - 1)}
                  disabled={page <= 1}
                  className="p-2 rounded-lg hover:bg-gray-100 disabled:opacity-30 cursor-pointer disabled:cursor-default transition-colors"
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>
                <span className="px-3 text-sm font-medium">{page} / {totalPages}</span>
                <button
                  onClick={() => setPage(page + 1)}
                  disabled={page >= totalPages}
                  className="p-2 rounded-lg hover:bg-gray-100 disabled:opacity-30 cursor-pointer disabled:cursor-default transition-colors"
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
