import {
  DynamicFormField
} from "./chunk-XON6DE42.js";
import {
  DynamicFormProvider,
  useDynamicForm
} from "./chunk-O2S7S5B4.js";
import {
  Form
} from "./chunk-2OMSNCRH.js";
import {
  Typo
} from "./chunk-PMJIFLDT.js";
import {
  __async
} from "./chunk-CRTRMMJ7.js";

// src/molecules/dynamic-form.tsx
import { useMemo, useCallback, useEffect } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import { Box } from "@radix-ui/themes";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function scrollToFirstError(errors, _fields) {
  const firstErrorFieldName = Object.keys(errors)[0];
  if (!firstErrorFieldName) return;
  let fieldElement = document.querySelector(`[name="${firstErrorFieldName}"]`);
  if (!fieldElement) {
    fieldElement = document.querySelector(`[data-field-name="${firstErrorFieldName}"]`);
  }
  if (!fieldElement) {
    fieldElement = document.querySelector(`[data-error-field="${firstErrorFieldName}"]`);
  }
  if (fieldElement) {
    fieldElement.scrollIntoView({
      behavior: "smooth",
      block: "nearest"
    });
  }
}
function DynamicFormRoot({
  fields,
  initialValues = {},
  onSubmit,
  children
}) {
  const validationSchema = useMemo(() => {
    const schema = {};
    fields.forEach((field) => {
      if (field.validation) {
        const validation = createYupValidation(field, field.validation);
        if (validation) {
          schema[field.name] = validation;
        }
      } else if (field.required) {
        if (field.type === "choices") {
          schema[field.name] = Yup.array().min(1, `${field.label}\uC744(\uB97C) \uD558\uB098 \uC774\uC0C1 \uC120\uD0DD\uD574\uC8FC\uC138\uC694`).required(`${field.label}\uC740(\uB294) \uD544\uC218\uC785\uB2C8\uB2E4`);
        } else if (field.type === "yes_no") {
          schema[field.name] = Yup.boolean().oneOf([true], `${field.label}\uC5D0 \uB3D9\uC758\uD574\uC8FC\uC138\uC694`);
        } else {
          schema[field.name] = Yup.string().required(
            `${field.label}\uC740(\uB294) \uD544\uC218\uC785\uB2C8\uB2E4`
          );
        }
      }
    });
    return Object.keys(schema).length > 0 ? Yup.object(schema) : void 0;
  }, [fields]);
  const handleSubmit = useCallback((values) => __async(null, null, function* () {
    yield onSubmit(values);
  }), [onSubmit]);
  const formik = useFormik({
    initialValues: fields.reduce((acc, field) => {
      if (field.type === "choices") {
        acc[field.name] = initialValues[field.name] || [];
      } else if (field.type === "yes_no") {
        acc[field.name] = initialValues[field.name] || false;
      } else {
        acc[field.name] = initialValues[field.name] || "";
      }
      return acc;
    }, {}),
    validationSchema,
    validateOnBlur: true,
    validateOnChange: true,
    onSubmit: handleSubmit
  });
  useEffect(() => {
    if (formik.submitCount > 0 && Object.keys(formik.errors).length > 0) {
      const timeoutId = setTimeout(() => {
        scrollToFirstError(formik.errors, fields);
      }, 100);
      return () => {
        clearTimeout(timeoutId);
      };
    }
  }, [formik.submitCount, formik.errors, fields]);
  return /* @__PURE__ */ jsx(DynamicFormProvider, { fields, formik, children });
}
function DynamicFormFieldList({
  fields: fieldsProp,
  labelVariant
}) {
  const { formik, fields: fieldsFromContext } = useDynamicForm();
  const fields = fieldsProp || fieldsFromContext;
  return /* @__PURE__ */ jsx(Fragment, { children: fields.map((field) => {
    const errorMessage = formik.touched[field.name] && formik.errors[field.name] ? String(formik.errors[field.name]) : void 0;
    return /* @__PURE__ */ jsx(
      Box,
      {
        "data-error-field": errorMessage ? field.name : void 0,
        "data-field-name": field.name,
        mb: "2",
        children: /* @__PURE__ */ jsxs(
          Form.FormItem,
          {
            errorMessage,
            label: field.label,
            labelVariant,
            name: field.name,
            required: field.required,
            children: [
              /* @__PURE__ */ jsx(DynamicFormField, { field }),
              field.description ? /* @__PURE__ */ jsx(Typo, { children: field.description }) : null
            ]
          }
        )
      },
      field.name
    );
  }) });
}
var DynamicForm = {
  Root: DynamicFormRoot,
  FieldList: DynamicFormFieldList
};
function createYupValidation(field, validation) {
  if (!validation) return void 0;
  let schema;
  if (field.type === "number") {
    schema = Yup.number();
  } else if (field.type === "email") {
    schema = Yup.string().email(
      validation.message || "\uC62C\uBC14\uB978 \uC774\uBA54\uC77C \uD615\uC2DD\uC774 \uC544\uB2D9\uB2C8\uB2E4"
    );
  } else if (field.type === "choices") {
    schema = Yup.array();
  } else if (field.type === "yes_no") {
    schema = Yup.boolean();
  } else {
    schema = Yup.string();
  }
  if (validation.min !== void 0) {
    if (field.type === "number") {
      schema = schema.min(
        validation.min,
        validation.message || `\uCD5C\uC18C ${validation.min}\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`
      );
    } else if (field.type === "choices") {
      schema = schema.min(
        validation.min,
        validation.message || `\uCD5C\uC18C ${validation.min}\uAC1C \uC774\uC0C1 \uC120\uD0DD\uD574\uC8FC\uC138\uC694`
      );
    } else if (field.type === "yes_no") {
    } else {
      schema = schema.min(
        validation.min,
        validation.message || `\uCD5C\uC18C ${validation.min}\uC790 \uC774\uC0C1\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`
      );
    }
  }
  if (validation.max !== void 0) {
    if (field.type === "number") {
      schema = schema.max(
        validation.max,
        validation.message || `\uCD5C\uB300 ${validation.max}\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`
      );
    } else if (field.type === "choices") {
      schema = schema.max(
        validation.max,
        validation.message || `\uCD5C\uB300 ${validation.max}\uAC1C\uAE4C\uC9C0 \uC120\uD0DD \uAC00\uB2A5\uD569\uB2C8\uB2E4`
      );
    } else if (field.type === "yes_no") {
    } else {
      schema = schema.max(
        validation.max,
        validation.message || `\uCD5C\uB300 ${validation.max}\uC790 \uC774\uD558\uC5EC\uC57C \uD569\uB2C8\uB2E4`
      );
    }
  }
  if (validation.pattern) {
    if (field.type === "yes_no") {
    } else {
      schema = schema.matches(
        new RegExp(validation.pattern),
        validation.message || "\uC62C\uBC14\uB978 \uD615\uC2DD\uC774 \uC544\uB2D9\uB2C8\uB2E4"
      );
    }
  }
  if (field.required) {
    if (field.type === "yes_no") {
      schema = schema.oneOf([true], validation.message || `${field.label}\uC5D0 \uB3D9\uC758\uD574\uC8FC\uC138\uC694`);
    } else if (field.type === "choices") {
      schema = schema.min(1, validation.message || `${field.label}\uC744(\uB97C) \uD558\uB098 \uC774\uC0C1 \uC120\uD0DD\uD574\uC8FC\uC138\uC694`);
    } else {
      schema = schema.required(validation.message || `${field.label}\uC740(\uB294) \uD544\uC218\uC785\uB2C8\uB2E4`);
    }
  }
  return schema;
}

export {
  DynamicForm,
  createYupValidation
};
//# sourceMappingURL=chunk-QG47PWPH.js.map