<template>
  <AppLayout>
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-900">{{ t('users.pageName') }}</h1>
      <button @click="openModal('create')" class="btn-primary flex items-center gap-2">
        <svg 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 4v16m8-8H4" />
        </svg>
        {{ t('users.add') }}
      </button>
    </div>

    <div class="card overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.id') }}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.login') }}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.email') }}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.role') }}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.status') }}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.ip') }}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.created') }}</th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">{{ t('common.actions') }}</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200 bg-white">
            <tr v-for="user in users" :key="user.id" class="hover:bg-gray-50 transition-colors">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ user.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ user.login }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.email }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span class="px-2 py-1 text-xs rounded-full" :class="user.role === 'admin' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-600'">
                  {{ user.role === 'admin' ? t('app.administrator') : t('app.user') }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <div v-if="user.id === userStore.id" class="text-xs text-gray-500">{{ t('users.you') }}</div>
                <label v-else class="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    :checked="user.active"
                    @change="toggleActive(user)"
                    class="sr-only peer"
                  />
                  <div class="w-9 h-5 bg-gray-200 rounded-full peer peer-checked:bg-primary-600 transition-colors"></div>
                  <div class="absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-4"></div>
                </label>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.ip || '-' }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(user.created) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-3">
                <button @click="openModal('edit', user)" class="text-blue-600 hover:text-blue-800 transition-colors">
                  <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </button>
                <button
                  v-if="user.id !== userStore.id"
                  @click="confirmDelete(user.id)"
                  class="text-red-600 hover:text-red-800 transition-colors"
                >
                  <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </button>
              </td>
            </tr>
            <tr v-if="users.length === 0">
              <td colspan="8" class="px-6 py-12 text-center text-gray-500">{{ t('users.noUsers') }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Modal for create/edit user -->
    <Transition name="fade">
      <div v-if="modalOpen" class="fixed inset-0 z-50 overflow-y-auto" @click.self="closeModal">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm"></div>
        <div class="flex items-center justify-center min-h-screen p-4">
          <div class="relative bg-white rounded-2xl shadow-xl max-w-md w-full transform transition-all">
            <div class="flex justify-between items-center p-6 border-b">
              <h2 class="text-xl font-bold text-gray-900">{{ modalTitle }}</h2>
              <button @click="closeModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <form @submit.prevent="submitUser" class="p-6 space-y-5">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">{{ t('common.email') }} *</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">{{ t('common.login') }} *</label>
                <input v-model="form.login" type="text" required class="input-field" />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">{{ t('common.role') }}</label>
                <select v-model="form.role" class="input-field" :disabled="isEditingSelf">
                  <option value="user">{{ t('app.user') }}</option>
                  <option value="admin">{{ t('app.administrator') }}</option>
                </select>
                <p v-if="isEditingSelf" class="text-xs text-amber-600 mt-1">{{ t('users.cannotChangeOwnRole') }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">{{ t('common.password') }}</label>
                <input
                  v-model="form.password"
                  :required="modalMode === 'create'"
                  type="password"
                  class="input-field"
                  autocomplete="new-password"
                />
                <p v-if="modalMode === 'edit'" class="text-xs text-gray-500 mt-1">{{ t('common.leavePasswordBlank') }}</p>
              </div>
              <div class="flex justify-end space-x-3 pt-2">
                <button type="button" @click="closeModal" class="btn-secondary">{{ t('app.cancel') }}</button>
                <button type="submit" class="btn-primary">{{ t('app.save') }}</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </Transition>

    <!-- Delete confirmation modal -->
    <Transition name="fade">
      <div v-if="deleteConfirm.show" class="fixed inset-0 z-50 overflow-y-auto" @click.self="deleteConfirm.show = false">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm"></div>
        <div class="flex items-center justify-center min-h-screen p-4">
          <div class="relative bg-white rounded-2xl shadow-xl max-w-md w-full">
            <div class="p-6 text-center">
              <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 mb-4">
                <svg class="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <h3 class="text-lg font-medium text-gray-900 mb-2">{{ t('users.delete') }}</h3>
              <p class="text-sm text-gray-500 mb-6">{{ t('users.deleteConfirmation') }}</p>
              <div class="flex justify-center space-x-3">
                <button @click="deleteConfirm.show = false" class="btn-secondary">{{ t('app.cancel') }}</button>
                <button @click="deleteUser(deleteConfirm.id)" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors">{{ t('app.delete') }}</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </AppLayout>
</template>

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

const { t } = useI18n();
const { showNotification } = useNotification();
const userStore = useUserStore();

const users = ref<any[]>([]);
const modalOpen = ref(false);
const modalMode = ref<'create' | 'edit'>('create');
const form = ref({ id: null, login: '', email: '', password: '', role: 'user' });
const modalTitle = ref('');
const deleteConfirm = ref({ show: false, id: null });

const isEditingSelf = computed(() => {
  return modalMode.value === 'edit' && form.value.id === userStore.id;
});

async function loadUsers() {
  try {
    const res = await fetch('/api/admin/users');
    if (!res.ok) throw new Error();
    users.value = await res.json();
  } catch (e) {
    showNotification('users.loadError', 'error');
  }
}

function formatDate(dateStr: string) {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString();
}

async function toggleActive(user: any) {
  try {
    const res = await fetch(`/api/admin/users/${user.id}/activate?active=${!user.active}`, { method: 'PUT' });
    if (!res.ok) throw new Error();
    await loadUsers();
    showNotification('users.statusUpdated', 'success');
  } catch (e) {
    showNotification('users.statusUpdateError', 'error');
  }
}

function openModal(mode: 'create' | 'edit', user: any = null) {
  modalMode.value = mode;
  if (mode === 'create') {
    form.value = { id: null, login: '', email: '', password: '', role: 'user' };
    modalTitle.value = t('users.add');
  } else {
    form.value = { id: user.id, login: user.login, email: user.email, password: '', role: user.role || 'user' };
    modalTitle.value = t('users.edit');
  }
  modalOpen.value = true;
}

function closeModal() {
  modalOpen.value = false;
}

async function submitUser() {
  if (isEditingSelf.value && form.value.role !== userStore.role) {
    showNotification('users.cannotChangeOwnRole', 'error');
    return;
  }

  if (modalMode.value === 'create' && !form.value.password) {
    showNotification('users.passwordRequired', 'error');
    return;
  }

  try {
    const payload: any = {
      login: form.value.login,
      email: form.value.email,
      role: form.value.role,
    };
    if (form.value.password) {
      payload.password = form.value.password;
    }

    let response;
    if (modalMode.value === 'create') {
      response = await fetch('/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!response.ok) throw new Error();
      showNotification('users.createSuccess', 'success');
    } else {
      response = await fetch(`/api/admin/users/${form.value.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!response.ok) throw new Error();
      showNotification('users.updateSuccess', 'success');
    }

    await loadUsers();
    closeModal();
  } catch (e) {
    showNotification(modalMode.value === 'create' ? 'users.createError' : 'users.updateError', 'error');
  }
}

function confirmDelete(id: number) {
  deleteConfirm.value = { show: true, id };
}

async function deleteUser(id: number) {
  try {
    const res = await fetch(`/api/admin/users/${id}`, { method: 'DELETE' });
    if (!res.ok) throw new Error();
    showNotification('users.deleteSuccess', 'success');
    await loadUsers();
  } catch (e) {
    showNotification('users.deleteError', 'error');
  } finally {
    deleteConfirm.value.show = false;
  }
}

onMounted(async () => {
  await loadUsers();
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
