<template>
  <main class="container page-padding">
    <VHeading level="1" text="Account Settings" class="mb-3" />

    <div v-if="loading" class="text-center">
      <VSpinner label="Loading profile..." />
    </div>

    <VAlert v-else-if="error" type="error" :message="error" class="mb-3">
      <template #actions>
        <VButton variant="danger" size="sm" @click="fetchProfile">Retry</VButton>
      </template>
    </VAlert>

    <form v-else @submit.prevent="onSubmitProfile">
      <!-- Profile Section -->
      <VCard class="mb-3">
        <template #header><VHeading level="3">Profile Information</VHeading></template>
        <div class="flex flex-wrap" style="gap: 1rem;">
          <VFormField label="Name" class="flex-grow">
            <VInput id="profileName" v-model="profile.name" required />
          </VFormField>
          <VFormField label="Email" 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" /> Save Changes
          </VButton>
        </template>
      </VCard>
    </form>

    <!-- Password Section -->
    <form @submit.prevent="onChangePassword">
      <VCard class="mb-3">
        <template #header><VHeading level="3">Change Password</VHeading></template>
        <div class="flex flex-wrap" style="gap: 1rem;">
          <VFormField label="Current Password" class="flex-grow">
            <VInput type="password" id="currentPassword" v-model="password.current" required />
          </VFormField>
          <VFormField label="New Password" 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" /> Change Password
          </VButton>
        </template>
      </VCard>
    </form>

    <!-- Notifications Section -->
    <VCard>
      <template #header><VHeading level="3">Notification Preferences</VHeading></template>
      <VList class="preference-list">
        <VListItem class="preference-item">
          <div class="preference-label">
            <span>Email Notifications</span>
            <small>Receive email notifications for important updates</small>
          </div>
          <VToggleSwitch v-model="preferences.emailNotifications" @change="onPreferenceChange" label="Email Notifications" id="emailNotificationsToggle" />
        </VListItem>
        <VListItem class="preference-item">
          <div class="preference-label">
            <span>List Updates</span>
            <small>Get notified when lists are updated</small>
          </div>
          <VToggleSwitch v-model="preferences.listUpdates" @change="onPreferenceChange" label="List Updates" id="listUpdatesToggle"/>
        </VListItem>
        <VListItem class="preference-item">
          <div class="preference-label">
            <span>Group Activities</span>
            <small>Receive notifications for group activities</small>
          </div>
          <VToggleSwitch v-model="preferences.groupActivities" @change="onPreferenceChange" label="Group Activities" id="groupActivitiesToggle"/>
        </VListItem>
      </VList>
    </VCard>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
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';

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 message = err instanceof Error ? err.message : 'Failed to load profile';
    error.value = message;
    console.error('Failed to fetch profile:', err);
    notificationStore.addNotification({ message, 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: 'Profile updated successfully', type: 'success' });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Failed to update profile';
    console.error('Failed to update profile:', err);
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    saving.value = false;
  }
};

const onChangePassword = async () => {
  if (!password.value.current || !password.value.newPassword) {
    notificationStore.addNotification({ message: 'Please fill in both current and new password fields.', type: 'warning' });
    return;
  }
  if (password.value.newPassword.length < 8) {
    notificationStore.addNotification({ message: 'New password must be at least 8 characters long.', 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: 'Password changed successfully', type: 'success' });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Failed to change password';
    console.error('Failed to change password:', err);
    notificationStore.addNotification({ message, 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: 'Preferences updated successfully', type: 'success' });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Failed to update preferences';
    console.error('Failed to update preferences:', err);
    notificationStore.addNotification({ message, 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>