'use client';

import { useState, useRef, useEffect } from 'react';
import { Minus, Plus } from 'lucide-react';

export interface RoomsGuestsData {
  rooms: number;
  adults: number;
  children: number;
  childrenAges: number[];
}

interface RoomsGuestsSelectorProps {
  value: RoomsGuestsData;
  onChange: (data: RoomsGuestsData) => void;
  className?: string;
  isOpen?: boolean;
  onOpenChange?: (isOpen: boolean) => void;
  onApply?: () => void;
}

export default function RoomsGuestsSelector({ 
  value, 
  onChange,
  className = '',
  isOpen: externalIsOpen,
  onOpenChange,
  onApply
}: RoomsGuestsSelectorProps) {
  const [internalShowMenu, setInternalShowMenu] = useState(false);
  const showMenu = externalIsOpen !== undefined ? externalIsOpen : internalShowMenu;
  const setShowMenu = onOpenChange || setInternalShowMenu;
  const containerRef = useRef<HTMLDivElement>(null);

  // Local (unapplied) children state — only committed to parent on Apply
  const [localChildren, setLocalChildren] = useState(value.children);
  const [localChildrenAges, setLocalChildrenAges] = useState(value.childrenAges);

  // Reset local children state whenever the dropdown opens
  useEffect(() => {
    if (showMenu) {
      setLocalChildren(value.children);
      setLocalChildrenAges(value.childrenAges);
    }
  }, [showMenu]); // eslint-disable-line react-hooks/exhaustive-deps

  // Dropdown only closes via the Apply button — outside clicks are intentionally ignored.
  
  // Counter handlers
  const handleRoomsChange = (e: React.MouseEvent, delta: number) => {
    e.preventDefault();
    e.stopPropagation();

    // Rooms allowed from 1 to 9
    const newRooms = Math.max(1, Math.min(9, value.rooms + delta));
    // Ensure at least 1 adult per room and maximum 4 adults per room
    const minAdults = newRooms;
    const maxAdults = newRooms * 4;
    const newAdults = Math.max(minAdults, Math.min(maxAdults, value.adults));

    // Clamp local (unapplied) children to new room limit
    const maxChildren = newRooms * 2;
    const newLocalChildren = Math.min(maxChildren, localChildren);
    setLocalChildren(newLocalChildren);
    setLocalChildrenAges(localChildrenAges.slice(0, newLocalChildren));

    onChange({
      rooms: newRooms,
      adults: newAdults,
      children: value.children,
      childrenAges: value.childrenAges,
    });
  };

  const handleAdultsChange = (e: React.MouseEvent, delta: number) => {
    e.preventDefault();
    e.stopPropagation();

    // Ensure at least 1 adult per room (minimum = rooms count) and maximum 4 adults per room
    const minAdults = value.rooms;
    const maxAdults = value.rooms * 4;
    const newAdults = Math.max(minAdults, Math.min(maxAdults, value.adults + delta));

    onChange({
      ...value,
      adults: newAdults
    });
  };

  const handleChildrenChange = (e: React.MouseEvent, delta: number) => {
    e.preventDefault();
    e.stopPropagation();

    // Maximum 2 children per room — update local state only
    const maxChildren = value.rooms * 2;
    const newCount = Math.max(0, Math.min(maxChildren, localChildren + delta));
    let newLocalAges = [...localChildrenAges];

    if (newCount > localChildren) {
      newLocalAges = [...localChildrenAges, ...Array(newCount - localChildren).fill(-1)];
    } else if (newCount < localChildren) {
      newLocalAges = localChildrenAges.slice(0, newCount);
    }

    setLocalChildren(newCount);
    setLocalChildrenAges(newLocalAges);
  };

  const handleChildAgeChange = (index: number, age: number) => {
    const newAges = [...localChildrenAges];
    newAges[index] = age;
    setLocalChildrenAges(newAges);
  };
  
  return (
    <div 
      className={`col position-relative d-flex m-0 guestPanel border-end border-2 py-2 ${className}`} 
      ref={containerRef}
    >
      <div className="w-100 bg-transparent rounded-3 mb-lg-0 mb-3">
        <div 
          className="collapse-fields p-2 cursor-pointer" 
          onClick={() => setShowMenu(!showMenu)}
        >
          {/* Desktop view */}
          <div className="d-none d-sm-block">
            <div className="d-flex justify-content-between label-height">
              <label className="d-block color-text-gray">Rooms & Guests </label>
              <svg className="iconSize-25" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path fillRule="evenodd" clipRule="evenodd" d="M1.00273 5.14403C1.19102 5.59467 11.8313 19.0398 11.968 18.9999C12.1428 18.949 23.1334 5 22.9988 5C22.9496 5 20.5584 6.49998 17.685 8.33341C14.8116 10.1668 12.3055 11.7084 12.1161 11.7591C11.9242 11.8106 9.88273 10.6507 7.50032 9.13625C5.15097 7.64308 2.71016 6.09111 2.07618 5.68778C1.4422 5.28444 0.95915 5.03984 1.00273 5.14403Z" fill="#BAC3C6"/>
              </svg>
            </div>
            <div className="travel-class-value d-flex align-items-center"> 
              <span className="travel-class-field color-text-gray">
                <p className="form-control bg-transparent rounded-0 p-0 collapse-fields-font color-text-gray d-inline" >{value.adults} </p> {" "}Adults ,
              </span>
              <span className="travel-class-field color-text-gray">
                <p className="form-control bg-transparent rounded-0 p-0 collapse-fields-font color-text-gray d-inline" >{value.rooms} </p> {" "}Rooms
              </span> 
            </div>
            <span className="totalChildren d-block color-text-gray">{value.children} {value.children === 1 ? 'Child' : 'Children'}</span>
          </div>

          {/* Mobile view: Rooms | Adults | Kids inline */}
          <div className="d-flex d-sm-none mobile-rooms-guests-grid">
            <div className="mobile-guest-item flex-fill text-center border-end border-2">
              <label className="d-block color-text-gray mobile-guest-label">Rooms</label>
              <div className="d-flex align-items-center justify-content-center gap-1">
                <span className="mobile-guest-value color-text-gray">{value.rooms}</span>
                <svg className="iconSize-15" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path fillRule="evenodd" clipRule="evenodd" d="M1.00273 5.14403C1.19102 5.59467 11.8313 19.0398 11.968 18.9999C12.1428 18.949 23.1334 5 22.9988 5C22.9496 5 20.5584 6.49998 17.685 8.33341C14.8116 10.1668 12.3055 11.7084 12.1161 11.7591C11.9242 11.8106 9.88273 10.6507 7.50032 9.13625C5.15097 7.64308 2.71016 6.09111 2.07618 5.68778C1.4422 5.28444 0.95915 5.03984 1.00273 5.14403Z" fill="#BAC3C6"/>
                </svg>
              </div>
            </div>
            <div className="mobile-guest-item flex-fill text-center border-end border-2">
              <label className="d-block color-text-gray mobile-guest-label">Adults</label>
              <div className="d-flex align-items-center justify-content-center gap-1">
                <span className="mobile-guest-value color-text-gray">{value.adults}</span>
                <svg className="iconSize-15" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path fillRule="evenodd" clipRule="evenodd" d="M1.00273 5.14403C1.19102 5.59467 11.8313 19.0398 11.968 18.9999C12.1428 18.949 23.1334 5 22.9988 5C22.9496 5 20.5584 6.49998 17.685 8.33341C14.8116 10.1668 12.3055 11.7084 12.1161 11.7591C11.9242 11.8106 9.88273 10.6507 7.50032 9.13625C5.15097 7.64308 2.71016 6.09111 2.07618 5.68778C1.4422 5.28444 0.95915 5.03984 1.00273 5.14403Z" fill="#BAC3C6"/>
                </svg>
              </div>
            </div>
            <div className="mobile-guest-item flex-fill text-center">
              <label className="d-block color-text-gray mobile-guest-label">Kids</label>
              <div className="d-flex align-items-center justify-content-center gap-1">
                <span className="mobile-guest-value color-text-gray">{value.children}</span>
                <svg className="iconSize-15" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path fillRule="evenodd" clipRule="evenodd" d="M1.00273 5.14403C1.19102 5.59467 11.8313 19.0398 11.968 18.9999C12.1428 18.949 23.1334 5 22.9988 5C22.9496 5 20.5584 6.49998 17.685 8.33341C14.8116 10.1668 12.3055 11.7084 12.1161 11.7591C11.9242 11.8106 9.88273 10.6507 7.50032 9.13625C5.15097 7.64308 2.71016 6.09111 2.07618 5.68778C1.4422 5.28444 0.95915 5.03984 1.00273 5.14403Z" fill="#BAC3C6"/>
                </svg>
              </div>
            </div>
          </div>
        </div>
        
        {/* Dropdown Menu */}
        <div className={`submenu-web bgColor-white rounded-3 shadow-sm ${showMenu ? 'd-block' : 'd-none'}`}>
          <div className="card border-0 rounded-2">
            <div className="card-body">
              {/* Rooms Counter */}
              <div className="row">
                <div className="col-xxl-7 col-xl-7 col-lg-7 col-md-7 col-sm-6 col-6">
                  <p>Rooms</p>
                </div>
                <div className="col-xxl-5 col-xl-5 col-lg-5 col-md-5 col-sm-6 col-6">
                  <div className="qty-container">
                    <button 
                      className="qty-btn-minus bgColor-white shadow-sm" 
                      type="button"
                      onClick={(e) => handleRoomsChange(e, -1)}
                      data-react-managed="true"
                    >
                      <Minus size={12} aria-hidden style={{ pointerEvents: 'none' }} />
                    </button>
                    <input 
                      type="text" 
                      value={value.rooms} 
                      className="input-qty bg-transparent" 
                      readOnly
                    />
                    <button 
                      className="qty-btn-plus bgColor-white shadow-sm" 
                      type="button"
                      onClick={(e) => handleRoomsChange(e, 1)}
                      data-react-managed="true"
                    >
                      <Plus size={12} aria-hidden style={{ pointerEvents: 'none' }} />
                    </button>
                  </div>
                </div>
              </div>
              
              {/* Adults Counter */}
              <div className="row">
                <div className="col-xxl-7 col-xl-7 col-lg-7 col-md-7 col-sm-6 col-6">
                  <p>Adults 18+</p>
                </div>
                <div className="col-xxl-5 col-xl-5 col-lg-5 col-md-5 col-sm-6 col-6">
                  <div className="qty-container">
                    <button 
                      className="qty-btn-minus bgColor-white shadow-sm" 
                      type="button"
                      onClick={(e) => handleAdultsChange(e, -1)}
                      data-react-managed="true"
                    >
                      <Minus size={12} aria-hidden style={{ pointerEvents: 'none' }} />
                    </button>
                    <input 
                      type="text" 
                      value={value.adults} 
                      className="input-qty bg-transparent" 
                      readOnly
                    />
                    <button 
                      className="qty-btn-plus bgColor-white shadow-sm" 
                      type="button"
                      onClick={(e) => handleAdultsChange(e, 1)}
                      data-react-managed="true"
                    >
                      <Plus size={12} aria-hidden style={{ pointerEvents: 'none' }} />
                    </button>
                  </div>
                </div>
              </div>
              
              {/* Children Counter */}
              <div className="row childSelectRow">
                <div className="col-xxl-7 col-xl-7 col-lg-7 col-md-7 col-sm-6 col-6">
                  <div>
                    <p>Children</p>
                    <small>0-17 Years Old</small>
                  </div>
                </div>
                <div className="col-xxl-5 col-xl-5 col-lg-5 col-md-5 col-sm-6 col-6">
                  <div className="qty-container">
                    <button 
                      className="qty-btn-minus bgColor-white shadow-sm" 
                      type="button"
                      onClick={(e) => handleChildrenChange(e, -1)}
                      data-react-managed="true"
                    >
                      <Minus size={12} aria-hidden style={{ pointerEvents: 'none' }} />
                    </button>
                    <input
                      type="text"
                      value={localChildren}
                      className="input-qty bg-transparent"
                      readOnly
                    />
                    <button 
                      className="qty-btn-plus bgColor-white shadow-sm" 
                      type="button"
                      onClick={(e) => handleChildrenChange(e, 1)}
                      data-react-managed="true"
                    >
                      <Plus size={12} aria-hidden style={{ pointerEvents: 'none' }} />
                    </button>
                  </div>
                </div>
              </div>
              
              {/* Children Ages */}
              {localChildren > 0 && (
                <div className="row mt-3">
                  <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12 pe-0">
                    <div className="childrenGroup">
                      <p>Please provide right number of children along with their right age for best options and prices.</p>
                      <div className="child-age-boxes border-top pt-3">
                        {localChildrenAges.map((age, index) => (
                          <div key={index} className="mb-2">
                            <label className="me-2">Child {index + 1} Age:</label>
                            <select
                              className="form-select form-select-sm d-inline-block w-auto"
                              value={age}
                              onChange={(e) => handleChildAgeChange(index, Number(e.target.value))}
                            >
                              <option value={-1} disabled>Select age</option>
                              {Array.from({length: 18}, (_, i) => (
                                <option key={i} value={i}>{i} years</option>
                              ))}
                            </select>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Apply Button */}
              <div className="row mt-3">
                <div className="col-12">
                  <div className="pt-3 border-top text-end">
                    <button
                      className="buttons btnColor-second px-4 py-2"
                      type="button"
                      onClick={() => {
                        onChange({ ...value, children: localChildren, childrenAges: localChildrenAges });
                        setShowMenu(false);
                        onApply?.();
                      }}
                      disabled={localChildrenAges.some(age => age === -1)}
                    >
                      Apply
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

