<template>
  <UDashboardPanel
    :ui="{
  body: 'flex-row p-0 sm:p-0 gap-0 sm:gap-0'
}"
  >
    <template #header>
      <UDashboardNavbar :title="title" :ui="{ right: 'gap-2' }">
        <template v-if="toBack" #leading>
          <UButton :to="toBack" variant="link" :icon="appConfig.ui.icons.arrowLeft" />
        </template>
        <template #right>
          <slot name="actions" />

          <UButton
            type="submit"
            label="Сохранить"
            :icon="appConfig.ui.icons.save"
            :form="formId"
            :loading="loading"
            loading-auto
          />
        </template>
      </UDashboardNavbar>
    </template>
    <template #body>
      <UForm
        :id="formId"
        :state="state"
        :schema="schema"
        :class="ui.form({ class: props.ui?.form })"
        :validate-on="['input']"
        @submit="submitHandler"
      >
        <div :class="ui.body({ class: props.ui?.body })">
          <slot />
        </div>
        <div v-if="$slots.sidebar" :class="ui.sidebar({ class: props.ui?.sidebar })">
          <slot name="sidebar" />
        </div>
      </UForm>
    </template>
  </UDashboardPanel>
</template>

<script>
import theme from "#build/cms/form-panel";
import { useAppConfig } from "#imports";
import { computed, useId } from "vue";
import { tv } from "../tv";
</script>

<script setup>
const props = defineProps({
  title: { type: String, required: false },
  toBack: { type: null, required: false },
  formId: { type: String, required: false },
  schema: { type: null, required: true },
  state: { type: Object, required: true },
  loading: { type: Boolean, required: false },
  handler: { type: Function, required: true },
  asideDivide: { type: Boolean, required: false },
  bodyFit: { type: Boolean, required: false, default: true },
  showReset: { type: Boolean, required: false },
  class: { type: null, required: false },
  ui: { type: null, required: false }
});
defineEmits(["update:state"]);
defineSlots();
const appConfig = useAppConfig();
const formId = computed(() => props.formId ?? `form-${useId()}`);
async function submitHandler(event) {
  await props.handler?.(event);
}
const ui = computed(() => tv({ extend: tv(theme), ...appConfig.cms?.formPanel || {} })({
  bodyFit: props.bodyFit,
  asideDivide: props.asideDivide
}));
</script>
