<template>
  <q-dialog
    ref="dialogRef"
    maximized
    persistent
    transition-hide="slide-right"
    transition-show="slide-left"
  >
    <q-card class="bg-white full-height full-width">
      <div
        class="bg-surface bg-white dialog-safe-header items-center q-pb-sm q-px-md row shadow-profile"
      >
        <q-btn
          color="primary"
          dense
          flat
          icon="mdi-chevron-left"
          round
          @click="onDialogCancel"
        />

        <q-space />

        <span class="font16 fontbold gradient-diarista">
          {{ $t("profile.edit_data") }}
        </span>

        <q-space />

        <div style="width: 32px" />
      </div>

      <div
        v-if="loading"
        class="flex flex-center q-pa-xl"
      >
        <q-spinner
          color="primary"
          size="3em"
        />
      </div>

      <template v-else>
        <q-scroll-area
          class="col"
          style="height: calc(100vh - 72px)"
        >
          <div class="column items-center q-mb-md q-mt-xl">
            <q-avatar
              class="shadow-1"
              size="140px"
              :style="!profilePhoto ? avatarStyle : undefined"
            >
              <img
                v-if="profilePhoto"
                :src="profilePhoto"
                style="border-radius: 50%; height: 100%; object-fit: cover; width: 100%"
              />

              <span
                v-else
                style="color: #7a154f"
              >
                {{ form.name ? form.name.slice(0, 2).toUpperCase() : "" }}
              </span>
            </q-avatar>

            <q-btn
              class="font12 fontregular q-mt-sm"
              color="grey-6"
              flat
              no-caps
              :label="$t('profile.change_photo')"
              :loading="capturingPhoto"
              @click="takeSelfie"
            />
          </div>

          <div class="q-gutter-y-lg q-px-xl">
            <div>
              <div class="font12 fontbold q-mb-sm text-grey-8">
                {{ $t("profile.full_name") }}
              </div>

              <q-input
                v-model="form.name"
                dense
                input-class="text-text"
                outlined
                :placeholder="$t('profile.placeholder_name')"
              />
            </div>

            <div>
              <div class="font12 fontbold q-mb-sm text-grey-8">
                {{ $t("profile.email") }}
              </div>

              <q-input
                v-model="form.email"
                dense
                input-class="text-text"
                outlined
                :placeholder="$t('profile.placeholder_email')"
              />
            </div>

            <div>
              <div class="font12 fontbold q-mb-sm text-grey-8">
                {{ $t("profile.phone") }}
              </div>

              <q-input
                v-model="form.phone"
                dense
                input-class="text-text"
                mask="(##) #####-####"
                outlined
                unmasked-value
                :placeholder="$t('profile.placeholder_phone')"
              />
            </div>

            <div>
              <div class="font12 fontbold q-mb-sm text-grey-8">
                {{ $t("common.gender") }}
              </div>

              <q-option-group
                v-model="form.gender"
                class="gender-options text-text"
                color="primary"
                type="radio"
                :options="translatedGenderOptions"
              />
            </div>

            <div>
              <div class="font12 fontbold q-mb-sm text-grey-8">
                {{ $t("profile.language") }}
              </div>

              <div class="row">
                <q-radio
                  v-model="selectedLocale"
                  class="text-text col-4 font10 fontmedium"
                  color="primary"
                  keep-color
                  val="pt"
                  :label="$t('profile.lang_pt')"
                  @update:model-value="onLocaleChange"
                />

                <q-radio
                  v-model="selectedLocale"
                  class="text-text col-4 font10 fontmedium"
                  color="primary"
                  keep-color
                  val="en"
                  :label="$t('profile.lang_en')"
                  @update:model-value="onLocaleChange"
                />

                <q-radio
                  v-model="selectedLocale"
                  class="text-text col-4 font10 fontmedium"
                  color="primary"
                  keep-color
                  val="es"
                  :label="$t('profile.lang_es')"
                  @update:model-value="onLocaleChange"
                />
              </div>
            </div>

            <!-- NOVA SEÇÃO -->
            <div>
              <div class="font12 fontbold q-mb-sm text-grey-8">
                {{ $t("profile.notifications") }}
              </div>

              <div class="notification-card">
                <span class="font14 text-text">
                  {{ $t("profile.push_notifications") }}
                </span>

                <q-toggle
                  v-model="form.push_notifications_enabled"
                  color="primary"
                />
              </div>
            </div>
          </div>

          <q-space />

          <div class="q-mt-md q-pa-xl">
            <q-btn
              class="full-width q-py-md"
              no-caps
              padding="8px 16px"
              rounded
              unelevated
              :color="hasChanges ? 'primary' : 'grey-4'"
              :disable="!hasChanges"
              :label="$t('profile.update')"
              :loading="submitting"
              @click="submitUpdate"
            />
          </div>
        </q-scroll-area>
      </template>
    </q-card>
  </q-dialog>
</template>

<script setup>
import {
  Camera,
  CameraDirection,
  CameraResultType,
  CameraSource,
} from "@capacitor/camera";

import { Cookies, useDialogPluginComponent, useQuasar } from "quasar";
import { computed, onMounted, ref } from "vue";
import { genderOptions } from "src/helpers/genderOptions";
import { getUser, updateUser } from "src/api/user";
import { i18n } from "src/boot/i18n";
import { updateProviderWithFiles } from "src/api/provider";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useI18n } from "vue-i18n";

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

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

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

const $q = useQuasar();

const { form, getUpdatedFields, hasUpdatedFields, setUpdateFormAsOriginal } =
  useFormUpdateTracker({
    email: "",
    gender: "",
    name: "",
    phone: "",
    push_notifications_enabled: false,
  });

const capturingPhoto = ref(false);
const loading        = ref(false);
const profilePhoto   = ref(null);
const providerId     = ref(null);
const selfieFile     = ref(null);
const submitting     = ref(false);
const userId         = ref(null);

const normalizeLocale = (loc) => {
  if (!loc) return "pt";

  const l = String(loc).toLowerCase();

  if (l.startsWith("pt")) return "pt";
  if (l.startsWith("en")) return "en";
  if (l.startsWith("es")) return "es";

  return "pt";
};

const selectedLocale = ref(
  normalizeLocale(i18n.global.locale.value ?? i18n.global.locale),
);

const hasChanges = computed(
  () => hasUpdatedFields.value || !!selfieFile.value,
);

const translatedGenderOptions = computed(() =>
  genderOptions.map((option) => ({
    ...option,
    label: t(option.label),
  })),
);

const avatarStyle = {
  background: "linear-gradient(135deg, #ffd7e8 0%, #ff9acc 100%)", color: "#7a154f",
};

const base64ToFile = (base64, mimeType) => {
  const byteString = atob(base64);

  const bytes = new Uint8Array(byteString.length);

  for (let index = 0; index < byteString.length; index++) {
    bytes[index] = byteString.charCodeAt(index);
  }

  return new File([bytes], "selfie.jpg", { type: mimeType });
};

const isCameraCancellation = (error) => {
  const message = String(error?.message ?? "").toLowerCase();

  return (
    message.includes("cancel")
    || message.includes("dismiss")
    || message.includes("no image")
  );
};

const takeSelfie = async () => {
  if (capturingPhoto.value) return;

  capturingPhoto.value = true;

  try {
    const photo = await Camera.getPhoto({
      allowEditing: false,
      direction: CameraDirection.Front,
      quality: 85,
      resultType: CameraResultType.Base64,
      saveToGallery: false,
      source: CameraSource.Camera,
    });

    const base64 = photo.base64String?.replace(/\s/g, "");

    if (!base64) {
      throw new Error("Camera did not return image data");
    }

    const mimeType = `image/${photo.format || "jpeg"}`;

    selfieFile.value = base64ToFile(base64, mimeType);

    profilePhoto.value = `data:${mimeType};base64,${base64}`;
  } catch (error) {
    if (!isCameraCancellation(error)) {
      console.error("Erro ao capturar selfie:", error);

      $q.notify({
        message: t("profile.photo_capture_error"),
        type: "negative",
      });
    }
  } finally {
    capturingPhoto.value = false;
  }
};

const onLocaleChange = (val) => {
  i18n.global.locale.value = val;

  Cookies.set("locale", val, { expires: 365, path: "/" });
};

const submitUpdate = async () => {
  if (!hasChanges.value) return;

  submitting.value = true;

  try {
    const userData = { ...getUpdatedFields.value };
    console.log("Campos atualizados:", userData);

    let data = null;

    if (Object.keys(userData).length > 0) {
      data = await updateUser(userData, userId.value);
    }

    if (selfieFile.value) {
      await updateProviderWithFiles(providerId.value, {
        avatar: selfieFile.value,
      });

      data = await getUser();
    }

    setUpdateFormAsOriginal();

    selfieFile.value = null;

    onDialogOK(data);
  } catch (error) {
    console.error("Erro ao atualizar perfil:", error);
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  if (!props.userData) {
    loading.value = true;

    return;
  }

  const data = props.userData;

  form.email = data.email || "";
  form.gender = data.gender || "";
  form.name = data.name || "";
  form.phone = data.phone || "";
  form.push_notifications_enabled = data.push_notifications_enabled ?? false;
  profilePhoto.value = data.profile_photo || null;
  providerId.value = data.provider_id || data.provider?.id || null;
  userId.value = data.id;

  setUpdateFormAsOriginal();
});
</script>

<style lang="scss" scoped>
:deep(.q-field--outlined .q-field__control) {
  border-radius: 8px;

  &::before {
    border: 1px solid #e0e0e0;
  }
}

.gender-options :deep(.q-radio__inner--falsy) {
  color: rgba(0, 0, 0, 0.62);
}

.notification-card {
  display: flex;
  align-items: center;
  justify-content: space-between;

  min-height: 56px;
  padding: 0 16px;

  border: 1px solid #e0e0e0;
  border-radius: 8px;

  background: #fff;
}

.notification-card :deep(.q-toggle__inner--falsy) {
  color: rgba(0, 0, 0, 0.62);

  .q-toggle__thumb:after {
    box-shadow:
      0 0 0 1px #bdbdbd,
      0 2px 2px 0 rgba(0, 0, 0, 0.14);
  }
}
</style>
