<script setup>
import { onMounted, reactive, ref } from "vue";
import { Delete, Refresh } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { apiRequest } from "@/lib/api";
import { useAuthStore } from "@/stores/auth";
import { useLanguageStore } from "@/stores/language";

const auth = useAuthStore();
const languageStore = useLanguageStore();
const router = useRouter();
const { t } = useI18n();
const health = ref(null);
const healthLoading = ref(false);
const deleteDialogOpen = ref(false);
const deleteForm = reactive({ password: "" });

async function loadHealth() {
  healthLoading.value = true;
  try {
    health.value = await apiRequest("/health", { auth: false });
  } catch (error) {
    health.value = null;
    ElMessage.error(error.message || t("common.requestFailed"));
  } finally {
    healthLoading.value = false;
  }
}

async function deleteAccount() {
  try {
    await ElMessageBox.confirm(
      t("settings.deleteConfirm"),
      t("settings.deleteAccount"),
      {
        type: "error",
        confirmButtonText: t("settings.confirmDelete"),
      },
    );
    await apiRequest("/auth/delete", {
      method: "POST",
      body: {
        user_id: auth.session?.id || "",
        password: deleteForm.password,
      },
    });
    deleteDialogOpen.value = false;
    await auth.logout();
    await router.push("/");
    ElMessage.success(t("settings.deleted"));
  } catch (error) {
    if (error !== "cancel" && error !== "close") {
      ElMessage.error(error.message || t("settings.deleteFailed"));
    }
  }
}

onMounted(loadHealth);
</script>

<template>
  <main class="settings-shell">
    <header class="settings-heading">
      <p class="section-kicker">{{ t("settings.kicker") }}</p>
      <h1>{{ t("settings.title") }}</h1>
    </header>

    <section class="settings-section">
      <div>
        <h2>{{ t("settings.language") }}</h2>
        <p>{{ t("settings.languageHint") }}</p>
      </div>
      <div class="segmented-control compact" role="group">
        <button
          type="button"
          :class="{ active: languageStore.locale === 'zh' }"
          @click="languageStore.setLocale('zh')"
        >
          中文
        </button>
        <button
          type="button"
          :class="{ active: languageStore.locale === 'en' }"
          @click="languageStore.setLocale('en')"
        >
          English
        </button>
      </div>
    </section>

    <section class="settings-section">
      <div>
        <h2>{{ t("settings.serviceStatus") }}</h2>
        <p>{{ t("settings.serviceHint") }}</p>
      </div>
      <div class="capability-list">
        <span :class="{ online: health?.capabilities?.database }">
          {{ t("settings.database") }}
        </span>
        <span :class="{ online: health?.capabilities?.redis }"> Redis </span>
        <span :class="{ online: health?.capabilities?.email }">
          {{ t("settings.outboundEmail") }}
        </span>
        <button
          class="icon-command"
          type="button"
          :title="t('common.refresh')"
          :aria-label="t('common.refresh')"
          :disabled="healthLoading"
          @click="loadHealth"
        >
          <el-icon><Refresh /></el-icon>
        </button>
      </div>
    </section>

    <section v-if="auth.isAuthenticated" class="settings-section danger-zone">
      <div>
        <h2>{{ t("settings.deleteAccount") }}</h2>
        <p>{{ t("settings.deleteHint") }}</p>
      </div>
      <button
        class="danger-command"
        type="button"
        @click="deleteDialogOpen = true"
      >
        <el-icon><Delete /></el-icon>
        {{ t("settings.deleteAccount") }}
      </button>
    </section>

    <el-dialog
      v-model="deleteDialogOpen"
      :title="t('settings.deleteAccount')"
      width="min(92vw, 440px)"
    >
      <form class="dialog-form" @submit.prevent="deleteAccount">
        <label>
          <span>{{ t("auth.password") }}</span>
          <input
            v-model="deleteForm.password"
            type="password"
            autocomplete="current-password"
            required
          />
        </label>
        <button class="danger-command" type="submit">
          <el-icon><Delete /></el-icon>
          {{ t("settings.confirmDelete") }}
        </button>
      </form>
    </el-dialog>
  </main>
</template>
