"use client";

import React from "react";
import { clsx } from "clsx";
import { OPPORTUNITY_MIN_AGE, OPPORTUNITY_MAX_AGE } from "@/data/Constants";

/**
 * One end of the age range.
 *
 * Both ends are the same floating-label number input; only the id suffix, the
 * label prefix and which half of the value they read differ, so they share one
 * component rather than two copies of the markup.
 */
export default function AgeRangeInput({
  id,
  labelPrefix,
  label,
  value,
  isFocused,
  hasError,
  isRtl,
  isModal,
  disabled,
  onChange,
  onBlur,
  onFocus,
  onKeyDown,
}: {
  id: string;
  /** "From" / "To", already translated. */
  labelPrefix: string;
  label?: string;
  value: number | null;
  isFocused: boolean;
  /** Truthy rather than boolean: the callers pass Formik's `error` through. */
  hasError: unknown;
  isRtl: boolean;
  isModal: boolean;
  disabled: boolean;
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  onBlur: () => void;
  onFocus: () => void;
  onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void;
}) {
  return (
    <div className="relative flex-1">
      {label && (
        <label
          htmlFor={id}
          className={clsx(
            "absolute transition-all duration-200 text-primary-5 z-10",
            isRtl ? "right-[9px]" : "left-[15px]",
            isFocused || value !== null
              ? "text-[10px] top-[5px] px-1 text-primary-5/70"
              : "lg:text-base md:text-sm text-sm top-3"
          )}
        >
          {labelPrefix} {label}
        </label>
      )}
      <div
        className={clsx(
          "w-full p-3 border rounded-2xl h-[48px] flex items-center modal-border",
          isRtl ? "pr-3" : "pl-[19px]",
          isModal ? "" : "bg-[#29246D]/[0.03]",
          hasError ? "border-red-500" : "border-[#29246D1A]/10",
          isFocused || value !== null ? "pt-6" : "pt-3"
        )}
      >
        <input
          id={id}
          type="number"
          value={value ?? ""}
          placeholder=""
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
          onKeyDown={onKeyDown}
          min={OPPORTUNITY_MIN_AGE}
          max={OPPORTUNITY_MAX_AGE}
          disabled={disabled}
          className={clsx(
            isModal ? "no-border" : "",
            "w-full bg-transparent text-primary-5 text-base outline-none appearance-none",
            isRtl ? "text-right" : "text-left"
          )}
        />
      </div>
    </div>
  );
}
