<template>
  <main class="container page-padding">
    <VHeading level="1" :text="$t('accountPage.title')" class="mb-3" />

    <div v-if="loading" class="text-center">
      <VSpinner :label="$t('accountPage.loadingProfile')" />
    </div>

    <VAlert v-else-if="error" type="error" :message="error" class="mb-3">
      <template #actions>
        <VButton variant="danger" size="sm" @click="fetchProfile">{{ $t('accountPage.retryButton') }}</VButton>
      </template>
    </VAlert>

    <form v-else @submit.prevent="onSubmitProfile">
      <!-- Profile Section -->
      <VCard class="mb-3">
        <template #header><VHeading level="3">{{ $t('accountPage.profileSection.header') }}</VHeading></template>
        <div class="flex flex-wrap" style="gap: 1rem;">
          <VFormField :label="$t('accountPage.profileSection.nameLabel')" class="flex-grow">
            <VInput id="profileName" v-model="profile.name" required />
          </VFormField>
          <VFormField :label="$t('accountPage.profileSection.emailLabel')" class="flex-grow">
            <VInput type="email" id="profileEmail" v-model="profile.email" required readonly />
          </VFormField>
        </div>
        <template #footer>
          <VButton type="submit" variant="primary" :disabled="saving">
            <VSpinner v-if="saving" size="sm" /> {{ $t('accountPage.profileSection.saveButton') }}
          </VButton>
        </template>
      </VCard>
    </form>

    <!-- Password Section -->
    <form @submit.prevent="onChangePassword">
      <VCard class="mb-3">
        <template #header><VHeading level="3">{{ $t('accountPage.passwordSection.header') }}</VHeading></template>
        <div class="flex flex-wrap" style="gap: 1rem;">
          <VFormField :label="$t('accountPage.passwordSection.currentPasswordLabel')" class="flex-grow">
            <VInput type="password" id="currentPassword" v-model="password.current" required />
          </VFormField>
          <VFormField :label="$t('accountPage.passwordSection.newPasswordLabel')" class="flex-grow">
            <VInput type="password" id="newPassword" v-model="password.newPassword" required />
          </VFormField>
        </div>
        <template #footer>
          <VButton type="submit" variant="primary" :disabled="changingPassword">
            <VSpinner v-if="changingPassword" size="sm" /> {{ $t('accountPage.passwordSection.changeButton') }}
          </VButton>
        </template>
      </VCard>
    </form>

    <!-- Notifications Section -->
    <VCard>
      <template #header><VHeading level="3">{{ $t('accountPage.notificationsSection.header') }}</VHeading></template>
      <VList class="preference-list">
        <VListItem class="preference-item">
          <div class="preference-label">
            <span>{{ $t('accountPage.notificationsSection.emailNotificationsLabel') }}</span>
            <small>{{ $t('accountPage.notificationsSection.emailNotificationsDescription') }}</small>
          </div>
          <VToggleSwitch v-model="preferences.emailNotifications" @change="onPreferenceChange" :label="$t('accountPage.notificationsSection.emailNotificationsLabel')" id="emailNotificationsToggle" />
        </VListItem>
        <VListItem class="preference-item">
          <div class="preference-label">
            <span>{{ $t('accountPage.notificationsSection.listUpdatesLabel') }}</span>
            <small>{{ $t('accountPage.notificationsSection.listUpdatesDescription') }}</small>
          </div>
          <VToggleSwitch v-model="preferences.listUpdates" @change="onPreferenceChange" :label="$t('accountPage.notificationsSection.listUpdatesLabel')" id="listUpdatesToggle"/>
        </VListItem>
        <VListItem class="preference-item">
          <div class="preference-label">
            <span>{{ $t('accountPage.notificationsSection.groupActivitiesLabel') }}</span>
            <small>{{ $t('accountPage.notificationsSection.groupActivitiesDescription') }}</small>
          </div>
          <VToggleSwitch v-model="preferences.groupActivities" @change="onPreferenceChange" :label="$t('accountPage.notificationsSection.groupActivitiesLabel')" id="groupActivitiesToggle"/>
        </VListItem>
      </VList>
    </VCard>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { apiClient, API_ENDPOINTS } from '@/config/api'; // Assuming path
import { useNotificationStore } from '@/stores/notifications';
import VHeading from '@/components/valerie/VHeading.vue';
import VSpinner from '@/components/valerie/VSpinner.vue';
import VAlert from '@/components/valerie/VAlert.vue';
import VCard from '@/components/valerie/VCard.vue';
import VFormField from '@/components/valerie/VFormField.vue';
import VInput from '@/components/valerie/VInput.vue';
import VButton from '@/components/valerie/VButton.vue';
import VToggleSwitch from '@/components/valerie/VToggleSwitch.vue';
import VList from '@/components/valerie/VList.vue';
import VListItem from '@/components/valerie/VListItem.vue';

const { t } = useI18n();

interface Profile {
  name: string;
  email: string;
}

interface PasswordForm {
  current: string;
  newPassword: string; // Renamed from 'new' to avoid conflict
}

interface Preferences {
  emailNotifications: boolean;
  listUpdates: boolean;
  groupActivities: boolean;
}

const loading = ref(true);
const saving = ref(false);
const changingPassword = ref(false);
const error = ref<string | null>(null);

const notificationStore = useNotificationStore();
const profile = ref<Profile>({ name: '', email: '' });
const password = ref<PasswordForm>({ current: '', newPassword: '' });
const preferences = ref<Preferences>({
  emailNotifications: true,
  listUpdates: true,
  groupActivities: true,
});

const fetchProfile = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await apiClient.get(API_ENDPOINTS.USERS.PROFILE);
    profile.value = response.data;
    // Assume preferences are also fetched or part of profile
    // preferences.value = response.data.preferences || preferences.value;
  } catch (err: unknown) {
    const apiMessage = err instanceof Error ? err.message : t('accountPage.notifications.profileLoadFailed');
    error.value = apiMessage; // Show translated or API error message in the VAlert
    console.error('Failed to fetch profile:', err);
    // For the notification pop-up, always use the translated generic message
    notificationStore.addNotification({ message: t('accountPage.notifications.profileLoadFailed'), type: 'error' });
  } finally {
    loading.value = false;
  }
};

const onSubmitProfile = async () => {
  saving.value = true;
  try {
    await apiClient.put(API_ENDPOINTS.USERS.UPDATE_PROFILE, profile.value);
    notificationStore.addNotification({ message: t('accountPage.notifications.profileUpdateSuccess'), type: 'success' });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : t('accountPage.notifications.profileUpdateFailed');
    console.error('Failed to update profile:', err);
    notificationStore.addNotification({ message: t('accountPage.notifications.profileUpdateFailed'), type: 'error' });
  } finally {
    saving.value = false;
  }
};

const onChangePassword = async () => {
  if (!password.value.current || !password.value.newPassword) {
    notificationStore.addNotification({ message: t('accountPage.notifications.passwordFieldsRequired'), type: 'warning' });
    return;
  }
  if (password.value.newPassword.length < 8) {
    notificationStore.addNotification({ message: t('accountPage.notifications.passwordTooShort'), type: 'warning' });
    return;
  }

  changingPassword.value = true;
  try {
    // API endpoint expects 'new' not 'newPassword'
    await apiClient.put(API_ENDPOINTS.USERS.PASSWORD, {
      current: password.value.current,
      new: password.value.newPassword
    });
    password.value = { current: '', newPassword: '' };
    notificationStore.addNotification({ message: t('accountPage.notifications.passwordChangeSuccess'), type: 'success' });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : t('accountPage.notifications.passwordChangeFailed');
    console.error('Failed to change password:', err);
    notificationStore.addNotification({ message: t('accountPage.notifications.passwordChangeFailed'), type: 'error' });
  } finally {
    changingPassword.value = false;
  }
};

const onPreferenceChange = async () => {
  // This will be called for each toggle change.
  // Consider debouncing or providing a "Save Preferences" button if API calls are expensive.
  try {
    await apiClient.put(API_ENDPOINTS.USERS.PREFERENCES, preferences.value);
    notificationStore.addNotification({ message: t('accountPage.notifications.preferencesUpdateSuccess'), type: 'success' });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : t('accountPage.notifications.preferencesUpdateFailed');
    console.error('Failed to update preferences:', err);
    notificationStore.addNotification({ message: t('accountPage.notifications.preferencesUpdateFailed'), type: 'error' });
    // Optionally revert the toggle if the API call fails
    // await fetchProfile(); // Or manage state more granularly
  }
};

onMounted(() => {
  fetchProfile();
});
</script>

<style scoped>
.page-padding {
  padding: 1rem;
  /* Or use var(--padding-page) if defined in Valerie UI */
}

.mb-3 {
  margin-bottom: 1.5rem;
}

/* From Valerie UI */
.flex-grow {
  flex-grow: 1;
}

.preference-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.preference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #eee;
  /* Softer border for list items */
}

.preference-item:last-child {
  border-bottom: none;
}

.preference-label {
  display: flex;
  flex-direction: column;
  margin-right: 1rem;
}

.preference-label small {
  font-size: 0.85rem;
  opacity: 0.7;
  margin-top: 0.2rem;
}
</style>