"use client";

import { forwardRef } from "react";
import { useTranslation } from "react-i18next";
import { clsx } from "clsx";
import AgeRangeInput from "./AgeRangeInput";
import { useAgeRange } from "./useAgeRange";

interface AgeRangeProps {
  name: string;
  label?: string;
  className?: string;
  disabled?: boolean;
  isModal?: boolean;
}

const AgeRange = forwardRef<HTMLDivElement, AgeRangeProps>(
  ({ name, label, className = "", disabled = false, isModal = false }, ref) => {
    const { t } = useTranslation();
    const {
      meta,
      isFocusedStart,
      isFocusedEnd,
      startAge,
      endAge,
      isEndAgeValid,
      isRtl,
      containerRef,
      hasStartError,
      hasEndError,
      handleStartInputChange,
      handleEndInputChange,
      handleStartInputBlur,
      handleEndInputBlur,
      handleStartInputFocus,
      handleEndInputFocus,
      handleKeyDown,
    } = useAgeRange(name);

    return (
      <div
        className={clsx("relative w-full mb-4", className)}
        ref={ref || containerRef}
        dir={isRtl ? "rtl" : "ltr"}
      >
        <div className="flex gap-2 w-full">
          <AgeRangeInput
            id={`${name}-start`}
            labelPrefix={t("COMMON.FROM")}
            label={label}
            value={startAge}
            isFocused={isFocusedStart}
            hasError={hasStartError}
            isRtl={isRtl}
            isModal={isModal}
            disabled={disabled}
            onChange={handleStartInputChange}
            onBlur={handleStartInputBlur}
            onFocus={handleStartInputFocus}
            onKeyDown={handleKeyDown}
          />
          <AgeRangeInput
            id={`${name}-end`}
            labelPrefix={t("COMMON.TO")}
            label={label}
            value={endAge}
            isFocused={isFocusedEnd}
            hasError={hasEndError}
            isRtl={isRtl}
            isModal={isModal}
            disabled={disabled}
            onChange={handleEndInputChange}
            onBlur={handleEndInputBlur}
            onFocus={handleEndInputFocus}
            onKeyDown={handleKeyDown}
          />
        </div>

        {meta.touched && meta.error && (
          <div className="text-red-500 text-xs mt-1">{meta.error}</div>
        )}
        {meta.touched && !meta.error && !isEndAgeValid && (
          <div className="text-red-500 text-xs mt-1">
            {t("COMMON.END_AGE_MUST_BE_GREATER_THAN_START_AGE")}
          </div>
        )}
      </div>
    );
  },
);

AgeRange.displayName = "AgeRange";

export default AgeRange;
