<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 700px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader
          :title="props.package ? 'Editar Pacote' : 'Novo Pacote'"
          @close="onDialogCancel"
        />

        <q-form ref="formRef" @submit="onOKClick">
          <q-card-section class="q-pt-sm">
            <div class="row q-col-gutter-sm">
              <DefaultInput
                v-model="form.name"
                label="Nome do Pacote"
                class="col-12"
              />

              <DefaultInput
                v-model="form.quantity_classes"
                label="Quantidade de Aulas"
                class="col-12"
                type="number"
              />

              <DefaultInput
                v-model="form.class_duration_hours"
                label="Duração da Aula (horas)"
                class="col-12"
                type="number"
                min="0.5"
                max="24"
                step="0.5"
              />

              <div class="col-12 package-duration-hint">
                A duração padrão das aulas é de 2 horas e pode ser alterada se
                necessário. É possível configurar no máximo dois dias.
              </div>

              <DefaultSelect
                v-model="form.weekday"
                label="1º Dia da Semana"
                class="col-4"
                :options="weekdays"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                clearable
              />

              <DefaultInput
                v-model="form.start_time"
                label="Horário Inicial"
                class="col-4"
                mask="##:##"
              />

              <DefaultInput
                :model-value="firstEndTime"
                label="Horário Final"
                class="col-4"
                disable
              />

              <DefaultSelect
                v-model="form.second_weekday"
                label="2º Dia da Semana"
                class="col-4"
                :options="secondWeekdayOptions"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                clearable
              />

              <DefaultInput
                v-model="form.second_start_time"
                label="Horário Inicial do 2º dia"
                class="col-4"
                mask="##:##"
              />

              <DefaultInput
                :model-value="secondEndTime"
                label="Horário Final do 2º dia"
                class="col-4"
                disable
              />

              <DefaultCurrencyInput
                v-model="form.contract_register_value"
                label="R$ Matrícula"
                class="col-4"
              />

              <DefaultCurrencyInput
                v-model="form.contract_value"
                label="R$ Total do Contrato"
                class="col-4"
              />

              <DefaultInput
                v-model="form.contrat_discount_value"
                label="Desconto em %"
                class="col-4"
                type="number"
                min="0"
                max="100"
              />

              <div
                v-for="(material, index) in form.materials"
                :key="index"
                class="col-12"
              >
                <div class="row q-col-gutter-sm items-center">
                  <DefaultSelect
                    v-model="material.product_id"
                    label="Material"
                    class="col"
                    :options="productOptions"
                    emit-value
                    map-options
                    @update:model-value="onProductSelected(material)"
                  />

                  <DefaultInput
                    v-model="material.quantity"
                    label="Qtd"
                    class="col-2"
                    type="number"
                    min="1"
                  />

                  <DefaultCurrencyInput
                    v-model="material.price"
                    label="R$ Unitário"
                    class="col-3"
                  />

                  <div class="col-auto">
                    <q-btn
                      v-if="index === form.materials.length - 1"
                      color="primary"
                      icon="mdi-plus"
                      unelevated
                      style="border-radius: 8px; height: 40px; width: 40px"
                      @click="addMaterial"
                    />
                    <q-btn
                      v-else
                      flat
                      round
                      dense
                      icon="mdi-delete-outline"
                      color="negative"
                      @click="removeMaterial(index)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </q-card-section>

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

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useDialogPluginComponent } 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 DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";

import {
  getUnitPackage,
  createUnitPackage,
  updateUnitPackage,
} from "src/api/package";
import { getProductsForSelect } from "src/api/product";

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

const props = defineProps({
  package: {
    type: Object,
    default: null,
  },
});

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

const formRef = ref(null);
const loading = ref(false);

const products = ref([]);

const weekdays = [
  { value: 1, label: "Segunda" },
  { value: 2, label: "Terça" },
  { value: 3, label: "Quarta" },
  { value: 4, label: "Quinta" },
  { value: 5, label: "Sexta" },
  { value: 6, label: "Sábado" },
  { value: 0, label: "Domingo" },
];

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

const calculateEndTime = (startTime, durationHours) => {
  if (!/^\d{2}:\d{2}$/.test(startTime ?? "")) return null;
  const [hours, minutes] = startTime.split(":").map(Number);
  if (hours > 23 || minutes > 59) return null;
  const end =
    (hours * 60 + minutes + Math.round(Number(durationHours) * 60)) %
    (24 * 60);
  return `${String(Math.floor(end / 60)).padStart(2, "0")}:${String(
    end % 60,
  ).padStart(2, "0")}`;
};

const productOptions = computed(() =>
  products.value.map((p) => ({
    label: p.name,
    value: p.id,
    price_sale: p.price_sale,
  })),
);

const form = ref({
  name: props.package?.name ?? null,
  quantity_classes: props.package?.quantity_classes ?? null,
  contract_register_value: props.package?.contract_register_value ?? null,
  contract_value: props.package?.contract_value ?? null,
  contrat_discount_value: props.package?.contrat_discount_value ?? null,
  class_duration_hours:
    (props.package?.class_duration_minutes ?? 120) / 60,
  weekday: props.package?.weekday ?? null,
  start_time: trimTime(props.package?.start_time),
  second_weekday: props.package?.second_weekday ?? null,
  second_start_time: trimTime(props.package?.second_start_time),
  materials: [{ product_id: null, quantity: 1, price: null }],
});

const secondWeekdayOptions = computed(() =>
  weekdays.filter((day) => day.value !== form.value.weekday),
);
const firstEndTime = computed(() =>
  calculateEndTime(form.value.start_time, form.value.class_duration_hours),
);
const secondEndTime = computed(() =>
  calculateEndTime(
    form.value.second_start_time,
    form.value.class_duration_hours,
  ),
);

watch(
  () => form.value.weekday,
  (weekday) => {
    if (form.value.second_weekday === weekday) {
      form.value.second_weekday = null;
    }
  },
);

const onProductSelected = (material) => {
  const option = productOptions.value.find(
    (o) => o.value === material.product_id,
  );
  if (option) material.price = option.price_sale;
};

const addMaterial = () => {
  form.value.materials.push({ product_id: null, quantity: 1, price: null });
};

const removeMaterial = (index) => {
  form.value.materials.splice(index, 1);
};

onMounted(async () => {
  const [allProducts] = await Promise.all([getProductsForSelect()]);
  products.value = allProducts;

  if (props.package?.id) {
    const pkg = await getUnitPackage(props.package.id);
    form.value.class_duration_hours =
      (pkg.class_duration_minutes ?? 120) / 60;
    form.value.weekday = pkg.weekday ?? null;
    form.value.start_time = trimTime(pkg.start_time);
    form.value.second_weekday = pkg.second_weekday ?? null;
    form.value.second_start_time = trimTime(pkg.second_start_time);
    if (pkg.materials?.length) {
      form.value.materials = pkg.materials.map((m) => ({
        product_id: m.product_id,
        quantity: m.quantity,
        price: m.price,
      }));
    }
  }
});

const onOKClick = async () => {
  loading.value = true;
  try {
    const validMaterials = form.value.materials.filter((m) => m.product_id);

    const payload = {
      name: form.value.name,
      quantity_classes: form.value.quantity_classes,
      contract_value: form.value.contract_value,
      contract_register_value: form.value.contract_register_value,
      contrat_discount_value: form.value.contrat_discount_value,
      class_duration_minutes: Math.round(
        Number(form.value.class_duration_hours) * 60,
      ),
      weekday: form.value.weekday,
      start_time: form.value.start_time || null,
      second_weekday: form.value.second_weekday,
      second_start_time: form.value.second_start_time || null,
      materials: validMaterials.map((m) => ({
        product_id: m.product_id,
        quantity: Number(m.quantity),
        price: Number(m.price),
      })),
    };

    const result = props.package?.id
      ? await updateUnitPackage(props.package.id, payload)
      : await createUnitPackage(payload);

    onDialogOK(result);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.package-duration-hint {
  color: #757575;
  font-size: 12px;
  line-height: 1.35;
  padding-top: 4px;
  padding-bottom: 2px;
}
</style>
