<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin dialog-form-card"
      style="width: 100%; max-width: 1400px"
    >
      <DefaultDialogHeader
        title="Dados do Aluno"
        @close="onDialogCancel"
      />

      <q-scroll-area
        class="dialog-form-scroll"
        style="height: 65vh"
      >
        <q-card-section class="q-pt-sm">
          <CustomTabComponent
            v-model:active-tab="currentTab"
            class="q-mb-md"
            :tabs="tabs"
          />

          <div v-show="currentTab === 'profile'">
            <StudentDataTab
              ref="studentDataTabRef"
              :student="props.student"
              :validation-errors="validationErrors"
            />
          </div>

          <div v-show="currentTab === 'responsible'">
            <ResponsibleTab
              ref="responsibleTabRef"
              :required="studentIsUnderage"
              :student-id="props.student.id"
            />
          </div>

          <div
            v-if="canViewContracts"
            v-show="currentTab === 'contracts'"
          >
            <ContractTab :student="props.student" />
          </div>

          <div
            v-if="canViewClasses"
            v-show="currentTab === 'history'"
          >
            <HistoryTab />
          </div>

          <div v-show="currentTab === 'media'">
            <MediaTab
              ref="mediaTabRef"
              :student-id="props.student.id"
            />
          </div>
        </q-card-section>
      </q-scroll-area>

      <q-card-actions
        align="right"
        class="q-px-md q-pb-md"
      >
        <q-btn
          color="primary"
          label="Cancelar"
          no-caps
          outline
          @click="onDialogCancel"
        />

        <q-btn
          color="primary"
          label="Salvar"
          no-caps
          :loading="saving"
          @click="handleSave"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import {
  computed,
  defineAsyncComponent,
  ref,
  useTemplateRef,
  watch,
} from "vue";

import { isUnderage } from "src/helpers/utils";
import { permissionStore } from "src/stores/permission";
import { updateStudent } from "src/api/student";
import { useDialogPluginComponent, useQuasar } from "quasar";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import CustomTabComponent from "src/components/shared/CustomTabComponent.vue";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";

const ContractTab = defineAsyncComponent(
  () => import("src/pages/students/tabs/ContractTab.vue"),
);

const HistoryTab = defineAsyncComponent(
  () => import("src/pages/students/tabs/HistoryTab.vue"),
);

const MediaTab = defineAsyncComponent(
  () => import("src/pages/students/tabs/MediaTab.vue"),
);

const ResponsibleTab = defineAsyncComponent(
  () => import("src/pages/students/tabs/ResponsibleTab.vue"),
);

const StudentDataTab = defineAsyncComponent(
  () => import("src/pages/students/tabs/StudentDataTab.vue"),
);

defineEmits([...useDialogPluginComponent.emits]);

const props = defineProps({
  student: {
    type: Object,
    required: true,
  },
});

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const $q = useQuasar();

const permissions = permissionStore();

const mediaTabRef = useTemplateRef("mediaTabRef");
const responsibleTabRef = useTemplateRef("responsibleTabRef");
const studentDataTabRef = useTemplateRef("studentDataTabRef");

const currentTab = ref("profile");

const canViewClasses = computed(() =>
  permissions.getAccess("franchisee_classes", "view"),
);

const canViewContracts = computed(() =>
  permissions.getAccess("franchisee_contracts", "view"),
);

const studentIsUnderage = computed(() =>
  isUnderage(props.student.birth_date),
);

const tabs = computed(() => [
  {
    label: "Perfil do Aluno",
    name: "profile",
  },
  {
    label: "Responsáveis",
    name: "responsible",
  },
  ...(canViewContracts.value
    ? [
        {
          label: "Contratos",
          name: "contracts",
        },
      ]
    : []),
  ...(canViewClasses.value
    ? [
        {
          label: "Frequência",
          name: "history",
        },
      ]
    : []),
  {
    label: "Mídias",
    name: "media",
  },
]);

const {
  loading: saving,
  validationErrors,
  execute,
} = useSubmitHandler({
  onSuccess: () => {
    onDialogOK(true);
  },
});

const handleSave = async () => {
  const valid = await (
    studentDataTabRef.value?.validate() ?? true
  );

  if (!valid) return;

  const underage =
    studentDataTabRef.value?.isUnderage() ?? false;

  const hasRequiredResponsible = underage
    ? await responsibleTabRef.value?.validateRequired(true)
    : true;

  if (!hasRequiredResponsible) {
    currentTab.value = "responsible";

    $q.notify({
      message:
        "Cadastre ao menos um responsável para o aluno menor de idade.",
      type: "warning",
    });

    return;
  }

  const studentPayload =
    studentDataTabRef.value.buildPayload();

  await execute(() =>
    updateStudent(
      studentPayload,
      props.student.id,
    ),
  );
};

watch(currentTab, (tab) => {
  if (tab === "media") {
    mediaTabRef.value?.refresh();
  }
});
</script>