'use client';

import { useState, useEffect, useRef } from 'react';
import { Hotel, ViewMode } from '@/features/search/types';
import HotelCard from './HotelCard';
import AuthModal from '@/components/auth/AuthModal';
import { useWindowVirtualizer } from '@tanstack/react-virtual';

interface HotelsListProps {
  hotels: Hotel[];
  viewMode: ViewMode;
  onLoadMore?: () => void;
  hasMore?: boolean;
  isLoading?: boolean;
  /** Pagination fetch in progress — separate from initial search loading */
  isLoadingMore?: boolean;
  /** When false, suppresses auto infinite-scroll (e.g. while background pricing fills page 1) */
  enableAutoLoadMore?: boolean;
  /** Hide "No hotels found" while Amadeus pricing is still running in background */
  isPricingPending?: boolean;
  /** When set, cards with wishlistId show a remove-from-wishlist control */
  onRemoveFromWishlist?: (wishlistId: number) => void;
  /** Prefetched wishlist lookup state keyed by hotel id (property_code). */
  wishlistLookupByHotelId?: Record<string, { wishlistItemId: number | null; wishlistName?: string }>;
  /** When true, disables per-card lookup calls (SRP uses batch lookup instead). */
  disableWishlistAutoLookup?: boolean;
}

export default function HotelsList({
  hotels,
  viewMode,
  onLoadMore,
  hasMore = false,
  isLoading = false,
  isLoadingMore = false,
  enableAutoLoadMore = true,
  isPricingPending = false,
  onRemoveFromWishlist,
  wishlistLookupByHotelId,
  disableWishlistAutoLookup,
}: HotelsListProps) {
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authView, setAuthView] = useState<"signup" | "signin" | "otp">("signin");

  const handleLoginClick = () => {
    setShowAuthModal(true);
  };

  // For grid view, we have 3 cards per row, so virtualize by rows
  const itemsPerRow = viewMode === 'grid' ? 3 : 1;
  const rowCount = Math.ceil(hotels.length / itemsPerRow);

  // The virtualizer - use window scroll with useWindowVirtualizer
  const rowVirtualizer = useWindowVirtualizer({
    count: rowCount,
    estimateSize: () => 300, // Initial estimate, will be measured dynamically
    overscan: 5,
    measureElement: (element) => {
      // Measure the actual height of the element
      return element?.getBoundingClientRect().height ?? 300;
    },
  })

  // Remeasure all items when viewMode changes to recalculate heights
  useEffect(() => {
    rowVirtualizer.measure();
  }, [viewMode, rowVirtualizer]);

  const loadMoreSentinelRef = useRef<HTMLDivElement>(null);
  const sentinelWasVisibleRef = useRef(false);
  const onLoadMoreRef = useRef(onLoadMore);
  const isLoadingRef = useRef(isLoading);
  const isLoadingMoreRef = useRef(isLoadingMore);
  const hasMoreRef = useRef(hasMore);
  const enableAutoLoadMoreRef = useRef(enableAutoLoadMore);

  useEffect(() => {
    onLoadMoreRef.current = onLoadMore;
    isLoadingRef.current = isLoading;
    isLoadingMoreRef.current = isLoadingMore;
    hasMoreRef.current = hasMore;
    enableAutoLoadMoreRef.current = enableAutoLoadMore;
  });

  // Infinite scroll: only fire when the sentinel newly enters view (not while it stays visible)
  useEffect(() => {
    if (!hasMore || !enableAutoLoadMore || !onLoadMore) {
      sentinelWasVisibleRef.current = false;
      return;
    }

    const sentinel = loadMoreSentinelRef.current;
    if (!sentinel) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (!entry) return;

        const isVisible = entry.isIntersecting;
        const shouldLoad =
          isVisible &&
          !sentinelWasVisibleRef.current &&
          hasMoreRef.current &&
          enableAutoLoadMoreRef.current &&
          !isLoadingRef.current &&
          !isLoadingMoreRef.current;

        sentinelWasVisibleRef.current = isVisible;

        if (shouldLoad) {
          isLoadingMoreRef.current = true;
          onLoadMoreRef.current?.();
        }
      },
      { root: null, rootMargin: '240px 0px', threshold: 0 }
    );

    observer.observe(sentinel);
    return () => {
      observer.disconnect();
      sentinelWasVisibleRef.current = false;
    };
  }, [hasMore, enableAutoLoadMore]);

  return (
    <div className="listing-card-group">
      <div
        style={{
          height: `${rowVirtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {rowVirtualizer.getVirtualItems().map((virtualRow) => {
          const startIndex = virtualRow.index * itemsPerRow;
          const endIndex = Math.min(startIndex + itemsPerRow, hotels.length);
          const rowHotels = hotels.slice(startIndex, endIndex);

          return (
            <div
              key={virtualRow.key}
              data-index={virtualRow.index}
              ref={(node) => rowVirtualizer.measureElement(node)}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                transform: `translateY(${virtualRow.start - rowVirtualizer.options.scrollMargin}px)`,
              }}
            >
              <div className={`row rows-listing ${viewMode === 'grid' ? 'rows-grid' : 'rows-list'}`}>
                {rowHotels.map((hotel, idx) => (
                  <HotelCard
                    key={hotel.id}
                    hotel={hotel}
                    index={startIndex + idx}
                    onLoginClick={handleLoginClick}
                    onRemoveFromWishlist={onRemoveFromWishlist}
                    wishlistLookup={wishlistLookupByHotelId?.[String(hotel.id)]}
                    disableWishlistAutoLookup={disableWishlistAutoLookup}
                  />
                ))}
              </div>
            </div>
          );
        })}
      </div>
      {hasMore && enableAutoLoadMore && (
        <div ref={loadMoreSentinelRef} aria-hidden className="w-100" style={{ height: 1 }} />
      )}
      {/* Loading State */}
      {isLoadingMore && (
        <div className="text-center py-4">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
          <p className="mt-2 color-text-dark">Loading more hotels...</p>
        </div>
      )}

      {/* Load More Button */}
      {/* {hasMore && !isLoading && onLoadMore && (
        <div className="text-center">
          <button
            onClick={onLoadMore}
            className="buttons btnColor-second w-fit-content font-15 rounded-3 py-2 px-3 my-3 mx-auto"
          >
            Load more results
          </button>
        </div>
      )} */}

      {/* No Results — only when search finished and inventory is truly empty */}
      {hotels.length === 0 && !isLoading && !isPricingPending && (
        <div className="text-center py-5">
          <h3 className="color-text-dark fw-semibold mb-2">No hotels found</h3>
          <p className="color-text-dark">
            {onRemoveFromWishlist ? 'Your wishlist is empty. Add hotels from search or hotel details.' : 'Try adjusting your filters to see more results'}
          </p>
        </div>
      )}

      {showAuthModal && (
        <AuthModal
          view={authView}
          setView={setAuthView}
          onClose={() => setShowAuthModal(false)}
        />
      )}
    </div>
  );
}
