<template>
  <q-card-section class="no-padding">
    <div class="column items-center q-gutter-y-xl q-pt-md">

      <div class="column items-center q-gutter-y-sm">
        <div
          class="photo-circle"
          :class="selfieDone ? 'photo-circle--done' : 'photo-circle--pending'"
          @click="takeSelfie"
        >
          <q-icon name="photo_camera" size="52px" color="white" />
        </div>

        <template v-if="!selfieDone">
          <q-btn
            color="primary-button"
            :label="t('provider.login.steps.step_4.btn_selfie')"
            rounded
            no-caps
            padding="10px 28px"
            :loading="loadingSelfie"
            @click="takeSelfie"
          />
          <div class="text-text text-center font12">{{ t('provider.login.steps.step_4.selfie_hint') }}</div>
        </template>
        <template v-else>
          <div class="row items-center q-gutter-x-xs">
            <q-icon name="check_circle" color="positive" size="18px" />
            <span class="text-primary">{{ t('provider.login.steps.step_4.selfie_sent') }}</span>
          </div>
        </template>
      </div>

      <div class="column items-center q-gutter-y-sm">
        <div
          class="photo-circle"
          :class="docDone ? 'photo-circle--done' : 'photo-circle--pending'"
          @click="takeDocFront"
        >
          <q-icon name="mdi-card-account-details-outline" size="52px" color="white" />
        </div>

        <template v-if="!docDone">
          <q-btn
            color="primary-button"
            :label="t('provider.login.steps.step_4.btn_document')"
            rounded
            no-caps
            padding="10px 28px"
            :loading="loadingDoc"
            @click="takeDocFront"
          />
          <div class="text-text text-center font12">{{ t('provider.login.steps.step_4.document_hint') }}</div>
        </template>
        <template v-else>
          <div class="row items-center q-gutter-x-xs">
            <q-icon name="check_circle" color="positive" size="18px" />
            <span class="text-primary">{{ t('provider.login.steps.step_4.document_sent') }}</span>
          </div>
        </template>
      </div>

    </div>

    <Teleport to="body">
      <div v-if="showResult" class="fs-overlay">
        <div class="fs-result">
          <q-img :src="LogoDiaria" class="q-mb-xl" style="max-width: 150px" />

          <div
            class="result-circle"
            :class="resultError ? 'result-circle--error' : 'result-circle--done'"
          >
            <q-icon
              :name="resultIcon"
              size="56px"
              color="white"
            />
          </div>

          <template v-if="resultError">
            <q-icon name="cancel" color="negative" size="28px" class="q-mt-md" />
            <div class="text-primary text-center q-mt-xs q-px-lg font14">
              {{ t('provider.login.steps.step_4.error_message') }}
            </div>
          </template>
          <div v-else class="text-primary text-center q-mt-md q-px-lg font14">
            {{ resultMessage }}
          </div>

          <q-btn
            color="primary-button"
            :label="resultError ? t('provider.login.steps.step_4.btn_retry') : t('provider.login.steps.step_4.btn_continue')"
            rounded
            no-caps
            padding="14px 48px"
            class="q-mt-xl"
            style="min-width: 200px"
            @click="closeResult"
          />

          <div v-if="!resultError && showDocHint" class="text-grey-6 text-center q-mt-sm font12">
            {{ t('provider.login.steps.step_4.document_hint_result') }}
          </div>
        </div>
      </div>
    </Teleport>

  </q-card-section>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Camera, CameraResultType, CameraSource, CameraDirection } from '@capacitor/camera';
import LogoDiaria from 'src/assets/logo_diaria_campos_login.svg';

const { t } = useI18n();

const form = defineModel({ type: Object, required: true });
const emit = defineEmits(['update:show-sub-step']);

const loadingSelfie = ref(false);
const loadingDoc = ref(false);

const showResult = ref(false);
const resultError = ref(false);
const resultIcon = ref('photo_camera');
const resultMessage = ref('');
const showDocHint = ref(false);

// foto de documento frente — aguarda verso antes de fechar
const tempDocFrontFile = ref(null);

const selfieDone = computed(() => !!form.value.selfie);
const docDone = computed(() => !!form.value.document_front && !!form.value.document_back);

const base64ToFile = (base64, filename, mimeType = 'image/jpeg') => {
  const byteString = atob(base64);
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new File([ab], filename, { type: mimeType });
};

const openCamera = async (direction) => {
  const photo = await Camera.getPhoto({
    resultType: CameraResultType.Base64,
    source: CameraSource.Camera,
    quality: 85,
    direction: direction === 'front' ? CameraDirection.Front : CameraDirection.Rear,
    allowEditing: false,
    saveToGallery: false,
  });
  return base64ToFile(photo.base64String.replace(/\s/g, ''), 'photo.jpg', `image/${photo.format}`);
};

const takeSelfie = async () => {
  if (loadingSelfie.value) return;
  loadingSelfie.value = true;
  try {
    const file = await openCamera('front');
    form.value.selfie = file;
    resultIcon.value = 'photo_camera';
    resultMessage.value = t('provider.login.steps.step_4.selfie_success');
    resultError.value = false;
    showDocHint.value = false;
    showResult.value = true;
    emit('update:show-sub-step', true);
  } catch (err) {
    const msg = (err?.message || '').toLowerCase();
    if (!msg.includes('cancel') && !msg.includes('dismiss') && !msg.includes('no image')) {
      resultIcon.value = 'photo_camera';
      resultError.value = true;
      showDocHint.value = false;
      showResult.value = true;
      emit('update:show-sub-step', true);
    }
  } finally {
    loadingSelfie.value = false;
  }
};

const takeDocFront = async () => {
  if (loadingDoc.value) return;
  loadingDoc.value = true;
  try {
    const file = await openCamera('rear');
    tempDocFrontFile.value = file;
    await takeDocBack();
  } catch (err) {
    const msg = (err?.message || '').toLowerCase();
    if (!msg.includes('cancel') && !msg.includes('dismiss') && !msg.includes('no image')) {
      resultIcon.value = 'mdi-card-account-details-outline';
      resultError.value = true;
      showDocHint.value = false;
      showResult.value = true;
      emit('update:show-sub-step', true);
    }
  } finally {
    loadingDoc.value = false;
  }
};

const takeDocBack = async () => {
  try {
    const file = await openCamera('rear');
    form.value.document_front = tempDocFrontFile.value;
    form.value.document_back = file;
    tempDocFrontFile.value = null;
    resultIcon.value = 'mdi-card-account-details-outline';
    resultMessage.value = t('provider.login.steps.step_4.document_success');
    resultError.value = false;
    showDocHint.value = true;
    showResult.value = true;
    emit('update:show-sub-step', true);
  } catch (err) {
    const msg = (err?.message || '').toLowerCase();
    if (!msg.includes('cancel') && !msg.includes('dismiss') && !msg.includes('no image')) {
      resultIcon.value = 'mdi-card-account-details-outline';
      resultError.value = true;
      showDocHint.value = false;
      showResult.value = true;
      emit('update:show-sub-step', true);
    }
    tempDocFrontFile.value = null;
  }
};

const closeResult = () => {
  showResult.value = false;
  emit('update:show-sub-step', false);
  if (resultError.value) {
    resultError.value = false;
  }
};
</script>

<style lang="scss" scoped>
.photo-circle {
  width: 130px;
  height: 130px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.15s ease;

  &:active { transform: scale(0.95); }

  &--pending {
    background-color: rgba(139, 92, 246, 0.18);
  }

  &--done {
    background: linear-gradient(-90deg, #ec48d1 5%, #6b11cb 65%, #2574fc 100%);
  }
}

.fs-overlay {
  position: fixed;
  inset: 0;
  z-index: 9999;
  background: white;
}

.fs-result {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 28px;
  background: white;
}

.result-circle {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  &--done {
    background: linear-gradient(-90deg, #ec48d1 5%, #6b11cb 65%, #2574fc 100%);
  }

  &--error {
    background-color: rgba(139, 92, 246, 0.18);
  }
}
</style>
