<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin column full-width" style="width: 900px; max-width: 80vw;height: 90vh;">
      <DefaultDialogHeader :title="title" class="col-12" @close="onDialogCancel"/>

      <q-tabs v-model="tab" dense class="text-grey" active-color="primary" indicator-color="primary" align="justify">
        <q-tab name="data" label="Dados" />
        <q-tab v-if="provider" name="addresses" :label="$t('address.tab')" />
        <q-tab v-if="provider" name="payment_methods" :label="$t('provider_payment_methods.header')" />
        <q-tab v-if="provider" name="working_days" :label="$t('provider_working_days.header')" />
        <q-tab v-if="provider" name="blocked_days" :label="$t('provider_blocked_days.header')" />
        <q-tab v-if="provider" name="blocked_clients" :label="$t('provider_client_blocks.tab')" />
        <q-tab v-if="provider" name="sent_reviews" :label="$t('provider_reviews.sent_tab')" />
        <q-tab v-if="provider" name="received_reviews" :label="$t('provider_reviews.received_tab')" />
      </q-tabs>

      <q-separator v-if="provider" />
      <div class="col no-padding scroll">
        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="data">
            <q-form ref="formRef" @submit="onOKClick">
              <q-card-section class="row q-col-gutter-sm no-padding scroll">
                <UserSelect
                  v-model="selectedUser"
                  :label="$t('common.terms.user')"
                  :rules="[inputRules.required]"
                  :error="!!serverErrors?.user_id"
                  :error-message="serverErrors?.user_id"
                  :initial-id="provider ? provider.user_id : null"
                  class="col-md-6 col-12"
                />

                <q-input
                  v-model="form.document"
                  :mask="documentMask"
                  fill-mask
                  unmasked-value
                  :label="$t('provider.fields.document')"
                  :rules="[inputRules.required, validateDocument]"
                  :error="!!serverErrors?.document"
                  :error-message="serverErrors?.document"
                  class="col-md-6 col-12"
                />

                <q-input
                  v-model="form.rg"
                  mask="##.###.###-#"
                  fill-mask
                  :label="$t('provider.fields.rg')"
                  :error="!!serverErrors?.rg"
                  :error-message="serverErrors?.rg"
                  class="col-md-6 col-12"
                />
                <DefaultInputDatePicker
                  v-model:untreated-date="form.birth_date"
                  :label="$t('provider.fields.birth_date')"
                  :error="serverErrors?.birth_date"
                  :error-message="serverErrors?.birth_date"
                  class="col-md-6 col-12"
                />

                <DefaultCurrencyInput
                  v-model="form.daily_price_8h"
                  :label="$t('provider.fields.daily_price_8h')"
                  :error="!!serverErrors?.daily_price_8h"
                  :error-message="serverErrors?.daily_price_8h"
                  :hint="$t('provider.hints.daily_price')"
                  lazy-rules
                  class="col-md-3 col-6"
                />

                <DefaultCurrencyInput
                  v-model="form.daily_price_6h"
                  :label="$t('provider.fields.daily_price_6h')"
                  :error="!!serverErrors?.daily_price_6h"
                  :error-message="serverErrors?.daily_price_6h"
                  disable
                  class="col-md-3 col-6"
                />

                <DefaultCurrencyInput
                  v-model="form.daily_price_4h"
                  :label="$t('provider.fields.daily_price_4h')"
                  :error="!!serverErrors?.daily_price_4h"
                  :error-message="serverErrors?.daily_price_4h"
                  disable
                  class="col-md-3 col-6"
                />

                <DefaultCurrencyInput
                  v-model="form.daily_price_2h"
                  :label="$t('provider.fields.daily_price_2h')"
                  :error="!!serverErrors?.daily_price_2h"
                  :error-message="serverErrors?.daily_price_2h"
                  disable
                  class="col-md-3 col-6"
                />

                <div class="col-12">
                  <q-select
                    v-model="form.approval_status"
                    :options="approvalStatusOptions"
                    :label="$t('provider.fields.approval_status')"
                    emit-value
                    map-options
                    outlined
                    dense
                    :error="!!serverErrors?.approval_status"
                    :error-message="serverErrors?.approval_status"
                    class="col-12"
                  />
                </div>

                <ProviderSpecialitiesPanel v-if="provider" :provider-id="provider.id" />

                <ProviderServicesTypesPanel v-if="provider" :provider-id="provider.id" />

                <div class="col-12 q-mt-md">
                  <div class="row q-col-gutter-md">
                    <div class="col-auto flex items-center">
                      <q-avatar size="80px" color="grey-3">
                        <q-icon name="mdi-account" size="50px" color="grey-6" />
                      </q-avatar>
                    </div>

                    <div class="col row q-col-gutter-sm">
                      <div class="col-md-6 col-12">
                        <div class="text-subtitle2 text-grey-7">
                          {{ $t('provider.fields.average_rating') }}
                        </div>
                        <div class="text-body1 text-weight-medium">
                          {{ provider?.average_rating || '-' }}
                        </div>
                      </div>

                      <div class="col-md-6 col-12">
                        <div class="text-subtitle2 text-grey-7">
                          {{ $t('provider.fields.total_services') }}
                        </div>
                        <div class="text-body1 text-weight-medium">
                          {{ provider?.total_services || '0' }}
                        </div>
                      </div>

                      <div class="col-md-6 col-12">

                        <div class="text-subtitle2 text-grey-7 q-mb-sm">
                          {{ $t('provider.fields.selfie_verified') }}
                        </div>

                        <q-checkbox
                          v-model="form.selfie_verified"
                          label="Verificar foto"
                          color="primary"
                        />

                      </div>

                      <div class="col-md-6 col-12">

                        <div class="text-subtitle2 text-grey-7 q-mb-sm">
                          {{ $t('provider.fields.document_verified') }}
                        </div>

                        <q-checkbox
                          v-model="form.document_verified"
                          label="Validar documentos"
                          color="primary"
                        />

                      </div>
                    </div>
                  </div>
                </div>
              </q-card-section>
              <q-card-actions align="right">
                <q-btn
                  :label="$t('common.actions.close')"
                  flat
                  color="primary"
                  @click="onDialogCancel"
                />
                <q-btn 
                  color="secondary"
                  :label="$t('common.actions.save')"
                  type="submit"
                  unelevated
                  :loading="loading"
                  :disable="!hasUpdatedFields"
                />
              </q-card-actions>
            </q-form>
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="addresses">
            <AddressesPanel :source="'provider'" :source-id="provider.id" />
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="payment_methods">
            <ProviderPaymentMethodsPanel :provider-id="provider.id" />
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="working_days">
            <ProviderWorkingDaysPanel :provider-id="provider.id" />
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="blocked_days">
            <ProviderBlockedDaysPanel :provider-id="provider.id" />
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="blocked_clients">
            <ProviderClientsBlocksPanel :provider-id="provider.id" />
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="sent_reviews">
            <ProviderReviewsPanel :provider-id="provider.id" type="sent" />
          </q-tab-panel>

          <q-tab-panel v-if="provider" name="received_reviews">
            <ProviderReviewsPanel :provider-id="provider.id" type="received" />
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </q-card>
  </q-dialog>
</template>
<script setup>
import { ref, useTemplateRef, onMounted, watch, computed } from "vue";
import { useInputRules } from "src/composables/useInputRules";
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import { createProvider, updateProvider } from "src/api/provider";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { dynamicCpfCnpjMask, validateCpfCnpj, calculateDailyPrices } from "src/helpers/utils";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import UserSelect from "src/components/user/UserSelect.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import AddressesPanel from "src/pages/address/components/AddressesPanel.vue";
import ProviderSpecialitiesPanel from "./ProviderSpecialitiesPanel.vue";
import ProviderServicesTypesPanel from "./ProviderServicesTypesPanel.vue";
import ProviderPaymentMethodsPanel from "./ProviderPaymentMethodsPanel.vue";
import ProviderWorkingDaysPanel from "./ProviderWorkingDaysPanel.vue";
import ProviderBlockedDaysPanel from "./ProviderBlockedDaysPanel.vue";
import ProviderClientsBlocksPanel from "./ProviderClientsBlocksPanel.vue";
import ProviderReviewsPanel from "./ProviderReviewsPanel.vue";

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

const { provider, title } = defineProps({
  provider: {
    type: Object,
    default: null,
  },
  title: {
    type: Function,
    default: () => useI18n().t("common.terms.title"),
  },
});

const { t } = useI18n();
const { inputRules } = useInputRules();

const approvalStatusOptions = computed(() => [
  { label: t("provider.approval_status.pending"),  value: "pending" },
  { label: t("provider.approval_status.accepted"), value: "accepted" },
  { label: t("provider.approval_status.rejected"), value: "rejected" },
]);

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

const formRef = useTemplateRef("formRef");
const tab = ref("data");

const { form, getUpdatedFields, hasUpdatedFields } = useFormUpdateTracker({
  user_id: provider ? provider?.user_id : null,
  document: provider ? provider?.document : "",
  rg: provider ? provider?.rg : "",
  birth_date: provider ? provider?.birth_date : null,
 selfie_verified: provider? provider?.selfie_verified:false,
 document_verified: provider? provider?.document_verified:false,
  approval_status: provider ? provider?.approval_status : "pending",
  daily_price_8h: provider ? Number(provider?.daily_price_8h) : null,
  daily_price_6h: provider ? Number(provider?.daily_price_6h) : null,
  daily_price_4h: provider ? Number(provider?.daily_price_4h) : null,
  daily_price_2h: provider ? Number(provider?.daily_price_2h) : null,
});

const {
  loading,
  serverErrors,
  execute: submitForm,
} = useSubmitHandler({
  onSuccess: () => onDialogOK(true),
  formRef: formRef,
});

const selectedUser = ref(null);

const documentMask = computed(() => {
  return dynamicCpfCnpjMask(form.document);
});

const validateDocument = (val) => {
  if (!val) return true;
  return validateCpfCnpj(val) || t("validation.rules.cpf") + " / " + t("validation.rules.cnpj");
};

const onOKClick = async () => {
  if (provider) {
    await submitForm(() => updateProvider(getUpdatedFields.value, provider.id));
  } else {
    await submitForm(() => createProvider({ ...form }));
  }
};

watch(selectedUser, () => {
  form.user_id = selectedUser.value?.value;
});

watch(
  () => form.daily_price_8h,
  (newValue) => {
    const prices = calculateDailyPrices(newValue);
    form.daily_price_6h = prices.daily_price_6h;
    form.daily_price_4h = prices.daily_price_4h;
    form.daily_price_2h = prices.daily_price_2h;
  }
);

onMounted(async () => {
  if (provider) {
    selectedUser.value = {
      label: provider.user?.name || "",
      value: provider.user?.id,
    };
  }
});
</script>
