<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 560px">
      <q-card style="display: flex; flex-direction: column; overflow: hidden">
        <DefaultDialogHeader
          :title="classData ? 'Editar Aula' : 'Nova Aula'"
          @close="onDialogCancel"
        />

        <q-form ref="formRef" @submit="onSubmit">
          <q-card-section class="q-pt-sm">
            <div class="row q-col-gutter-sm">
              <!-- Nome da Atividade -->
              <DefaultInput
                v-model="form.title"
                label="Nome da Atividade"
                class="col-12"
                :rules="[(v) => !!v || 'Campo obrigatório']"
              />

              <!-- Pacote vinculado -->
              <DefaultSelect
                v-model="form.class_package_unit_id"
                label="Pacote relacionado"
                :options="packageOptions"
                option-value="id"
                option-label="name"
                emit-value
                map-options
                :loading="loadingPackages"
                class="col-12"
                :rules="[(v) => !!v || 'Campo obrigatório']"
              />

              <!-- Horários -->
              <DefaultInput
                v-model="form.start_time"
                label="Hora de Início"
                mask="##:##"
                placeholder="08:40"
                class="col-6"
                :rules="[(v) => !!v || 'Campo obrigatório']"
              >
                <template #append>
                  <q-icon name="mdi-clock-outline" class="cursor-pointer" color="secondary">
                    <q-popup-proxy transition-show="scale" transition-hide="scale">
                      <q-time v-model="form.start_time" format24h mask="HH:mm">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="OK" color="primary" flat />
                        </div>
                      </q-time>
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </DefaultInput>

              <DefaultInput
                v-model="form.end_time"
                label="Hora de Fim"
                mask="##:##"
                placeholder="09:40"
                class="col-6"
                :rules="[
                  (v) => !!v || 'Campo obrigatório',
                  (v) => !form.start_time || v > form.start_time || 'Fim deve ser após o início',
                ]"
              >
                <template #append>
                  <q-icon name="mdi-clock-outline" class="cursor-pointer" color="secondary">
                    <q-popup-proxy transition-show="scale" transition-hide="scale">
                      <q-time v-model="form.end_time" format24h mask="HH:mm">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="OK" color="primary" flat />
                        </div>
                      </q-time>
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </DefaultInput>

              <!-- Instrutor (Neurotrainer da unidade) -->
              <DefaultSelect
                v-model="form.instructor"
                label="Neurotrainer"
                :options="instructorOptions"
                option-value="name"
                option-label="name"
                emit-value
                map-options
                clearable
                :loading="loadingInstructors"
                class="col-6"
              />

              <!-- Sala -->
              <DefaultInput
                v-model="form.room"
                label="Número da Sala"
                class="col-6"
              />

              <!-- Data de início da aula -->
              <DefaultInputDatePicker
                v-model="form.date_display"
                v-model:untreated-date="form.date"
                label="Data de Início"
                class="col-12"
                :rules="[(v) => !!v || 'Campo obrigatório']"
              />
            </div>
          </q-card-section>

          <q-card-actions align="right" class="q-px-md q-pb-md">
            <q-btn outline color="primary" label="Cancelar" no-caps @click="onDialogCancel" />
            <q-btn
              type="submit"
              color="primary"
              label="Salvar"
              no-caps
              :loading="saving"
            />
          </q-card-actions>
        </q-form>
      </q-card>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useDialogPluginComponent, useQuasar } from "quasar";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";

import { createClass, updateClass } from "src/api/class";
import { getUnitPackagesForSelect } from "src/api/package";
import { getUsersByUnit } from "src/api/user";

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

const props = defineProps({
  classData: { type: Object, default: null },
  // Data pré-selecionada ao adicionar a partir de um dia do calendário (YYYY-MM-DD)
  initialDate: { type: String, default: null },
});

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

const $q = useQuasar();

const formRef = ref(null);
const saving = ref(false);
const loadingPackages = ref(false);
const packageOptions = ref([]);
const loadingInstructors = ref(false);
const instructorOptions = ref([]);

const toDisplay = (isoDate) =>
  isoDate ? isoDate.split("-").reverse().join("/") : null;

const form = reactive({
  title: props.classData?.title ?? "",
  class_package_unit_id: props.classData?.class_package_unit_id ?? null,
  instructor: props.classData?.instructor ?? "",
  room: props.classData?.room ?? "",
  start_time: props.classData?.date_time_start?.slice(11, 16) ?? "",
  end_time: props.classData?.date_time_end?.slice(11, 16) ?? "",
  date: props.classData?.date_time_start?.slice(0, 10) ?? props.initialDate ?? null,
  date_display: toDisplay(
    props.classData?.date_time_start?.slice(0, 10) ?? props.initialDate,
  ),
});

const trimTime = (time) => (time ? time.slice(0, 5) : "");

function calculateEndTime(startTime, durationMinutes = 120) {
  if (!/^\d{2}:\d{2}$/.test(startTime ?? "")) return "";
  const [hours, minutes] = startTime.split(":").map(Number);
  if (hours > 23 || minutes > 59) return "";

  const endMinutes = (hours * 60 + minutes + durationMinutes) % (24 * 60);
  return `${String(Math.floor(endMinutes / 60)).padStart(2, "0")}:${String(
    endMinutes % 60,
  ).padStart(2, "0")}`;
}

function selectedPackage() {
  return packageOptions.value.find(
    (pkg) => pkg.id === form.class_package_unit_id,
  );
}

function applyPackageSchedule() {
  if (props.classData) return;
  const pkg = selectedPackage();
  if (!pkg) return;

  const selectedWeekday = form.date
    ? new Date(`${form.date}T00:00:00`).getDay()
    : null;
  const startTime =
    selectedWeekday === pkg.second_weekday
      ? pkg.second_start_time
      : pkg.start_time;

  form.start_time = trimTime(startTime);
  form.end_time = calculateEndTime(
    form.start_time,
    pkg.class_duration_minutes ?? 120,
  );
}

watch(() => form.class_package_unit_id, applyPackageSchedule);
watch(() => form.date, applyPackageSchedule);
watch(
  () => form.start_time,
  (startTime) => {
    const endTime = calculateEndTime(
      startTime,
      selectedPackage()?.class_duration_minutes ?? 120,
    );
    if (endTime) form.end_time = endTime;
  },
);

const loadPackages = async () => {
  loadingPackages.value = true;
  try {
    packageOptions.value = await getUnitPackagesForSelect();
  } finally {
    loadingPackages.value = false;
  }
};

const loadInstructors = async () => {
  loadingInstructors.value = true;
  try {
    const users = await getUsersByUnit();
    instructorOptions.value = (users ?? []).filter(
      (u) =>
        u.user_type_system_key === "NEUROTRAINER" ||
        u.user_type === "NEUROTRAINER",
    );
  } catch (e) {
    console.error("Erro ao carregar neurotrainers:", e);
  } finally {
    loadingInstructors.value = false;
  }
};

const onSubmit = async () => {
  const valid = await formRef.value.validate();
  if (!valid) return;

  const payload = {
    title: form.title,
    class_package_unit_id: form.class_package_unit_id,
    instructor: form.instructor || null,
    room: form.room || null,
    date_time_start: `${form.date}T${form.start_time}:00`,
    date_time_end: `${form.date}T${form.end_time}:00`,
  };

  saving.value = true;
  try {
    if (props.classData?.id) {
      await updateClass(payload, props.classData.id);
    } else {
      await createClass(payload);
    }
    $q.notify({ type: "positive", message: "Aula salva com sucesso." });
    onDialogOK(true);
  } catch {
    // O interceptor do axios já notifica os erros de validação/servidor
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  loadPackages();
  loadInstructors();
});
</script>
