<template>
  <AppLayout>
    <div class="max-w-4xl mx-auto">
      <div class="card">
        <div class="flex items-center space-x-4 mb-6">
          <div class="relative">
            <div class="w-20 h-20 bg-gradient-to-br from-primary-500 to-primary-700 rounded-full flex items-center justify-center text-white text-2xl font-bold">
              {{ userInitials }}
            </div>
            <button class="absolute bottom-0 right-0 p-1 bg-white rounded-full shadow-md hover:shadow-lg transition-shadow">
              <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
            </button>
          </div>
          <div>
            <h1 class="text-2xl font-bold text-gray-900">My Profile</h1>
            <p class="text-gray-500">Manage your account settings</p>
          </div>
        </div>

        <form @submit.prevent="saveProfile" class="space-y-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Username</label>
              <input v-model="userStore.login" type="text" disabled class="input-field bg-gray-100" />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Role</label>
              <div class="relative">
                <input :value="userStore.role === 'admin' ? 'Administrator' : 'User'" type="text" disabled class="input-field bg-gray-100" />
                <div class="absolute right-3 top-2.5">
                  <span class="px-2 py-0.5 text-xs rounded-full" :class="userStore.role === 'admin' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-600'">
                    {{ userStore.role === 'admin' ? 'Admin' : 'User' }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
            <input v-model="form.email" type="email" required class="input-field" />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">New Password</label>
            <input v-model="form.password" type="password" class="input-field" autocomplete="new-password" />
            <p class="text-xs text-gray-500 mt-1">Leave blank to keep current password</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Confirm New Password</label>
            <input v-model="form.confirmPassword" type="password" class="input-field" :class="{ 'border-red-300': passwordMismatch }" />
            <p v-if="passwordMismatch" class="text-xs text-red-600 mt-1">Passwords do not match</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Language</label>
            <select v-model="form.language" class="input-field">
              <option value="en">English</option>
              <option value="ru">Русский</option>
            </select>
          </div>

          <div class="pt-4 border-t">
            <div class="flex justify-end space-x-3">
              <button type="button" @click="resetForm" class="btn-secondary">Reset</button>
              <button type="submit" :disabled="loading" class="btn-primary flex items-center gap-2">
                <svg v-if="loading" class="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Save Changes
              </button>
            </div>
          </div>
        </form>

        <!-- Notification Toast -->
        <Transition name="slide">
          <div v-if="notification.show" class="fixed bottom-4 right-4 z-50 flex items-center space-x-2 px-4 py-3 rounded-lg shadow-lg" :class="notification.type === 'success' ? 'bg-green-50 text-green-800 border border-green-200' : 'bg-red-50 text-red-800 border border-red-200'">
            <svg v-if="notification.type === 'success'" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>{{ notification.message }}</span>
          </div>
        </Transition>
      </div>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useUserStore } from '../stores/user';
import { useI18n } from 'vue-i18n';
import AppLayout from '../components/Layout/AppLayout.vue';

const userStore = useUserStore();
const { locale } = useI18n();

const form = reactive({
  email: '',
  password: '',
  confirmPassword: '',
  language: 'en'
});

const loading = ref(false);
const notification = ref({ show: false, type: 'success', message: '' });

const userInitials = computed(() => (userStore.login[0] || 'U').toUpperCase());
const passwordMismatch = computed(() => !!form.password && form.password !== form.confirmPassword);

function showNotification(message: string, type: 'success' | 'error') {
  notification.value = { show: true, type, message };
  setTimeout(() => {
    notification.value.show = false;
  }, 3000);
}

function resetForm() {
  form.email = userStore.email;
  form.password = '';
  form.confirmPassword = '';
  form.language = userStore.language;
}

async function saveProfile() {
  if (form.password && form.password !== form.confirmPassword) {
    showNotification('Passwords do not match', 'error');
    return;
  }

  loading.value = true;
  const updates: any = {
    email: form.email,
    language: form.language
  };
  if (form.password) updates.password = form.password;

  const ok = await userStore.updateProfile(updates);
  loading.value = false;

  if (ok) {
    locale.value = form.language;
    showNotification('Profile updated successfully', 'success');
    resetForm(); // очищаем поля пароля
  } else {
    showNotification('Failed to update profile', 'error');
  }
}

onMounted(() => {
  form.email = userStore.email;
  form.language = userStore.language;
});
</script>

<style scoped>
.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease, opacity 0.3s ease;
}
.slide-enter-from,
.slide-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>
