import { Form } from "antd";
import LayoutFormRow from "./layout-form-row.component";

export default function InlineValidatedFormRow({ actions, errorNames = [], extraErrors = [], form, ...layoutFormRowProps }) {
  const normalizedErrorNames = Array.isArray(errorNames) ? errorNames : [errorNames];
  const normalizedExtraErrors = Array.isArray(extraErrors) ? extraErrors.filter(Boolean) : [extraErrors].filter(Boolean);

  return (
    <Form.Item noStyle shouldUpdate>
      {() => {
        const fieldErrors = normalizedErrorNames.flatMap((name) => form?.getFieldError?.(name) || []);
        const errors = [...new Set([...fieldErrors, ...normalizedExtraErrors])];
        const resolvedClassName = [
          layoutFormRowProps.className,
          errors.length > 0 ? "imex-form-row--error" : null
        ]
          .filter(Boolean)
          .join(" ");

        const normalizedActions = Array.isArray(actions) ? actions.filter(Boolean) : [actions].filter(Boolean);
        const resolvedActions =
          errors.length > 0
            ? [
                <div
                  key="inline-form-row-footer"
                  className="imex-inline-form-row-errors"
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: normalizedActions.length > 0 ? 8 : 0,
                    width: "100%",
                    textAlign: "left"
                  }}
                >
                  <Form.ErrorList errors={errors} />
                  {normalizedActions.length > 0 ? <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>{normalizedActions}</div> : null}
                </div>
              ]
            : normalizedActions.length > 0
              ? normalizedActions
              : undefined;

        return <LayoutFormRow {...layoutFormRowProps} className={resolvedClassName} actions={resolvedActions} />;
      }}
    </Form.Item>
  );
}
