import React, { useState, useEffect, useRef } from "react";
import "./TimePicker.css";
import { Typography } from "@mui/material";

const TimePicker = ({
  value = "",
  onChange,
  label = "زمان",
  disabled = false,
  className = "",
}) => {
  const [time, setTime] = useState(value);
  const [isOpen, setIsOpen] = useState(false);
  const timePickerRef = useRef(null);

  const hours = Array.from({ length: 24 }, (_, i) =>
    i.toString().padStart(2, "0")
  );
  const minutes = Array.from({ length: 12 }, (_, i) =>
    (i * 5).toString().padStart(2, "0")
  );

  useEffect(() => {
    setTime(value);
  }, [value]);

  const [currentHour, currentMinute] = time ? time.split(":") : "";
  const selectedHour = currentHour || "00";
  const selectedMinute = currentMinute || "00";

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        timePickerRef.current &&
        !timePickerRef.current.contains(event.target)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleHourChange = (hour) => {
    const newTime = `${hour}:${selectedMinute}:00`;
    setTime(newTime);
    onChange(newTime);
  };

  const handleMinuteChange = (minute) => {
    const newTime = `${selectedHour}:${minute}:00`;
    setTime(newTime);
    onChange(newTime);
    setIsOpen(false);
  };

  const handleInputChange = (e) => {
    const value = e.target.value;
    if (/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/.test(value) || value === "") {
      setTime(value);
      if (value.includes(":") && value.length === 5) {
        const formatted = `${value}:00`;
        onChange(formatted);
      }
    }
  };
  const handleInputBlur = () => {
    if (!time.includes(":") || time.length !== 5) {
      setTime(selectedHour + ":" + selectedMinute);
    }
  };

  return (
    <div className={`time-picker ${className}`} ref={timePickerRef}>
      <Typography>
        {label && <label className="time-picker-label">{label}</label>}
      </Typography>
      <div className="time-picker-input-container">
        {/* eslint-disable-next-line  */}
        <input
          type="text"
          value={time.slice(0, 5)}
          onChange={handleInputChange}
          onBlur={handleInputBlur}
          onFocus={() => setIsOpen(true)}
          placeholder="hh:mm"
          className="time-picker-input"
          disabled={disabled}
          aria-haspopup="listbox"
          aria-expanded={isOpen}
        />
        <button
          type="button"
          className="time-picker-toggle"
          onClick={() => setIsOpen(!isOpen)}
          disabled={disabled}
          aria-label="Toggle time picker"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <circle cx="12" cy="12" r="10" />
            <polyline points="12 6 12 12 16 14" />
          </svg>
        </button>
      </div>

      {isOpen && (
        <div className="time-picker-dropdown">
          <div className="time-picker-column">
            <div className="time-picker-header">دقیقه</div>
            <div className="time-picker-list">
              {minutes.map((minute) => (
                <button
                  key={minute}
                  type="button"
                  className={`time-picker-item ${
                    minute === selectedMinute ? "selected" : ""
                  }`}
                  onClick={() => handleMinuteChange(minute)}
                >
                  {minute}
                </button>
              ))}
            </div>
          </div>
          <div className="time-picker-column">
            <div className="time-picker-header">ساعت</div>
            <div className="time-picker-list">
              {hours.map((hour) => (
                <button
                  key={hour}
                  type="button"
                  className={`time-picker-item ${
                    hour === selectedHour ? "selected" : ""
                  }`}
                  onClick={() => handleHourChange(hour)}
                >
                  {hour}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TimePicker;
