import React from 'react';
import { Link } from 'react-router-dom';
import {
  Users,
  Star,
  MapPin,
  Wifi,
  Tv,
  Wind,
  ArrowRight,
  Crown,
} from 'lucide-react';
import type { Room } from '../services/roomService';
import FavoriteButton from './FavoriteButton';
import { useFormatCurrency } from '../../payments/hooks/useFormatCurrency';

interface RoomCardProps {
  room: Room;
  compact?: boolean;
}

const RoomCard: React.FC<RoomCardProps> = ({ room, compact = false }) => {
  const roomType = room.room_type;
  const { formatCurrency } = useFormatCurrency();
  
  if (!roomType) {
    return null;
  }

  
  const imageUrl = (room.images && room.images.length > 0) 
    ? room.images[0] 
    : (roomType.images?.[0] || '/images/room-placeholder.jpg');
  
  
  const formattedPrice = formatCurrency(room.price || roomType.base_price);

  
  const normalizeAmenities = (input: unknown): string[] => {
    if (Array.isArray(input)) return input;
    if (!input) return [];
    if (typeof input === 'string') {
      try {
        const parsed = JSON.parse(input);
        if (Array.isArray(parsed)) return parsed;
      } catch {
        // Silently fail if JSON parsing fails - will fall back to comma-separated parsing
      }
      return input.split(',').map((s) => s.trim()).filter(Boolean);
    }
    if (typeof input === 'object') {
      try {
        const vals = Object.values(input);
        if (Array.isArray(vals) && vals.length > 0) return vals.flat().map((v: unknown) => String(v).trim());
      } catch {
        // Silently fail if JSON parsing fails - will fall back to comma-separated parsing
      }
    }
    return [];
  };

  const amenitiesSource =
    (room.amenities && normalizeAmenities(room.amenities).length > 0)
      ? normalizeAmenities(room.amenities)
      : normalizeAmenities(roomType.amenities);

  
  const amenities = amenitiesSource.slice(0, 3);

  
  const amenityIcons: Record<string, React.ReactNode> = {
    wifi: <Wifi className="w-4 h-4" />,
    tv: <Tv className="w-4 h-4" />,
    'air-conditioning': <Wind className="w-4 h-4" />,
  };

  return (
    <div 
      className={`luxury-card overflow-hidden group h-full flex flex-col
        border-t-2 transition-all duration-300
        ${room.featured 
          ? 'border-[var(--luxury-gold)] shadow-lg shadow-[var(--luxury-gold)]/20 hover:border-[var(--luxury-gold)] hover:shadow-luxury-gold' 
          : 'border-transparent hover:border-[var(--luxury-gold)] hover:shadow-luxury-gold'
        }`}
    >
      {}
      <div className={`relative overflow-hidden 
        bg-gradient-to-br from-gray-200 to-gray-300
        ${compact ? 'h-32 sm:h-36' : 'h-40 sm:h-44 md:h-48 lg:h-52'}`}
      >
        <img
          src={imageUrl}
          alt={roomType.name}
          loading="lazy"
          className="w-full h-full object-cover 
            group-hover:scale-110 transition-transform 
            duration-500 ease-out"
          onLoad={(e) => 
            e.currentTarget.classList.add('loaded')
          }
        />
        
        {}
        <div className="absolute inset-0 bg-gradient-to-t 
          from-black/60 via-transparent to-transparent 
          opacity-0 group-hover:opacity-100 transition-opacity 
          duration-300"
        />
        
        {}
        <div className="absolute top-3 right-3 z-10">
          <FavoriteButton roomId={room.id} size="md" />
        </div>
        
        {}
        {room.featured && (
          <div 
            className="absolute top-3 left-3 z-20
              bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
              text-[#0f0f0f] px-3 py-1.5 
              rounded-sm text-xs font-medium tracking-wide
              shadow-lg shadow-[var(--luxury-gold)]/30 backdrop-blur-sm
              flex items-center gap-1.5"
          >
            <Crown className="w-4 h-4 fill-[#0f0f0f] text-[#0f0f0f]" />
            <span>Featured</span>
          </div>
        )}

        {}
        <div 
          className={`absolute bottom-3 left-3 px-3 py-1.5 
            rounded-sm text-xs font-medium tracking-wide
            backdrop-blur-sm shadow-lg
            ${
              room.status === 'available'
                ? 'bg-green-500/90 text-white border border-green-400/50'
                : room.status === 'occupied'
                ? 'bg-red-500/90 text-white border border-red-400/50'
                : 'bg-gray-500/90 text-white border border-gray-400/50'
            }`}
        >
          {room.status === 'available'
            ? 'Available'
            : room.status === 'occupied'
            ? 'Occupied'
            : 'Maintenance'}
        </div>
      </div>

      {}
      <div className={`flex-1 flex flex-col ${compact ? 'p-3' : 'p-4 sm:p-5'}`}>
        {}
        <h3 className={`font-serif font-semibold text-gray-900 mb-1.5 tracking-tight
          ${compact ? 'text-base' : 'text-lg sm:text-xl'}
          flex items-center gap-2`}>
          {room.featured && (
            <Crown 
              className={`${compact ? 'w-4 h-4' : 'w-5 h-5'} 
                text-[var(--luxury-gold)] fill-[var(--luxury-gold)] 
                drop-shadow-lg animate-pulse`}
            />
          )}
          <span>{roomType.name}</span>
        </h3>

        {}
        <div 
          className={`flex items-center text-gray-600 font-light tracking-wide
            ${compact ? 'text-xs mb-1.5' : 'text-xs sm:text-sm mb-2'}`}
        >
          <MapPin className={`${compact ? 'w-3 h-3' : 'w-4 h-4'} mr-1.5 text-[var(--luxury-gold)]`} />
          <span>
            Room {room.room_number} - Floor {room.floor}
          </span>
        </div>

        {}
        {(room.description || roomType.description) && !compact && (
          <p className="text-gray-600 text-xs sm:text-sm mb-3 line-clamp-2 
            leading-relaxed font-light">
            {room.description || roomType.description}
          </p>
        )}

        {}
        <div className={`flex items-center justify-between ${compact ? 'mb-1.5' : 'mb-3'}`}>
          <div className="flex items-center text-gray-700">
            <Users className={`${compact ? 'w-3 h-3' : 'w-4 h-4'} mr-1.5 text-[var(--luxury-gold)]`} />
            <span className={`font-light tracking-wide ${compact ? 'text-xs' : 'text-sm'}`}>
              {room.capacity || roomType.capacity} guests
            </span>
          </div>

          {room.average_rating != null && (
            <div className="flex items-center">
              <Star
                className={`${compact ? 'w-3 h-3' : 'w-4 h-4'} text-[var(--luxury-gold)] mr-1`}
                fill="#d4af37"
              />
              <span className={`font-semibold text-gray-900 ${compact ? 'text-xs' : 'text-sm'}`}>
                {Number(room.average_rating).toFixed(1)}
              </span>
              {!compact && (
                <span className="text-xs text-gray-500 ml-1 font-light">
                  ({Number(room.total_reviews || 0)})
                </span>
              )}
            </div>
          )}
        </div>

        {}
        {amenities.length > 0 && !compact && (
          <div className="flex items-center gap-1.5 sm:gap-2 mb-3 sm:mb-4 flex-wrap">
            {amenities.map((amenity, index) => (
              <div
                key={index}
                className="flex items-center gap-1 
                  text-gray-700 text-xs bg-[var(--luxury-gold)]/10 
                  border border-[var(--luxury-gold)]/20
                  px-2 sm:px-2.5 py-1 sm:py-1.5 rounded-sm
                  font-light tracking-wide"
                title={amenity}
              >
                <span className="text-[var(--luxury-gold)]">
                  {amenityIcons[amenity.toLowerCase()] || 
                    <span>•</span>}
                </span>
                <span className="capitalize hidden sm:inline">{amenity}</span>
              </div>
            ))}
          </div>
        )}

        {}
        <div className={`flex flex-col sm:flex-row items-start sm:items-center justify-between mt-auto
          border-t border-gray-200
          ${compact ? 'gap-2 pt-2' : 'gap-2 sm:gap-3 pt-3'}`}>
          <div>
            {!compact && (
              <p className="text-xs text-gray-500 font-light tracking-wide mb-0.5">From</p>
            )}
            <p className={`font-serif font-semibold text-gradient-luxury tracking-tight
              ${compact ? 'text-lg' : 'text-lg sm:text-xl'}`}>
              {formattedPrice}
            </p>
            {!compact && (
              <p className="text-xs text-gray-500 font-light tracking-wide mt-0.5">/ night</p>
            )}
          </div>

          <Link
            to={`/rooms/${room.room_number}`}
            className={`btn-luxury-primary flex items-center gap-1.5 sm:gap-2 relative justify-center
              ${compact 
                ? 'text-xs px-3 py-1.5 w-full sm:w-auto' 
                : 'text-xs px-3 sm:px-4 py-1.5 sm:py-2 w-full sm:w-auto'}`}
          >
            <span className="relative z-10">View Details</span>
            <ArrowRight className={`relative z-10 ${compact ? 'w-3 h-3' : 'w-4 h-4'}`} />
          </Link>
        </div>
      </div>
    </div>
  );
};

export default RoomCard;
