import React, { useState, useRef, useEffect } from "react";

const TimePicker = ({ label, onChange, interval = 10, value }) => {
  const [time, setTime] = useState(value || "");
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  const getCurrentTime = () => {
    const now = new Date();
    const minutes = now.getMinutes();
    const roundedMinutes = Math.round(minutes / interval) * interval; // Round to nearest interval
    now.setMinutes(roundedMinutes);
    now.setSeconds(0);
    now.setMilliseconds(0);
    return now;
  };

  const formatTime = (date) => {
    let hours = date.getHours();
    const minutes = date.getMinutes();
    const period = hours >= 12 ? "PM" : "AM";

    hours = hours % 12; // Convert 24-hour format to 12-hour format
    hours = hours ? hours : 12; // The hour '0' should be '12'
    const hoursFormatted = hours < 10 ? `0${hours}` : hours; // Ensure two-digit hour
    const minutesFormatted = minutes < 10 ? `0${minutes}` : minutes; // Ensure two-digit minutes

    return `${hoursFormatted}:${minutesFormatted} ${period}`;
  };

  const generateTimeSlots = () => {
    const slots = [];
    let currentTime = new Date(getCurrentTime());
    for (let i = 0; i < 144; i++) { // 24 hours with custom interval
      slots.push(formatTime(currentTime));
      currentTime.setMinutes(currentTime.getMinutes() + interval);
    }
    return slots;
  };

  const handleSelect = (selectedTime) => {
    setTime(selectedTime);
    if (onChange) onChange(selectedTime);
    setIsOpen(false);
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (!value) {
      const defaultTime = formatTime(getCurrentTime());
      setTime(defaultTime);
      if (onChange) onChange(defaultTime); 
    }
  }, [value, interval, onChange]);

  return (
    <div className="position-relative w-100" ref={dropdownRef}>
      {label && <label className="form-label">{label}</label>}
      <div className="position-relative">
        <input
          type="text"
          className="form-control pe-5"
          value={time}
          readOnly
          onClick={() => setIsOpen(!isOpen)}
          style={{ cursor: "pointer" }}
        />
        <span
          className="position-absolute end-0 top-50 translate-middle-y pe-3 d-flex align-items-center"
          style={{ cursor: "pointer" }}
          onClick={() => setIsOpen(!isOpen)}
        >
          <i className="bx bx-time fs-4"></i>
        </span>
      </div>

      {isOpen && (
        <div
          className="dropdown-menu show shadow-lg border rounded p-2"
          style={{
            position: "absolute",
            width: "auto",
            background: "#fff",
            display: "flex",
            flexDirection: "column",
            gap: "5px",
            maxHeight: "200px", // Adjust max height to fit the container
            overflowY: "auto", // Enables vertical scrolling
          }}
        >
          {generateTimeSlots().map((slot, index) => (
            <button
              key={index}
              className={`dropdown-item px-3 py-1 text-center rounded-1 ${
                time === slot ? "btn-primary" : ""
              }`}
              onClick={(event) => {
                event.preventDefault();
                handleSelect(slot);
              }}
            >
              {slot}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

export default TimePicker;
