<script setup>
import { ref, computed, onMounted } from 'vue'
import * as usersApi from '@/api/users'
import UserFormModal from '@/components/admin/UserFormModal.vue'
import Button from '@/components/ui/Button.vue'
import Badge from '@/components/ui/Badge.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import EmptyState from '@/components/ui/EmptyState.vue'
import {
  emptyUserForm,
  userToForm,
  roleLabel,
  formatLastLogin,
} from '@/composables/userForm'

const users = ref([])
const loading = ref(true)
const error = ref('')
const modalOpen = ref(false)
const modalMode = ref('edit')
const editingUser = ref(null)
const submitting = ref(false)
const submitError = ref('')

const modalTitle = computed(() =>
  modalMode.value === 'create' ? 'Create User' : 'Edit User',
)

const modalInitialValues = computed(() =>
  modalMode.value === 'create'
    ? emptyUserForm()
    : userToForm(editingUser.value ?? {}),
)

async function loadUsers() {
  loading.value = true
  error.value = ''
  try {
    users.value = await usersApi.fetchUsers()
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }
}

function openCreate() {
  modalMode.value = 'create'
  editingUser.value = null
  submitError.value = ''
  modalOpen.value = true
}

function openEdit(user) {
  modalMode.value = 'edit'
  editingUser.value = user
  submitError.value = ''
  modalOpen.value = true
}

function closeModal() {
  modalOpen.value = false
}

async function onSubmit(payload) {
  submitting.value = true
  submitError.value = ''
  try {
    if (modalMode.value === 'create') {
      await usersApi.createUser(payload)
    } else {
      await usersApi.updateUser(editingUser.value.id, payload)
    }
    modalOpen.value = false
    await loadUsers()
  } catch (err) {
    submitError.value = err.message
  } finally {
    submitting.value = false
  }
}

onMounted(loadUsers)
</script>

<template>
  <div>
    <div class="mb-4 flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="text-xl font-bold dark:text-white">User Management</h1>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          Create clinical accounts, assign roles, and deactivate users.
        </p>
      </div>
      <Button size="sm" @click="openCreate">Create User</Button>
    </div>

    <p v-if="error" class="mb-4 text-sm text-red-600 dark:text-red-400">{{ error }}</p>

    <Skeleton v-if="loading" :rows="6" />
    <EmptyState v-else-if="users.length === 0" message="No users found" />

    <div v-else class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
      <table class="min-w-full divide-y divide-gray-200 text-sm dark:divide-gray-700">
        <thead class="bg-gray-50 dark:bg-gray-800">
          <tr class="text-left text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">
            <th class="px-4 py-3">Username</th>
            <th class="px-4 py-3">Display name</th>
            <th class="px-4 py-3">Role</th>
            <th class="px-4 py-3">Last login</th>
            <th class="px-4 py-3">Status</th>
            <th class="px-4 py-3 text-right">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
          <tr v-for="user in users" :key="user.id">
            <td class="px-4 py-3 font-medium text-gray-900 dark:text-white">
              {{ user.username }}
            </td>
            <td class="px-4 py-3 text-gray-700 dark:text-gray-300">{{ user.displayName }}</td>
            <td class="px-4 py-3 text-gray-700 dark:text-gray-300">{{ roleLabel(user.role) }}</td>
            <td class="px-4 py-3 text-gray-700 dark:text-gray-300">
              {{ formatLastLogin(user.lastLoginAt) }}
            </td>
            <td class="px-4 py-3">
              <Badge :variant="user.isActive ? 'success' : 'critical'">
                {{ user.isActive ? 'Active' : 'Inactive' }}
              </Badge>
            </td>
            <td class="px-4 py-3">
              <div class="flex justify-end">
                <Button size="sm" variant="secondary" @click="openEdit(user)">Edit</Button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <UserFormModal
      :open="modalOpen"
      :title="modalTitle"
      :mode="modalMode"
      :initial-values="modalInitialValues"
      :submitting="submitting"
      :error="submitError"
      @close="closeModal"
      @submit="onSubmit"
    />
  </div>
</template>
