import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  Users,
  MapPin,
  ArrowLeft,
  Star,
  Calendar,
  Shield,
  Award,
  Sparkles,
} from 'lucide-react';
import { getRoomByNumber, type Room } from 
  '../../services/api/roomService';
import RoomGallery from '../../components/rooms/RoomGallery';
import RoomAmenities from '../../components/rooms/RoomAmenities';
import ReviewSection from '../../components/rooms/ReviewSection';
import CurrencyIcon from '../../components/common/CurrencyIcon';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import useAuthStore from '../../store/useAuthStore';

const RoomDetailPage: React.FC = () => {
  const { room_number } = useParams<{ room_number: string }>();
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const { userInfo } = useAuthStore();
  const [room, setRoom] = useState<Room | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (room_number) {
      fetchRoomDetail(room_number);
    }
  }, [room_number]);

  const fetchRoomDetail = async (roomNumber: string) => {
    try {
      setLoading(true);
      setError(null);
      const response = await getRoomByNumber(roomNumber);
      
      
      if ((response as any).success || (response as any).status === 'success') {
        if (response.data && response.data.room) {
          const fetchedRoom = response.data.room;
          
          
          if (fetchedRoom.room_number !== roomNumber) {
            console.error(`Room number mismatch: requested ${roomNumber}, got ${fetchedRoom.room_number}`);
            throw new Error(`Room data mismatch: expected room number ${roomNumber} but got ${fetchedRoom.room_number}`);
          }
          
          setRoom(fetchedRoom);
        } else {
          throw new Error('Failed to fetch room details');
        }
      } else {
        throw new Error('Failed to fetch room details');
      }
    } catch (err: any) {
      console.error('Error fetching room:', err);
      const message =
        err.response?.data?.message ||
        err.message ||
        'Unable to load room information';
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div 
        className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] w-screen relative -mt-6 -mb-6"
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          paddingTop: '1.5rem',
          paddingBottom: '1.5rem',
          zIndex: 1
        }}
      >
        <div className="w-full px-2 sm:px-4 md:px-6 lg:px-8 py-8 sm:py-12">
          <div className="animate-pulse space-y-6">
            <div className="h-[600px] bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-xl border border-[#d4af37]/20" />
            <div className="h-12 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg w-1/3 border border-[#d4af37]/10" />
            <div className="h-6 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg w-2/3 border border-[#d4af37]/10" />
          </div>
        </div>
      </div>
    );
  }

  if (error || !room) {
    return (
      <div 
        className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] w-screen relative -mt-6 -mb-6"
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          paddingTop: '1.5rem',
          paddingBottom: '1.5rem',
          zIndex: 1
        }}
      >
        <div className="w-full px-2 sm:px-4 md:px-6 lg:px-8 py-8 sm:py-12">
          <div className="bg-gradient-to-br from-red-900/20 to-red-800/10 
            border border-red-500/30 rounded-xl p-12 text-center 
            backdrop-blur-xl shadow-2xl shadow-red-500/10"
          >
            <p className="text-red-300 font-light text-lg mb-6 tracking-wide">
              {error || 'Room not found'}
            </p>
            <button
              onClick={() => navigate('/rooms')}
              className="inline-flex items-center gap-2 bg-gradient-to-r 
                from-[#d4af37] to-[#c9a227] text-[#0f0f0f] 
                px-6 py-3 rounded-sm hover:from-[#f5d76e] 
                hover:to-[#d4af37] transition-all duration-300 
                font-medium tracking-wide shadow-lg shadow-[#d4af37]/30"
            >
              <ArrowLeft className="w-5 h-5" />
              Back to Room List
            </button>
          </div>
        </div>
      </div>
    );
  }

  const roomType = room.room_type;
  const formattedPrice = formatCurrency(room?.price || roomType?.base_price || 0);

  return (
    <div 
      className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] w-screen relative -mt-6 -mb-6"
      style={{ 
        marginLeft: 'calc(50% - 50vw)',
        marginRight: 'calc(50% - 50vw)',
        width: '100vw',
        paddingTop: '1.5rem',
        paddingBottom: '1.5rem',
        zIndex: 1
      }}
    >
      <div className="w-full px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4">
        {}
        <Link
          to="/rooms"
          className="inline-flex items-center gap-1 
            text-[#d4af37]/80 hover:text-[#d4af37] 
            mb-3 transition-all duration-300 
            group font-light tracking-wide text-xs sm:text-sm"
        >
          <ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
          <span>Back to room list</span>
        </Link>

        {}
        <div className="mb-4">
          <RoomGallery
            images={(room.images && room.images.length > 0) 
              ? room.images 
              : (roomType?.images || [])}
            roomName={roomType?.name || 'Room'}
          />
        </div>

        {}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-3 sm:gap-4 lg:gap-6 mb-4 sm:mb-5">
          {}
          <div className="lg:col-span-8 space-y-3 sm:space-y-4">
            {}
            <div className="space-y-3">
              {}
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-1.5 mb-2">
                    {room.featured && (
                      <div className="flex items-center gap-1 
                        bg-gradient-to-r from-[#d4af37] to-[#c9a227] 
                        text-[#0f0f0f] px-2 py-0.5 rounded-sm 
                        text-[10px] sm:text-xs font-medium tracking-wide
                        shadow-sm shadow-[#d4af37]/30"
                      >
                        <Sparkles className="w-2.5 h-2.5" />
                        Featured
                      </div>
                    )}
                    <div
                      className={`px-2 py-0.5 rounded-sm 
                        text-[10px] sm:text-xs font-medium tracking-wide
                        backdrop-blur-sm shadow-sm
                        ${
                          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 Now'
                        : room.status === 'occupied'
                        ? 'Booked'
                        : 'Maintenance'}
                    </div>
                  </div>
                  
                  <h1 className="text-xl sm:text-2xl lg:text-3xl font-serif font-semibold 
                    text-white mb-2 tracking-tight leading-tight
                    bg-gradient-to-r from-white via-[#d4af37] to-white 
                    bg-clip-text text-transparent"
              >
                {roomType?.name}
              </h1>
                </div>
              </div>
              
              {}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-2 sm:gap-3 mb-3">
                <div className="flex items-center gap-2 
                  p-2 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                  rounded-lg border border-[#d4af37]/20 
                  hover:border-[#d4af37]/40 transition-all duration-300"
              >
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <MapPin className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                  <div>
                    <p className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide mb-0.5">
                      Location
                    </p>
                    <p className="text-xs sm:text-sm text-white font-light tracking-wide">
                    Room {room.room_number} - Floor {room.floor}
                    </p>
                  </div>
                </div>
                
                <div className="flex items-center gap-2 
                  p-2 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                  rounded-lg border border-[#d4af37]/20"
                >
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <Users className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                  <div>
                    <p className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide mb-0.5">
                      Capacity
                    </p>
                    <p className="text-xs sm:text-sm text-white font-light tracking-wide">
                    {room?.capacity || roomType?.capacity || 0} guests
                    </p>
                  </div>
                </div>

                {room.average_rating != null && (
                  <div className="flex items-center gap-2 
                    p-2 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                    rounded-lg border border-[#d4af37]/20 
                    hover:border-[#d4af37]/40 transition-all duration-300"
                  >
                    <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                      border border-[#d4af37]/30">
                      <Star className="w-3.5 h-3.5 text-[#d4af37] fill-[#d4af37]" />
                    </div>
                    <div>
                      <p className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide mb-0.5">
                        Rating
                      </p>
                  <div className="flex items-center gap-1">
                        <p className="text-xs sm:text-sm text-white font-semibold">
                          {Number(room.average_rating).toFixed(1)}
                        </p>
                        <span className="text-[10px] sm:text-xs text-gray-500 font-light">
                          ({room.total_reviews || 0})
                    </span>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {}
            {(room?.description || roomType?.description) && (
              <div className="p-3 sm:p-4 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                rounded-lg border border-[#d4af37]/20 
                backdrop-blur-xl shadow-lg shadow-[#d4af37]/5"
              >
                <div className="flex items-center gap-2 mb-2">
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <Award className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                  <h2 className="text-sm sm:text-base font-serif font-semibold 
                    text-white tracking-wide"
                >
                  {room?.description ? 'Room Description' : 'Room Type Description'}
                </h2>
                </div>
                <p className="text-gray-300 leading-relaxed 
                  font-light tracking-wide text-xs sm:text-sm"
                >
                  {room?.description || roomType?.description}
                </p>
              </div>
            )}

            {}
            <div className="p-3 sm:p-4 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
              rounded-lg border border-[#d4af37]/20 
              backdrop-blur-xl shadow-lg shadow-[#d4af37]/5"
            >
              <div className="flex items-center gap-2 mb-2">
                <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                  border border-[#d4af37]/30">
                  <Sparkles className="w-3.5 h-3.5 text-[#d4af37]" />
                </div>
                <h2 className="text-sm sm:text-base font-serif font-semibold 
                  text-white tracking-wide"
              >
                  Amenities & Features
              </h2>
              </div>
              <RoomAmenities
                amenities={
                  (room.amenities && room.amenities.length > 0)
                    ? room.amenities
                    : (roomType?.amenities || [])
                }
              />
            </div>
          </div>

          {}
          <aside className="lg:col-span-4">
            <div className="bg-gradient-to-br from-[#1a1a1a] via-[#0f0f0f] to-[#1a1a1a] 
              rounded-lg border border-[#d4af37]/30 
              backdrop-blur-xl shadow-lg shadow-[#d4af37]/20 
              p-3 sm:p-4 sticky top-4"
            >
              {}
              <div className="mb-4 pb-4 border-b border-[#d4af37]/20">
                <p className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide mb-1">
                  Starting from
                </p>
                <div className="flex items-baseline gap-1.5">
                  <CurrencyIcon className="text-[#d4af37]" size={16} />
                <div>
                    <div className="text-2xl sm:text-3xl font-serif font-semibold 
                      bg-gradient-to-r from-[#d4af37] to-[#f5d76e] 
                      bg-clip-text text-transparent tracking-tight"
                    >
                    {formattedPrice}
                    </div>
                    <div className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide mt-0.5">
                      / night
                    </div>
                  </div>
                </div>
              </div>

              {}
              {userInfo?.role !== 'admin' && userInfo?.role !== 'staff' && (
                <>
                  <div className="mb-3">
                    <Link
                      to={`/booking/${room.id}`}
                      className={`block w-full py-2 text-center 
                        font-medium rounded-sm transition-all duration-300 
                        tracking-wide relative overflow-hidden group text-xs sm:text-sm
                        ${
                        room.status === 'available'
                            ? 'bg-gradient-to-r from-[#d4af37] to-[#c9a227] text-[#0f0f0f] hover:from-[#f5d76e] hover:to-[#d4af37] shadow-sm shadow-[#d4af37]/30 hover:shadow-[#d4af37]/50'
                            : 'bg-gray-800 text-gray-500 cursor-not-allowed border border-gray-700'
                      }`}
                      onClick={(e) => {
                        if (room.status !== 'available') e.preventDefault();
                      }}
                    >
                      <span className="relative z-10 flex items-center justify-center gap-1.5">
                        <Calendar className="w-3.5 h-3.5" />
                      {room.status === 'available' ? 'Book Now' : 'Not Available'}
                      </span>
                      {room.status === 'available' && (
                        <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                      )}
                    </Link>
                  </div>

                  {room.status === 'available' && (
                    <div className="flex items-start gap-2 p-2 bg-[#d4af37]/5 
                      rounded-lg border border-[#d4af37]/20 mb-3"
                    >
                      <Shield className="w-3.5 h-3.5 text-[#d4af37] mt-0.5 flex-shrink-0" />
                      <p className="text-[10px] sm:text-xs text-gray-300 font-light tracking-wide leading-relaxed">
                        <strong className="text-[#d4af37]">20% deposit required</strong> to secure your booking. Pay the remaining balance on arrival at the hotel.
                    </p>
                    </div>
                  )}
                </>
              )}

              {}
              <div className="space-y-2">
                <div className="flex items-center justify-between 
                  py-1.5 border-b border-[#d4af37]/10"
                >
                  <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">Room Type</span>
                  <strong className="text-xs sm:text-sm text-white font-light">{roomType?.name}</strong>
                </div>
                <div className="flex items-center justify-between 
                  py-1.5 border-b border-[#d4af37]/10"
                >
                  <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">Max Guests</span>
                  <span className="text-xs sm:text-sm text-white font-light">{(room?.capacity || roomType?.capacity || 0)} guests</span>
                </div>
                {room?.room_size && (
                  <div className="flex items-center justify-between 
                    py-1.5 border-b border-[#d4af37]/10"
                  >
                    <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">Room Size</span>
                    <span className="text-xs sm:text-sm text-white font-light">{room.room_size}</span>
                  </div>
                )}
                {room?.view && (
                  <div className={`flex items-center justify-between ${room?.room_size ? 'py-1.5 border-b border-[#d4af37]/10' : 'py-1.5'}`}>
                    <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">View</span>
                    <span className="text-xs sm:text-sm text-white font-light">{room.view}</span>
                  </div>
                )}
              </div>
            </div>
          </aside>
        </div>

        {}
        <div className="mb-4 p-3 sm:p-4 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
          rounded-lg border border-[#d4af37]/20 
          backdrop-blur-xl shadow-lg shadow-[#d4af37]/5"
        >
          <ReviewSection roomId={room.id} />
        </div>
      </div>
    </div>
  );
};

export default RoomDetailPage;
