<template>
  <div class="profile-page">
    <DefaultHeaderPage class="q-px-md" />

    <q-card flat class="profile-card q-mt-sm q-ma-md">

        <div class="profile-header row items-center q-pa-lg">
          <div class="profile-avatar-wrap q-mr-md">
            <q-avatar size="76px" class="profile-avatar">
              <img v-if="user?.photo_url" :src="user.photo_url" />
              <q-icon v-else name="mdi-account" size="44px" color="white" />
            </q-avatar>
            <q-btn
              round
              unelevated
              size="xs"
              icon="mdi-pencil-outline"
              class="profile-avatar-edit"
              color="white"
              text-color="violet-normal"
              :loading="uploadingAvatar"
              @click="triggerAvatarUpload"
            />
            <input
              ref="avatarInputRef"
              type="file"
              accept="image/*"
              style="display: none"
              @change="onAvatarSelected"
            />
          </div>
          <div class="column q-gutter-xs">
            <span class="text-white text-h6 text-weight-bold">{{ user?.name || '—' }}</span>
            <div class="row items-center q-gutter-xs">
              <q-badge
                :color="statusBadgeColor"
                class="text-capitalize"
                style="font-size:11px; padding: 3px 8px; border-radius: 20px;"
              >
                {{ statusLabel }}
              </q-badge>
              <q-btn
                v-if="user?.photo_url"
                flat
                round
                dense
                size="xs"
                icon="mdi-image-remove"
                color="white"
                :loading="removingAvatar"
                @click="onRemoveAvatar"
              />
            </div>
            <span class="text-white profile-validity text-caption">
              {{ $t('associado.validity') }} {{ user?.expiry_date || '—' }}
            </span>
          </div>
        </div>

        <div class="q-pa-md column">
          <div
            v-for="field in infoFields"
            :key="field.label"
            class="info-row row items-center no-wrap q-my-sm q-px-md"
          >
            <q-icon :name="field.icon" size="22px" class="info-icon q-mr-md" />
            <div class="column">
              <span class="info-label">{{ field.label }}</span>
              <span class="info-value">{{ field.value || '—' }}</span>
            </div>
          </div>
        </div>

    </q-card>

    <!-- Dependentes — fora do card branco, sobre fundo violet-light -->
    <div class="dependents-section q-ma-md">
      <div class="row items-center justify-between q-mb-sm">
        <span class="text-h6 text-weight-bold text-violet-normal">
          {{ $t('associado.dependents') }}
        </span>
        <q-btn
          unelevated
          size="md"
          icon="mdi-plus"
          color="violet-normal"
          text-color="white"
          @click="onAddDependent"
        />
      </div>

      <div v-if="dependents.length > 0" class="column" style="gap: 8px;">
        <div
          v-for="dep in dependents"
          :key="dep.id"
          class="dependent-card row items-center no-wrap"
        >
          <q-avatar size="40px" class="dependent-avatar q-mr-md" text-color="white">
            {{ initials(dep.name) }}
          </q-avatar>

          <div class="col column">
            <span class="dependent-name">{{ dep.name }}</span>
            <span class="dependent-kinship">
              {{ $t(`associado.kinship_options.${dep.kinship}`) }}
            </span>
          </div>

          <q-chip
            :color="dependentStatusColor(dep.status)"
            outline
            dense
            class="text-capitalize dependent-status-chip"
          >
            {{ dependentStatusLabel(dep.status) }}
          </q-chip>
        </div>
      </div>

      <div v-else class="text-center q-py-md text-grey">
        {{ $t('associado.no_dependents') }}
      </div>
    </div>

    <!-- Seção legal -->
    <div class="legal-section q-ma-md q-pb-lg">
      <q-btn
        flat
        no-caps
        class="full-width legal-btn"
        icon="mdi-shield-account-outline"
        :label="$t('common.terms.privacy_policy')"
        @click="openUrl(PRIVACY_POLICY_URL)"
      />
      <q-separator class="q-my-xs" color="grey-3" />
      <q-btn
        flat
        no-caps
        class="full-width legal-btn text-negative"
        icon="mdi-delete-outline"
        :label="$t('common.terms.delete_account')"
        @click="openUrl(PRIVACY_POLICY_URL)"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineAsyncComponent, useTemplateRef } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { userStore } from "src/stores/user";
import { getDependentsByUser } from "src/api/profile";
import { uploadMyAvatar, deleteMyAvatar } from "src/api/user";
import { useMediaFile } from "src/composables/useMediaFile";
import { PRIVACY_POLICY_URL, openUrl } from "src/helpers/links";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";

const AddEditDependentDialog = defineAsyncComponent(
  () => import("src/pages/associado/profile/components/AddEditDependentDialog.vue"),
);

const $q = useQuasar();
const { t } = useI18n();
const store = userStore();
const { prepareFile } = useMediaFile();

const user = ref(null);
const dependents = ref([]);
const uploadingAvatar = ref(false);
const removingAvatar = ref(false);
const avatarInputRef = useTemplateRef("avatarInputRef");

const statusBadgeColor = computed(() => {
  switch (user.value?.status) {
    case "active":   return "positive";
    case "inactive": return "grey";
    case "canceled": return "negative";
    default:         return "grey";
  }
});

const statusLabel = computed(() => {
  const map = { active: t("common.status.active"), inactive: t("common.status.inactive"), canceled: t("common.status.canceled") };
  return map[user.value?.status] ?? user.value?.status ?? "—";
});

const infoFields = computed(() => [
  { icon: "mdi-card-account-details-outline", label: t("common.terms.cpf"),          value: user.value?.cpf },
  { icon: "mdi-email-outline",                label: "E-mail",                        value: user.value?.email },
  { icon: "mdi-briefcase-outline",            label: t("associado.position"),         value: user.value?.position?.name },
  { icon: "mdi-domain",                       label: t("associado.sector"),           value: user.value?.sector?.name },
  { icon: "mdi-card-text-outline",            label: t("associado.registration"),     value: user.value?.registration },
  { icon: "mdi-calendar-outline",             label: t("associado.admission_date"),   value: user.value?.admission_date },
]);

const initials = (name) => {
  if (!name) return "?";
  return name.split(" ").slice(0, 2).map((w) => w[0]).join("").toUpperCase();
};

const dependentStatusColor = (status) => {
  switch (status) {
    case "approved": return "positive";
    case "refused":  return "negative";
    case "pending":  return "warning-light";
    default:         return "grey";
  }
};

const dependentStatusLabel = (status) => {
  const map = {
    approved: t("associado.dependent_statuses.approved"),
    refused:  t("associado.dependent_statuses.refused"),
    pending:  t("associado.dependent_statuses.pending"),
  };
  return map[status] ?? status ?? "—";
};

const loadUser = async () => {
  await store.fetchUser();
  user.value = store.user;
};

const loadDependents = async () => {
  if (!user.value?.id) return;
  try {
    dependents.value = await getDependentsByUser(user.value.id);
  } catch {
    dependents.value = [];
  }
};

onMounted(async () => {
  await loadUser();
  await loadDependents();
});

const triggerAvatarUpload = () => {
  avatarInputRef.value?.click();
};

const onAvatarSelected = async (event) => {
  const selected = event.target.files?.[0];
  event.target.value = "";
  if (!selected) return;

  const { file } = await prepareFile(selected);
  if (!file) return;

  uploadingAvatar.value = true;
  try {
    const updated = await uploadMyAvatar(file);
    store.user = updated;
    user.value = updated;
    $q.notify({ type: "positive", message: t("http.success") });
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  } finally {
    uploadingAvatar.value = false;
  }
};

const onRemoveAvatar = () => {
  $q.dialog({
    title: t("common.ui.messages.confirm_action"),
    message: t("associado.remove_photo"),
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    removingAvatar.value = true;
    try {
      const updated = await deleteMyAvatar();
      store.user = updated;
      user.value = updated;
      $q.notify({ type: "positive", message: t("http.success") });
    } catch {
      $q.notify({ type: "negative", message: t("http.errors.failed") });
    } finally {
      removingAvatar.value = false;
    }
  });
};

const onAddDependent = () => {
  $q.dialog({
    component: AddEditDependentDialog,
    componentProps: {
      userId: user.value.id,
      title: () => t("common.actions.add") + " " + t("associado.dependent"),
    },
  }).onOk(() => loadDependents());
};
</script>

<style lang="scss" scoped>
@use "src/css/quasar.variables.scss" as *;

.profile-page {
  background: $violet-light;
  min-height: 100%;
}

.profile-card {
  background: white !important;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.profile-header {
  background: linear-gradient(135deg, $violet-normal 0%, $violet-dark 100%);
}

.profile-avatar-wrap {
  position: relative;
  flex-shrink: 0;
}

.profile-avatar {
  background: rgba(255, 255, 255, 0.18) !important;
  border: 2px solid rgba(255, 255, 255, 0.45);

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.profile-avatar-edit {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 22px;
  height: 22px;
  min-height: 22px;
}

.profile-validity {
  opacity: 0.85;
}

.info-row {
  background: $violet-light;
  border-radius: 8px;
  padding: 12px 16px;
}

.info-icon {
  color: $violet-normal;
  flex-shrink: 0;
}

.info-label {
  font-size: 11px;
  color: $color-text-2;
  line-height: 1.2;
}

.info-value {
  font-size: 14px;
  color: $color-text;
  font-weight: 500;
  line-height: 1.4;
}

.dependents-section {
  padding-bottom: 16px;
}

.dependent-card {
  background: white;
  border-radius: 10px;
  padding: 10px 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.07);
}

.dependent-avatar {
  background: $violet-normal !important;
  font-size: 14px;
  font-weight: 700;
  flex-shrink: 0;
}

.dependent-name {
  font-size: 14px;
  font-weight: 600;
  color: $color-text;
  line-height: 1.3;
}

.dependent-kinship {
  font-size: 12px;
  color: $color-text-2;
  line-height: 1.2;
}

.dependent-status-chip {
  font-size: 11px !important;
  font-weight: 600;
  flex-shrink: 0;
}

.legal-section {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.07);
}

.legal-btn {
  justify-content: flex-start;
  padding: 12px 16px;
  font-size: 13px;
  font-weight: 500;
  color: $color-text;
  border-radius: 0;
}
</style>
