'use client';

import { useState, useCallback } from 'react';
import dynamic from 'next/dynamic';
import { Hotel } from '@/features/search/types';
import Link from 'next/link';
import Image from 'next/image';
import { useSearchParams } from 'next/navigation';
import { useAppSelector } from '@/store/hooks';
import { Tooltip, TooltipArrow, TooltipContent, TooltipPortal, TooltipProvider, TooltipTrigger } from "@radix-ui/react-tooltip"
import { AddToWishlistButton } from '../hotel-details/AddToWishlistButton';
import { assetPath } from '@/utils/assets';
import { sendFunnelEvent } from '@/utils/tracking';

/** One shared chunk; only mounted after hover so SRP does not init N Swipers on load. */
const HotelCardCarousel = dynamic(() => import('./HotelCardCarousel'), { ssr: false });
import { trackMetaPixelCustomEvent } from '@/lib/meta-pixel';
import HotelCardV3 from './v3/HotelCardV3';
import HotelCardOfferDetails from './HotelCardOfferDetails';
import HotelCardLocationMeta from './HotelCardLocationMeta';

interface HotelCardProps {
  hotel: Hotel;
  index: number;
  onLoginClick?: () => void;
  /** When provided and hotel has wishlistId, shows remove-from-wishlist button */
  onRemoveFromWishlist?: (wishlistId: number) => void;
  /** SRP batch lookup result (disables per-card lookup calls) */
  wishlistLookup?: { wishlistItemId: number | null; wishlistName?: string };
  /** When true, disables per-card lookup calls (SRP uses batch lookup instead). */
  disableWishlistAutoLookup?: boolean;
}

export default function HotelCard({ hotel, index, onLoginClick, onRemoveFromWishlist, wishlistLookup, disableWishlistAutoLookup }: HotelCardProps) {
  const isV3 = process.env.NEXT_PUBLIC_DESIGN_VERSION === 'v3'; // Temporary flag to switch between v2 and v3 card while we roll out the new design
  const searchParams = useSearchParams();
  const user = useAppSelector((state) => state.auth.user);
  const presence = useAppSelector((state) => state.srp.presenceData[String(hotel.id)]);
  const isAuthenticated = !!user;
  const [wishlistState, setWishlistState] = useState<{ wishlistItemId: number | null; wishlistName: string } | null>(null);
  const effectiveWishlistItemId = wishlistState?.wishlistItemId ?? wishlistLookup?.wishlistItemId ?? null;
  const effectiveWishlistName = wishlistState?.wishlistName ?? wishlistLookup?.wishlistName ?? '';
  const [carouselActive, setCarouselActive] = useState(false);
  const activateCarousel = useCallback(() => {
    if (hotel.images.length > 1) setCarouselActive(true);
  }, [hotel.images.length]);
  const primaryImage = hotel.images[0] ?? assetPath('/assets/img/no-image.png');

  // Get query params: prefer hotel.searchParams (from wishlist) over current page params
  const queryParams = (() => {
    const params = new URLSearchParams(searchParams.toString());

    // Always replace hotel-details specific params to avoid duplicates/stale values.
    params.delete('hotelId');
    params.delete('lat');
    params.delete('lng');
    params.set('hotelId', hotel.id);
    if (hotel.address?.latitude && hotel.address?.longitude) {
      params.set('lat', String(hotel.address.latitude));
      params.set('lng', String(hotel.address.longitude));
    }

    // When card carries booking params (e.g. wishlist), prefer those values,
    // but still keep unknown params from current URL (utm_*, etc.).
    if (hotel.searchParams) {
      if (hotel.searchParams.checkinDate) params.set('checkinDate', hotel.searchParams.checkinDate);
      if (hotel.searchParams.checkoutDate) params.set('checkoutDate', hotel.searchParams.checkoutDate);
      if (hotel.searchParams.rooms != null) params.set('rooms', String(hotel.searchParams.rooms));
      if (hotel.searchParams.adults != null) params.set('adults', String(hotel.searchParams.adults));
      if (hotel.searchParams.children != null && hotel.searchParams.children !== '') {
        params.set('children', hotel.searchParams.children);
      }
    }

    return params.toString();
  })();
  const hotelDetailsUrl = `/hotel-details${queryParams ? `?${queryParams}` : ''}`;

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }).map((_, i) => (
      <svg
        key={i}
        className={`iconSize-15 stars-svg ${i < rating ? 'active' : ''}`}
        xmlns="http://www.w3.org/2000/svg"
        version="1.1"
        viewBox="0 0 105 100"
      >
        <path className="star" d="M57.8,5.9l12.1,24.5,27.1,3.9c4.9.8,6.8,6.7,3.3,10.2l-19.6,19.1,4.7,26.9c.9,4.9-4.3,8.6-8.6,6.3l-24.2-12.7-24.2,12.7c-4.4,2.3-9.4-1.4-8.7-6.3l4.7-26.9L4.8,44.6c-3.5-3.4-1.6-9.4,3.3-10.2l27.1-3.9,12.1-24.5c2.1-4.4,8.4-4.4,10.7,0h-.1Z" />
      </svg>
    ));
  };

  const handleRemoveFromWishlist = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (hotel.wishlistId != null && onRemoveFromWishlist) onRemoveFromWishlist(hotel.wishlistId);
  };

  const handleHotelCardClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    if (e.defaultPrevented) {
      return;
    }
    trackMetaPixelCustomEvent('SeeAvailabilityClick');
  };

  if (isV3) return <HotelCardV3 hotel={hotel} index={index} onLoginClick={onLoginClick} onRemoveFromWishlist={onRemoveFromWishlist} wishlistLookup={wishlistLookup} disableWishlistAutoLookup={disableWishlistAutoLookup} />;

  return (
    <div className={`cols-listing ${hotel.isSponsored ? 'sponsered-listing' : ''} mb-3`}>
      <div className="card listing-card rounded-start-3 w-100 shadow-sm p-0" style={{ overflow: 'hidden', position: 'relative' }}>
        {hotel.wishlistId != null && onRemoveFromWishlist && (
          <button
            type="button"
            onClick={handleRemoveFromWishlist}
            className="position-absolute top-0 end-0 m-2 rounded-circle border-0 bg-white shadow-sm d-flex align-items-center justify-content-center z-1"
            style={{ width: 36, height: 36 }}
            aria-label="Remove from wishlist"
            title="Remove from wishlist"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 16 16">
              <path d="M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854Z" />
            </svg>
          </button>
        )}
        <Link
          href={hotelDetailsUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="text-decoration-none"
          style={{ position: 'relative', display: 'block' }}
          onClick={(e) => {
            sendFunnelEvent('SEE_AVAILABILITY_CLICK', {
              hotelId: String(hotel.id),
              hotelName: hotel.name,
            });
            handleHotelCardClick(e);
          }}
        >
          <div className="row listing-row g-0" style={{ minHeight: 'auto' }}>
            {/* Image Carousel */}
            <div
              className="listing-col-h col-xxl-3 col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 p-2 p-md-3 pe-2 pe-md-0"
              style={{ height: 'auto' }}
              onMouseEnter={activateCarousel}
              onFocus={activateCarousel}
            >
              {carouselActive && hotel.images.length > 1 ? (
                <HotelCardCarousel images={hotel.images} index={index} />
              ) : (
                <div
                  className="leisure-properties-carousel h-imgs-carousel position-relative"
                  style={{ height: '200px', minHeight: '200px', maxHeight: '200px' }}
                >
                  <Image
                    src={primaryImage}
                    width={300}
                    height={200}
                    className="d-block w-100 h-100"
                    alt={hotel.name}
                    priority={index < 2}
                    loading={index < 2 ? 'eager' : 'lazy'}
                    style={{ objectFit: 'cover', maxHeight: '200px' }}
                  />
                </div>
              )}
            </div>

            {/* Hotel Details */}
            <div className="listing-col-h col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 booking-content-details p-2 p-md-3" style={{ height: 'auto', minHeight: 'auto' }}>
              {/* Sponsored/Luxe Badges */}
              {(hotel.isSponsored || hotel.isLuxe) && (
                <div className="sponserd-section mb-2">
                  {hotel.isSponsored && (
                    <div className="sponserBy">
                      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" className="bi bi-arrow-up-right" viewBox="0 0 16 16">
                        <path fillRule="evenodd" d="M14 2.5a.5.5 0 0 0-.5-.5h-6a.5.5 0 0 0 0 1h4.793L2.146 13.146a.5.5 0 0 0 .708.708L13 3.707V8.5a.5.5 0 0 0 1 0z" />
                      </svg>
                      <span>SPONSERED</span>
                    </div>
                  )}
                  {hotel.isLuxe && (
                    <div className="luxeIcon">
                      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" className="bi bi-star-fill" viewBox="0 0 16 16">
                        <path d="M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z" />
                      </svg>
                      <span>LES/Luxe</span>
                    </div>
                  )}
                </div>
              )}

              {/* Name and Rating — list: name left / stars right; grid stacks via CSS */}
              <div className="hotel-card-title-row d-flex justify-content-between align-items-start gap-2 mb-2">
                <h3 className="subHeading text-capitalize color-text-dark fw-semibold mb-0">
                  {hotel.name}
                </h3>
                <div className="rating-stars flex-shrink-0"> development
                  {renderStars(hotel.starRating)}
                </div>
              </div>

              {/* Location: address | Show on map | nearby landmark */} development
              <HotelCardLocationMeta hotel={hotel} />

              {/* Amenities */}
              {hotel.amenities.length > 0 && (
                <ul className="d-flex flex-wrap justify-content-start align-items-center column-gap-2 row-gap-1 p-0 mb-2 amenities-list">
                  {hotel.amenities.slice(0, 3).map((amenity, idx) => (
                    <li key={idx} className="fw-medium">
                      {amenity}
                    </li>
                  ))}

                  {hotel.amenities.length > 3 && <TooltipProvider>
                    <Tooltip delayDuration={0}>
                      <TooltipTrigger asChild>
                        <li className="fw-medium position-relative amenity-more">
                          + {hotel.amenities.length - 3}
                        </li>
                      </TooltipTrigger>
                      <TooltipPortal>
                        <TooltipContent className="amenity-tooltip" sideOffset={5}>
                          {hotel.amenities.slice(3).join(', ')}
                          <TooltipArrow className='amenity-tooltip-arrow' />
                        </TooltipContent>
                      </TooltipPortal>
                    </Tooltip>
                  </TooltipProvider>}
                </ul>
              )}

              <HotelCardOfferDetails offer={hotel.featuredOffer} />

              {/* Features not covered by the priced offer */}
              {(hotel.hasBookNowPayLater ||
                (hotel.hasFreeCancellation &&
                  !hotel.featuredOffer?.highlights.some((line) =>
                    /free cancellation/i.test(line)
                  ))) && (
                <ul className="p-0 mb-2">
                  {hotel.hasFreeCancellation &&
                    !hotel.featuredOffer?.highlights.some((line) =>
                      /free cancellation/i.test(line)
                    ) && (
                      <li className="color-text-first fw-medium">✓ Free Cancellation</li>
                    )}
                  {hotel.hasBookNowPayLater && (
                    <li className="color-text-first fw-medium">✓ Book Now Pay Later</li>
                  )}
                </ul>
              )}


              {/* Live viewer count */}
              {presence?.viewerCount > 0 && (
                <p className="d-flex align-items-center gap-1 mb-0" style={{ fontSize: '0.78rem', color: '#e05c00' }}>
                  <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM8 11a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/>
                  </svg>
                  {presence.viewerCount} {presence.viewerCount === 1 ? 'person' : 'people'} viewing this hotel
                </p>
              )}
 development
            </div>

            {/* Pricing */}
            <div className="listing-col-h col-xxl-3 col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 border-start no-grid position-relative" style={{ height: 'auto', minHeight: 'auto' }}>

              <div className={` listing-col-h d-flex align-items-end text-end flex-column p-2 p-md-3 h-100 justify-content-start ${hotel.isPriceAvailable !== false ? 'justify-content-between' : 'gap-5'}`}>
                {/* Rating - always shown */}
                <div className="listing-div text-end d-flex justify-content-between align-items-end text-end flex-column mb-2 w-100">
                  <div className='mb-2'>
                    <AddToWishlistButton
                      hotelId={hotel.id}
                      checkinDate={hotel.searchParams?.checkinDate}
                      checkoutDate={hotel.searchParams?.checkoutDate}
                      disableAutoLookup={!!disableWishlistAutoLookup}
                      initialWishlistItemId={wishlistLookup?.wishlistItemId}
                      initialWishlistName={wishlistLookup?.wishlistName}
                      controlledWishlistItemId={effectiveWishlistItemId}
                      controlledWishlistName={effectiveWishlistName}
                      onWishlistStateChange={setWishlistState}
                    />
                  </div>
                  {hotel.avgOverallRating > 0 && <>
                    <h5 className="color-text-first fw-semibold mb-2 d-flex align-items-center justify-content-end">
                      {hotel.avgOverallRating >= 4.5 ? 'Excellent' : hotel.avgOverallRating >= 4 ? 'Very Good' : 'Good'}
                      <span className="rating-avg-number bgColor-first-same mb-0 ms-1">{parseFloat(String(hotel.avgOverallRating)).toFixed(1)}</span>
                    </h5>
                    {hotel.reviewCount > 0 && <small className="d-block">({hotel.reviewCount} Ratings)</small>}
                  </>}
                </div>

                {hotel.isPriceAvailable !== false ? (
                  <>
                    <div className="listing-div text-end d-flex justify-content-between align-items-end text-end flex-column">
                      {hotel.isLimitedOffer && (
                        <small className="d-block limited-time-offer mb-2">Limited Time Offer</small>
                      )}
                      {hotel.originalPrice != null && hotel.originalPrice > hotel.price && (
                        <small className="d-block text-muted mb-0" style={{ fontSize: '0.85rem' }}>
                          <span style={{ textDecoration: 'line-through', color: "#FF0000" }}>${hotel.originalPrice.toLocaleString()}</span>
                        </small>
                      )}
                      <span className="mainHeading color-text-dark fw-bold">${hotel.price.toLocaleString()}</span>
                      <small className="d-block color-text-dark mb-0">+${hotel.taxes} taxes & fees</small>
                      <small className="d-block color-text-dark mb-2">Per Night</small>
                    </div>
                  </>
                ) : (
                  <div className="listing-div text-end d-flex justify-content-end align-items-end flex-column w-100">
                    <h6 className="fw-semibold color-text-second mb-1">You Just Missed It</h6>
                    <small className="d-block text-muted">
                      {hotel.unavailableReason || 'Not available for selected dates on Leisure.'}
                    </small>
                  </div>
                )}
                <span
                  className="see-availability-btn buttons btnColor-first text-md lh-base my-3 ls-0 py-1 px-3 rounded-2 li d-inline-flex align-items-center gap-1"
                >
                  See Availability
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="14" height="14"
                    viewBox="0 0 1024 1024"
                    className="icon"
                  >
                    <path
                      fill="#fff"
                      d="M338.752 104.704a64 64 0 000 90.496l316.8 316.8-316.8 316.8a64 64 0 0090.496 90.496l362.048-362.048a64 64 0 000-90.496L429.248 104.704a64 64 0 00-90.496 0z"
                    />
                  </svg>
                </span>
              </div>
            </div>

            {/* Pricing for Mobile */}
            <div className='no-list'>
              <div className='mb-2 d-flex justify-content-end px-2'>
                <AddToWishlistButton
                  hotelId={hotel.id}
                  checkinDate={hotel.searchParams?.checkinDate}
                  checkoutDate={hotel.searchParams?.checkoutDate}
                  disableAutoLookup={!!disableWishlistAutoLookup}
                  initialWishlistItemId={wishlistLookup?.wishlistItemId}
                  initialWishlistName={wishlistLookup?.wishlistName}
                  controlledWishlistItemId={effectiveWishlistItemId}
                  controlledWishlistName={effectiveWishlistName}
                  onWishlistStateChange={setWishlistState}
                />
              </div>
              {hotel.isPriceAvailable !== false ? (
                <div className="d-flex justify-content-between align-items-end text-end flex-column p-2 pb-3">
                  <div className="listing-div text-end d-flex justify-content-between align-items-end text-end flex-column">
                    {hotel.originalPrice != null && hotel.originalPrice > hotel.price && (
                      <small className="d-block text-muted mb-0" style={{ fontSize: '0.85rem' }}>
                        <span style={{ textDecoration: 'line-through', color: "#FF0000" }}>${hotel.originalPrice.toLocaleString()}</span>
                      </small>
                    )}
                    <span className="mainHeading color-text-dark fw-bold">${hotel.price.toLocaleString()}</span>
                    <small className="d-block color-text-dark mb-0">+${hotel.taxes} taxes & fees</small>
                    <small className="d-block color-text-dark mb-2">Per Night</small>
                  </div>
                </div>
              ) : (
                <div className="d-flex justify-content-center align-items-center text-center flex-column p-2 pb-3">
                  <div className="listing-div text-center d-flex justify-content-center align-items-center flex-column">
                    <div className="unavailable-badge d-flex gap-2 align-items-center mb-1">
                      <h5 className="fw-semibold color-text-second">You Just Missed It</h5>
                    </div>

                    <small className="d-block text-muted px-2">
                      {hotel.unavailableReason || 'Not available for selected dates on Leisure.'}
                    </small>
                  </div>
                </div>
              )}
            </div>
          </div>
        </Link>
      </div>
    </div>
  );
}
