<template>
  <q-dialog ref="dialogRef" persistent maximized transition-show="slide-left" transition-hide="slide-right">
    <q-card class="bg-white full-width full-height">
      <div class="row items-center q-px-md q-pb-sm bg-white shadow-profile dialog-safe-header">
        <q-btn flat round dense icon="mdi-chevron-left" color="primary" @click="onDialogCancel" />
        <q-space />
        <span class="font16 fontbold gradient-diarista">{{ $t('profile.edit_data') }}</span>
        <q-space />
        <div style="width: 32px"></div>
      </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-mt-xl q-mb-md">
            <q-avatar size="140px" class="shadow-1" :style="!profilePhoto ? avatarStyle : undefined">
              <img v-if="profilePhoto" :src="profilePhoto" style="object-fit:cover;width:100%;height:100%;border-radius:50%" />
              <span v-else style="color: #7a154f">{{ form.name ? form.name.slice(0, 2).toUpperCase() : '' }}</span>
            </q-avatar>
            <q-btn flat no-caps color="grey-6" class="q-mt-sm font12 fontregular" :label="$t('profile.change_photo')" />
          </div>

          <div class="q-px-xl q-gutter-y-lg">
            <div>
              <div class="text-grey-8 q-mb-sm font12 fontbold">{{ $t('profile.full_name') }}</div>
              <q-input
                v-model="form.name"
                outlined
                dense
                input-class="text-text"
                :placeholder="$t('profile.placeholder_name')"
              />
            </div>

            <div>
              <div class="text-grey-8 q-mb-sm font12 fontbold">{{ $t('profile.email') }}</div>
              <q-input
                v-model="form.email"
                outlined
                dense
                input-class="text-text"
                :placeholder="$t('profile.placeholder_email')"
              />
            </div>

            <div>
              <div class="text-grey-8 q-mb-sm font12 fontbold">{{ $t('profile.phone') }}</div>
              <q-input
                v-model="form.phone"
                outlined
                dense
                input-class="text-text"
                mask="(##) #####-####"
                unmasked-value
                :placeholder="$t('profile.placeholder_phone')"
              />
            </div>
          </div>

          <q-space/>

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

<script setup>
import { ref, onMounted } from 'vue';
import { useDialogPluginComponent } from 'quasar';
import { updateUser } from 'src/api/user';
import { useFormUpdateTracker } from 'src/composables/useFormUpdateTracker';

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

const profilePhoto = ref(null);

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

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

const { dialogRef, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const loading = ref(false);
const submitting = ref(false);
const userId = ref(null);

const { form, hasUpdatedFields, setUpdateFormAsOriginal } = useFormUpdateTracker({
  name: '',
  email: '',
  phone: ''
});

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

  submitting.value = true;
  try {
    const data = await updateUser({
      name: form.name,
      email: form.email,
      phone: form.phone
    }, userId.value);
    console.log(data)
    setUpdateFormAsOriginal(data);
    onDialogOK(data);
  } catch (error) {
    console.error('Erro ao atualizar perfil:', error);
  } finally {
    submitting.value = false;
  }
};

onMounted(async () => {
  if (props.userData) {
    const data = props.userData;
    userId.value = data.id;
    form.name = data.name || '';
    form.email = data.email || '';
    form.phone = data.phone || '';
    profilePhoto.value = data.profile_photo || null;
    setUpdateFormAsOriginal(data);
    return;
  }

  loading.value = true;
});
</script>

<style scoped lang="scss">


:deep(.q-field--outlined .q-field__control) {
  border-radius: 8px;
  &::before { border: 1px solid #e0e0e0; }
}
</style>
