"use client";

import { forwardRef } from "react";
import Image from "next/image";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/helpers";
import { clickable } from "@/lib/a11y";
import TimePickerDropdown from "./TimePickerDropdown";
import { useTimePicker, type TimePickerProps } from "./useTimePicker";

const TimePicker = forwardRef<HTMLInputElement, TimePickerProps>(
  (
    {
      name,
      label,
      className = "",
      disabled = false,
      autoSetTime = false,
      ...props
    },
    ref,
  ) => {
    const { t } = useTranslation();
    const {
      field,
      meta,
      helpers,
      isFocused,
      setIsFocused,
      isDropdownOpen,
      isManualInput,
      selectedHour,
      selectedMinute,
      selectedPeriod,
      inputValue,
      isRtl,
      dropdownRef,
      visibleInputRef,
      baseHours,
      hours,
      baseMinutes,
      minutes,
      hoursScrollRef,
      minutesScrollRef,
      periodScrollRef,
      wasExplicitlyFocused,
      setWasExplicitlyFocused,
      handleTimeChange,
      handleDropdownToggle,
      handleInputAreaClick,
      handleManualInputChange,
      handleManualInputBlur,
      handleLoopingScroll,
      displayValue,
    } = useTimePicker({ name, autoSetTime, disabled });

    const boxClassName = cn(
      "w-full p-3 border rounded-2xl h-[48px] bg-[#29246D]/[0.03] text-primary-5",
      isRtl ? "text-right pr-3" : "text-left pl-[19px]",
      meta.touched && meta.error ? "border-red-500" : "border-[#29246D1A]/10",
      isFocused || field.value ? "pt-6" : "pt-3",
      disabled ? "opacity-50 cursor-not-allowed" : "",
      className,
    );

    return (
      <div
        className={cn("relative w-full mb-4", className)}
        dir={isRtl ? "rtl" : "ltr"}
        ref={dropdownRef}
        onClick={(e) => e.stopPropagation()} // Prevent clicks from bubbling
      >
        {/* Floating Label */}
        {label && (
          <label
            htmlFor={name}
            className={`absolute transition-all duration-200 text-primary-5 pointer-events-none
              ${isRtl ? "right-[9px]" : "left-[15px]"}
              ${
                isFocused || field.value
                  ? "text-[10px] top-[5px] bg-white px-1 text-primary-5/70"
                  : "lg:text-base md:text-sm text-sm top-3"
              }
            `}
          >
            {label}
          </label>
        )}

        <div
          className={`relative flex items-center ${
            isRtl ? "flex-row-reverse" : ""
          }`}
        >
          {!isManualInput ? (
            /* Display box - visible when not in manual input mode */
            <div
              className={cn(boxClassName, "cursor-pointer flex items-center")}
              {...clickable(() => !disabled && handleInputAreaClick())}
              aria-label={[label, displayValue].filter(Boolean).join(" ")}
              aria-disabled={disabled || undefined}
            >
              {/* The 12-hour value with its period: «02:30» alone could not
                  say whether it was 02:30 or 14:30. */}
              <span
                className={displayValue ? "text-primary-5" : "text-transparent"}
              >
                {displayValue
                  ? `${displayValue} ${t(selectedPeriod === "AM" ? "COMMON.AM" : "COMMON.PM")}`
                  : "00:00"}
              </span>
            </div>
          ) : (
            /* Manual input field */
            <input
              ref={visibleInputRef}
              type="text"
              value={inputValue}
              onChange={handleManualInputChange}
              onFocus={() => setWasExplicitlyFocused(true)}
              onBlur={handleManualInputBlur}
              placeholder="00:00"
              className={cn(boxClassName, "outline-none")}
              disabled={disabled}
              dir={isRtl ? "rtl" : "ltr"}
              maxLength={5}
              inputMode="numeric"
              aria-label={label}
              autoFocus
            />
          )}

          {/* Custom Clock Icon */}
          <button
            type="button"
            onClick={handleDropdownToggle}
            disabled={disabled}
            aria-label={t("COMMON.OPEN_TIME_PICKER")}
            aria-expanded={isDropdownOpen}
            className="absolute text-primary-5"
            style={{
              left: isRtl ? "10px" : "auto",
              right: isRtl ? "auto" : "10px",
            }}
          >
            <Image src="/assets/profile/clockicn.svg" alt="" width={20} height={20} />
          </button>
        </div>

        {/* Custom Dropdown */}
        {isDropdownOpen && (
          <TimePickerDropdown
            hours={hours}
            minutes={minutes}
            baseHours={baseHours}
            baseMinutes={baseMinutes}
            selectedHour={selectedHour}
            selectedMinute={selectedMinute}
            selectedPeriod={selectedPeriod}
            hoursScrollRef={hoursScrollRef}
            minutesScrollRef={minutesScrollRef}
            periodScrollRef={periodScrollRef}
            onTimeChange={handleTimeChange}
            onLoopingScroll={handleLoopingScroll}
          />
        )}

        {/* Hidden input for form compatibility and validation */}
        <input
          {...field}
          {...props}
          ref={ref}
          type="time"
          name={name}
          value={field.value || ""}
          onChange={(e) => { helpers.setValue(e.target.value); helpers.setTouched(true); }}
          onBlur={() => {
            if (wasExplicitlyFocused) {
              helpers.setTouched(true);
              setIsFocused(false);
            }
          }}
          style={{ position: "absolute", left: "-9999px", opacity: 0, pointerEvents: "none" }}
          tabIndex={-1}
        />

        {/* Error Message */}
        {meta.touched && meta.error && (
          <div className="text-red-500 text-sm mt-1">{meta.error}</div>
        )}
      </div>
    );
  },
);

TimePicker.displayName = "TimePicker";

export default TimePicker;
