<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1>{{ $t('users.title') }}</h1>
        <p>{{ $t('users.manage') }}</p>
      </div>
      <button @click="showCreateModal" class="btn-primary">{{ $t('users.add') }}</button>
    </div>

    <div class="content">
      <!-- Search & Filters -->
      <div class="filters-bar">
        <input
          v-model="searchQuery"
          type="text"
          :placeholder="$t('common.search') + '...'"
          class="search-input"
        />
        <select v-model="filterRole" class="filter-select">
          <option value="">All Roles</option>
          <option value="superadmin">{{ $t('users.roles.superadmin') }}</option>
          <option value="admin">{{ $t('users.roles.admin') }}</option>
          <option value="owner">{{ $t('users.roles.owner') }}</option>
          <option value="user">{{ $t('users.roles.user') }}</option>
        </select>
        <select v-model="filterOrg" class="filter-select">
          <option value="">All Organizations</option>
          <option value="null">No Organization (Cloud)</option>
          <option v-for="org in organizations" :key="org.id" :value="org.id">
            {{ org.name }}
          </option>
        </select>
        <select v-model="filterStatus" class="filter-select">
          <option value="">All Statuses</option>
          <option value="pending">Pending</option>
          <option value="active">Active</option>
          <option value="suspended">Suspended</option>
        </select>
      </div>

      <div v-if="loading" class="loading">{{ $t('common.loading') }}</div>
      <div v-else-if="error" class="error">{{ error }}</div>

      <table v-else-if="filteredUsers.length > 0" class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Email</th>
            <th>{{ $t('users.fullName') }}</th>
            <th>{{ $t('users.role') }}</th>
            <th>{{ $t('devices.organization') }}</th>
            <th>Email ✓</th>
            <th>Last Login</th>
            <th>{{ $t('common.status') }}</th>
            <th>{{ $t('common.actions') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td><strong>{{ user.email }}</strong></td>
            <td>{{ user.full_name || '-' }}</td>
            <td><span class="badge role">{{ $t(`users.roles.${user.role}`) }}</span></td>
            <td>{{ getOrganizationName(user.organization_id) }}</td>
            <td>
              <span class="badge" :class="user.email_verified ? 'badge-verified' : 'badge-unverified'">
                {{ user.email_verified ? '✓' : '✗' }}
              </span>
            </td>
            <td>{{ formatLastLogin(user.last_login_at) }}</td>
            <td><span class="badge" :class="`status-${user.status}`">{{ user.status }}</span></td>
            <td>
              <div class="actions">
                <button @click="showEditModal(user)" class="btn-icon" title="Edit">✏️</button>
                <button @click="showPasswordModal(user)" class="btn-icon" title="Change Password">🔑</button>
                <button @click="confirmDelete(user)" class="btn-icon" title="Delete">🗑️</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-else class="empty">No users yet</div>
    </div>

    <!-- Create/Edit Modal -->
    <div v-if="modalVisible" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h2>{{ editingUser ? $t('common.edit') : $t('users.add') }}</h2>
          <button @click="closeModal" class="btn-close">×</button>
        </div>
        <form @submit.prevent="saveUser" class="modal-body">
          <div class="form-group">
            <label>Email *</label>
            <input v-model="form.email" type="email" required :disabled="!!editingUser" />
          </div>
          <div class="form-group" v-if="!editingUser">
            <label>{{ $t('auth.password') }} *</label>
            <input v-model="form.password" type="password" minlength="8" required />
          </div>
          <div class="form-group">
            <label>{{ $t('users.fullName') }}</label>
            <input v-model="form.full_name" type="text" />
          </div>
          <div class="form-group">
            <label>Phone</label>
            <input v-model="form.phone" type="tel" />
          </div>
          <div class="form-group">
            <label>{{ $t('users.role') }} *</label>
            <select v-model="form.role" required>
              <option value="superadmin">{{ $t('users.roles.superadmin') }}</option>
              <option value="admin">{{ $t('users.roles.admin') }}</option>
              <option value="owner">{{ $t('users.roles.owner') }}</option>
              <option value="user">{{ $t('users.roles.user') }}</option>
            </select>
          </div>
          <div class="form-group" v-if="form.role !== 'superadmin' && form.role !== 'admin'">
            <label>{{ $t('devices.organization') }} *</label>
            <select v-model="form.organization_id" required>
              <option :value="null">Select organization...</option>
              <option v-for="org in organizations" :key="org.id" :value="org.id">
                {{ org.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>{{ $t('common.status') }}</label>
            <select v-model="form.status">
              <option value="pending">Pending</option>
              <option value="active">Active</option>
              <option value="suspended">Suspended</option>
            </select>
          </div>
          <div class="form-group">
            <label>{{ $t('users.notes') }}</label>
            <textarea v-model="form.notes" rows="3" :placeholder="$t('users.notesHint')"></textarea>
          </div>
          <div class="modal-footer">
            <button type="button" @click="closeModal" class="btn-secondary">{{ $t('common.cancel') }}</button>
            <button type="submit" :disabled="saving" class="btn-primary">
              {{ saving ? $t('common.loading') : $t('common.save') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Change Password Modal -->
    <div v-if="passwordModalVisible" class="modal-overlay" @click="passwordModalVisible = false">
      <div class="modal modal-sm" @click.stop>
        <div class="modal-header">
          <h2>Change Password</h2>
          <button @click="passwordModalVisible = false" class="btn-close">×</button>
        </div>
        <form @submit.prevent="changePassword" class="modal-body">
          <div class="form-group">
            <label>New Password *</label>
            <input v-model="passwordForm.new_password" type="password" minlength="8" required />
          </div>
          <div class="modal-footer">
            <button type="button" @click="passwordModalVisible = false" class="btn-secondary">{{ $t('common.cancel') }}</button>
            <button type="submit" :disabled="changingPassword" class="btn-primary">
              {{ changingPassword ? $t('common.loading') : $t('common.save') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div v-if="deleteConfirmVisible" class="modal-overlay" @click="deleteConfirmVisible = false">
      <div class="modal modal-sm" @click.stop>
        <div class="modal-header">
          <h2>{{ $t('common.confirm') }}</h2>
        </div>
        <div class="modal-body">
          <p>Delete user <strong>{{ userToDelete?.email }}</strong>?</p>
        </div>
        <div class="modal-footer">
          <button @click="deleteConfirmVisible = false" class="btn-secondary">{{ $t('common.cancel') }}</button>
          <button @click="deleteUser" :disabled="deleting" class="btn-danger">
            {{ deleting ? $t('common.loading') : $t('common.delete') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import usersApi from '@/api/users'
import organizationsApi from '@/api/organizations'

const route = useRoute()
const router = useRouter()

const users = ref([])
const organizations = ref([])
const loading = ref(false)
const error = ref(null)
const modalVisible = ref(false)
const passwordModalVisible = ref(false)
const deleteConfirmVisible = ref(false)
const editingUser = ref(null)
const userForPassword = ref(null)
const userToDelete = ref(null)
const saving = ref(false)
const changingPassword = ref(false)
const deleting = ref(false)

// Filters
const searchQuery = ref('')
const filterRole = ref('')
const filterOrg = ref('')
const filterStatus = ref('')

const form = ref({
  email: '',
  password: '',
  full_name: '',
  phone: '',
  role: 'user',
  organization_id: null,
  status: 'pending',
  notes: ''
})

const passwordForm = ref({
  new_password: ''
})

// Filtered users
const filteredUsers = computed(() => {
  let result = users.value

  // Search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user =>
      user.email.toLowerCase().includes(query) ||
      (user.full_name && user.full_name.toLowerCase().includes(query))
    )
  }

  // Role filter
  if (filterRole.value) {
    result = result.filter(user => user.role === filterRole.value)
  }

  // Organization filter
  if (filterOrg.value) {
    if (filterOrg.value === 'null') {
      result = result.filter(user => user.organization_id === null)
    } else {
      result = result.filter(user => user.organization_id === parseInt(filterOrg.value))
    }
  }

  // Status filter
  if (filterStatus.value) {
    result = result.filter(user => user.status === filterStatus.value)
  }

  return result
})

async function loadUsers() {
  loading.value = true
  error.value = null
  try {
    users.value = await usersApi.getAllSuperadmin()
  } catch (err) {
    error.value = err.response?.data?.detail || 'Failed to load users'
  } finally {
    loading.value = false
  }
}

async function loadOrganizations() {
  try {
    organizations.value = await organizationsApi.getAll()
  } catch (err) {
    console.error('Failed to load organizations:', err)
  }
}

function getOrganizationName(orgId) {
  if (!orgId) return 'None'
  const org = organizations.value.find(o => o.id === orgId)
  return org ? org.name : `Org #${orgId}`
}

function formatLastLogin(lastLoginAt) {
  if (!lastLoginAt) return 'Never'
  const date = new Date(lastLoginAt)
  const now = new Date()
  const diffMs = now - date
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 60) return `${diffMins}m ago`
  if (diffHours < 24) return `${diffHours}h ago`
  if (diffDays < 7) return `${diffDays}d ago`
  return date.toLocaleDateString()
}

function showCreateModal() {
  editingUser.value = null
  form.value = {
    email: '',
    password: '',
    full_name: '',
    phone: '',
    role: 'user',
    organization_id: null,
    status: 'pending',
    notes: ''
  }
  modalVisible.value = true
}

function showEditModal(user) {
  editingUser.value = user
  form.value = {
    email: user.email,
    full_name: user.full_name || '',
    phone: user.phone || '',
    role: user.role,
    organization_id: user.organization_id,
    status: user.status,
    notes: user.notes || ''
  }
  modalVisible.value = true
}

function closeModal() {
  modalVisible.value = false
  editingUser.value = null
}

function showPasswordModal(user) {
  userForPassword.value = user
  passwordForm.value.new_password = ''
  passwordModalVisible.value = true
}

async function saveUser() {
  saving.value = true
  try {
    if (editingUser.value) {
      await usersApi.updateSuperadmin(editingUser.value.id, form.value)
    } else {
      await usersApi.createSuperadmin(form.value)
    }
    await loadUsers()
    closeModal()
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to save user')
  } finally {
    saving.value = false
  }
}

async function changePassword() {
  changingPassword.value = true
  try {
    await usersApi.changePasswordSuperadmin(userForPassword.value.id, passwordForm.value)
    passwordModalVisible.value = false
    alert('Password changed successfully')
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to change password')
  } finally {
    changingPassword.value = false
  }
}

function confirmDelete(user) {
  userToDelete.value = user
  deleteConfirmVisible.value = true
}

async function deleteUser() {
  deleting.value = true
  try {
    await usersApi.deleteSuperadmin(userToDelete.value.id)
    await loadUsers()
    deleteConfirmVisible.value = false
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to delete user')
  } finally {
    deleting.value = false
  }
}

// Auto-clear organization if role is cloud-side (superadmin or admin)
watch(() => form.value.role, (newRole) => {
  if (newRole === 'superadmin' || newRole === 'admin') {
    form.value.organization_id = null
  }
})

// Watch for query parameter to auto-open edit modal
watch(() => route.query.edit, async (userId) => {
  if (userId) {
    const user = users.value.find(u => u.id === parseInt(userId))
    if (user) {
      showEditModal(user)
    } else {
      // User not loaded yet, wait for load
      await loadUsers()
      const loadedUser = users.value.find(u => u.id === parseInt(userId))
      if (loadedUser) {
        showEditModal(loadedUser)
      }
    }
    // Clear query param
    router.replace({ query: {} })
  }
}, { immediate: true })

onMounted(() => {
  loadUsers()
  loadOrganizations()
})
</script>

<style scoped>
.page { padding: 32px; }
.page-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 32px; }
.page-header h1 { font-size: 32px; font-weight: 700; color: #1a202c; margin-bottom: 8px; }
.page-header p { color: #718096; font-size: 16px; }
.content { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); }

.filters-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
  padding: 10px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
}

.filter-select {
  min-width: 180px;
  padding: 10px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: border-color 0.2s;
}

.filter-select:focus {
  outline: none;
  border-color: #667eea;
}
.loading, .error, .empty { text-align: center; padding: 40px; color: #718096; }
.error { color: #e53e3e; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th { text-align: left; padding: 12px; border-bottom: 2px solid #e2e8f0; font-weight: 600; color: #4a5568; font-size: 14px; }
.data-table td { padding: 12px; border-bottom: 1px solid #e2e8f0; color: #1a202c; }
.data-table tbody tr:hover { background: #f7fafc; }
.badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; background: #e2e8f0; color: #718096; }
.badge.role { background: #dbeafe; color: #1e40af; }
.badge.status-active { background: #c6f6d5; color: #22543d; }
.badge.status-pending { background: #fef3c7; color: #92400e; }
.badge.status-suspended { background: #fed7d7; color: #742a2a; }
.badge.badge-verified { background: #c6f6d5; color: #22543d; }
.badge.badge-unverified { background: #e2e8f0; color: #718096; }
.actions { display: flex; gap: 8px; }
.btn-icon { padding: 4px 8px; background: none; border: none; cursor: pointer; font-size: 16px; opacity: 0.7; transition: opacity 0.2s; }
.btn-icon:hover { opacity: 1; }
.btn-primary { padding: 12px 24px; background: #667eea; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-primary:hover { background: #5568d3; }
.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
.btn-secondary { padding: 12px 24px; background: #e2e8f0; color: #4a5568; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-secondary:hover { background: #cbd5e0; }
.btn-danger { padding: 12px 24px; background: #f56565; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-danger:hover { background: #e53e3e; }
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal { background: white; border-radius: 12px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto; }
.modal-sm { max-width: 400px; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 24px; border-bottom: 1px solid #e2e8f0; }
.modal-header h2 { font-size: 24px; font-weight: 700; color: #1a202c; }
.btn-close { width: 32px; height: 32px; border: none; background: none; font-size: 32px; color: #718096; cursor: pointer; line-height: 1; }
.btn-close:hover { color: #1a202c; }
.modal-body { padding: 24px; }
.modal-footer { display: flex; justify-content: flex-end; gap: 12px; padding: 24px; border-top: 1px solid #e2e8f0; }
.form-group { margin-bottom: 20px; }
.form-group label { display: block; margin-bottom: 8px; font-weight: 500; color: #4a5568; font-size: 14px; }
.form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 14px; transition: border-color 0.2s; font-family: inherit; }
.form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: #667eea; }
.form-group input:disabled { background: #f7fafc; color: #718096; }
.form-group textarea { resize: vertical; min-height: 80px; }
</style>
