import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import Grid from "../grid";
import Input from ".";
import React, { useMemo, useState, useEffect, useCallback } from "react";
import InputBlockLabel, { InputError } from "./input-block-label";
// function isDefaultValue(value: unknown): value is RangeValue {
//   return (
//     value instanceof RangeValue &&
//     value !== null &&
//     "min" in value &&
//     "max" in value
//   );
// }

function CurrencyRangeInput(_ref) {
  var prefix = _ref.prefix,
    allowDecimals = _ref.allowDecimals,
    intlConfig = _ref.intlConfig,
    children = _ref.children,
    value = _ref.value,
    _ref$defaultValue = _ref.defaultValue,
    defaultValue = _ref$defaultValue === void 0 ? {
      min: "",
      max: ""
    } : _ref$defaultValue,
    onChange = _ref.onChange,
    _ref$debounce = _ref.debounce,
    debounce = _ref$debounce === void 0 ? 300 : _ref$debounce,
    externalError = _ref.error,
    externalHelperText = _ref.helperText;
  var isControlled = value !== undefined;
  var _useState = useState(defaultValue),
    _useState2 = _slicedToArray(_useState, 2),
    internalValue = _useState2[0],
    setInternalValue = _useState2[1];
  var currentValue = isControlled ? value : internalValue;
  var setValue = useCallback(function (val) {
    if (!isControlled) {
      setInternalValue(val);
    }
  }, [isControlled]);

  // function toNumber(value: string): number {
  // if (typeof value != "string") {
  //   throw Error("Invalid default value")
  // }
  //   let cleaned = value.trim();

  //   // Remove currency symbols and letters
  //   cleaned = cleaned.replace(/[^\d.,-]/g, '');

  //   // If both comma and dot exist → detect format
  //   if (cleaned.includes(',') && cleaned.includes('.')) {
  //     // If comma appears after dot → European format
  //     if (cleaned.lastIndexOf(',') > cleaned.lastIndexOf('.')) {
  //       cleaned = cleaned.replace(/\./g, '').replace(',', '.');
  //     } else {
  //       cleaned = cleaned.replace(/,/g, '');
  //     }
  //   }
  //   // If only comma exists → assume European decimal
  //   else if (cleaned.includes(',')) {
  //     cleaned = cleaned.replace(',', '.');
  //   }

  //   return Number(cleaned);
  // }

  function toNumber(value) {
    if (typeof value != "string") {
      throw Error("Invalid default value");
    }
    var cleaned = value.replace(/[^\d.-]/g, '');
    var result = Number(cleaned);
    return isNaN(result) ? 0 : result;
  }

  // Validation
  var isInvalid = useMemo(function () {
    if (!currentValue.min || !currentValue.max) return false;
    return toNumber(currentValue.max) <= toNumber(currentValue.min);
  }, [currentValue]);

  // Debounced onChange
  useEffect(function () {
    if (!onChange || isInvalid) return;
    // console.log(currentValue, isInvalid);
    var handler = setTimeout(function () {
      if (currentValue.min && currentValue.max) {
        onChange({
          min: currentValue.min,
          max: currentValue.max
        });
      }
    }, debounce);
    return function () {
      return clearTimeout(handler);
    };
  }, [isInvalid, debounce, currentValue]);
  var finalError = externalError !== null && externalError !== void 0 ? externalError : isInvalid;
  var finalHelperText = isInvalid ? "Max must be greater than min" : externalHelperText;
  return /*#__PURE__*/React.createElement("div", {
    className: "with-label"
  }, children && /*#__PURE__*/React.createElement(InputBlockLabel, null, children), /*#__PURE__*/React.createElement(Grid.Container, {
    gap: 2
  }, /*#__PURE__*/React.createElement(Grid, null, /*#__PURE__*/React.createElement(Input.Currency, {
    value: toNumber(currentValue.min),
    onValueChange: function onValueChange(_, __, values) {
      return setValue(_extends({}, currentValue, {
        min: values === null || values === void 0 ? void 0 : values.formatted
      }));
    },
    intlConfig: intlConfig,
    prefix: prefix,
    placeholder: "Min",
    allowDecimals: allowDecimals
  })), /*#__PURE__*/React.createElement(Grid, null, /*#__PURE__*/React.createElement(Input.Currency, {
    value: toNumber(currentValue.max),
    onValueChange: function onValueChange(_, __, values) {
      return setValue(_extends({}, currentValue, {
        max: values === null || values === void 0 ? void 0 : values.formatted
      }));
    },
    intlConfig: intlConfig,
    prefix: prefix,
    placeholder: "Max",
    allowDecimals: allowDecimals
  }))), finalHelperText && /*#__PURE__*/React.createElement(InputError, {
    error: finalError,
    text: finalHelperText
  }));
}
export default /*#__PURE__*/React.memo(CurrencyRangeInput);