<template>
  <div class="user-management">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>Käyttäjien hallinta</h2>
      <button class="btn btn-primary" @click="showCreateModal = true">
        <i class="fas fa-plus"></i> Luo uusi käyttäjä
      </button>
    </div>

    <!-- Users Table -->
    <div class="card">
      <div class="card-body">
        <div v-if="loading" class="text-center">
          <div class="spinner-border" role="status">
            <span class="visually-hidden">Ladataan...</span>
          </div>
        </div>
        
        <div v-else-if="users.length === 0" class="text-center text-muted">
          <i class="fas fa-users fa-3x mb-3"></i>
          <p>Ei käyttäjiä löytynyt</p>
        </div>
        
        <div v-else class="table-responsive">
          <table class="table table-striped">
            <thead>
              <tr>
                <th>Käyttäjänimi</th>
                <th>Nimi</th>
                <th>Sähköposti</th>
                <th>Rooli</th>
                <th>Tila</th>
                <th>Viimeksi kirjautunut</th>
                <th>Toiminnot</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.username }}</td>
                <td>{{ user.first_name }} {{ user.last_name }}</td>
                <td>{{ user.email }}</td>
                <td>
                  <span :class="getRoleBadgeClass(user.role)">
                    {{ getRoleLabel(user.role) }}
                  </span>
                </td>
                <td>
                  <span :class="getStatusBadgeClass(user.is_active)">
                    {{ user.is_active ? 'Aktiivinen' : 'Passiivinen' }}
                  </span>
                </td>
                <td>{{ formatDate(user.last_login) }}</td>
                <td>
                  <div class="btn-group" role="group">
                    <button 
                      class="btn btn-sm btn-outline-primary" 
                      @click="editUser(user)"
                      title="Muokkaa"
                    >
                      <i class="fas fa-edit"></i>
                    </button>
                    <button 
                      class="btn btn-sm btn-outline-danger" 
                      @click="deleteUser(user)"
                      title="Poista"
                      :disabled="currentUser && user.id === currentUser.id"
                    >
                      <i class="fas fa-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Create/Edit User Modal -->
    <div class="modal fade" :class="{ show: showCreateModal || showEditModal }" 
         :style="{ display: showCreateModal || showEditModal ? 'block' : 'none' }">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              {{ editingUser ? 'Muokkaa käyttäjää' : 'Luo uusi käyttäjä' }}
            </h5>
            <button type="button" class="btn-close" @click="closeModals"></button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="saveUser">
              <div class="mb-3">
                <label for="username" class="form-label">Käyttäjänimi</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="username" 
                  v-model="formData.username" 
                  required
                  :disabled="editingUser"
                >
              </div>
              
              <div class="mb-3">
                <label for="email" class="form-label">Sähköposti</label>
                <input 
                  type="email" 
                  class="form-control" 
                  id="email" 
                  v-model="formData.email" 
                  required
                >
              </div>
              
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label for="firstName" class="form-label">Etunimi</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="firstName" 
                    v-model="formData.first_name" 
                    required
                  >
                </div>
                <div class="col-md-6 mb-3">
                  <label for="lastName" class="form-label">Sukunimi</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="lastName" 
                    v-model="formData.last_name" 
                    required
                  >
                </div>
              </div>
              
              <div v-if="!editingUser" class="mb-3">
                <label for="password" class="form-label">Salasana</label>
                <input 
                  type="password" 
                  class="form-control" 
                  id="password" 
                  v-model="formData.password" 
                  required
                >
              </div>
              
              <div v-else class="mb-3">
                <label for="newPassword" class="form-label">Uusi salasana (jätä tyhjäksi jos et halua vaihtaa)</label>
                <input 
                  type="password" 
                  class="form-control" 
                  id="newPassword" 
                  v-model="formData.password"
                  placeholder="Jätä tyhjäksi jos et halua vaihtaa salasanaa"
                >
              </div>
              
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label for="role" class="form-label">Rooli</label>
                  <select class="form-select" id="role" v-model="formData.role">
                    <option value="user">Käyttäjä</option>
                    <option value="admin">Ylläpitäjä</option>
                  </select>
                </div>
                <div class="col-md-6 mb-3">
                  <label for="isActive" class="form-label">Tila</label>
                  <select class="form-select" id="isActive" v-model="formData.is_active">
                    <option :value="true">Aktiivinen</option>
                    <option :value="false">Passiivinen</option>
                  </select>
                </div>
              </div>
              
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" @click="closeModals">
                  Peruuta
                </button>
                <button type="submit" class="btn btn-primary">
                  {{ editingUser ? 'Tallenna' : 'Luo' }}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../api/axios'

export default {
  name: 'UserManagement',
  props: {
    currentUser: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      users: [],
      loading: false,
      showCreateModal: false,
      showEditModal: false,
      editingUser: null,
      formData: {
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        password: '',
        role: 'user',
        is_active: true
      }
    }
  },
  
  async mounted() {
    await this.loadUsers()
  },
  
  methods: {
        
    async loadUsers() {
      this.loading = true
      try {
        const response = await api.get('/users.php')
        this.users = response.data.records || []
      } catch (error) {
        console.error('Error loading users:', error)
        this.$emit('error', 'Käyttäjien lataaminen epäonnistui')
      } finally {
        this.loading = false
      }
    },
    
    editUser(user) {
      this.editingUser = user
      this.formData = {
        id: user.id,
        username: user.username,
        email: user.email,
        first_name: user.first_name,
        last_name: user.last_name,
        password: '',
        role: user.role,
        is_active: user.is_active === '1' || user.is_active === 1 || user.is_active === true
      }
      this.showEditModal = true
    },
    
    async saveUser() {
      try {
        if (this.editingUser) {
          await api.put('/users.php', this.formData)
          this.$emit('success', 'Käyttäjä päivitetty onnistuneesti')
        } else {
          await api.post('/users.php', this.formData)
          this.$emit('success', 'Käyttäjä luotu onnistuneesti')
        }
        
        this.closeModals()
        await this.loadUsers()
      } catch (error) {
        console.error('Error saving user:', error)
        const message = error.response?.data?.message || 'Käyttäjän tallentaminen epäonnistui'
        this.$emit('error', message)
      }
    },
    
    async deleteUser(user) {
      if (!confirm(`Oletko varma että haluat poistaa käyttäjän ${user.username}?`)) {
        return
      }
      
      try {
        await api.delete(`/users?id=${user.id}`)
        this.$emit('success', 'Käyttäjä poistettu onnistuneesti')
        await this.loadUsers()
      } catch (error) {
        console.error('Error deleting user:', error)
        const message = error.response?.data?.message || 'Käyttäjän poistaminen epäonnistui'
        this.$emit('error', message)
      }
    },
    
    closeModals() {
      this.showCreateModal = false
      this.showEditModal = false
      this.editingUser = null
      this.formData = {
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        password: '',
        role: 'user',
        is_active: true
      }
    },
    
    getRoleBadgeClass(role) {
      return role === 'admin' ? 'badge bg-danger' : 'badge bg-primary'
    },
    
    getRoleLabel(role) {
      return role === 'admin' ? 'Ylläpitäjä' : 'Käyttäjä'
    },
    
    getStatusBadgeClass(isActive) {
      return isActive ? 'badge bg-success' : 'badge bg-secondary'
    },
    
    formatDate(dateString) {
      if (!dateString) return 'Ei koskaan'
      return new Date(dateString).toLocaleString('fi-FI')
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.modal {
  background-color: rgba(0, 0, 0, 0.5);
}

.modal.show {
  display: block !important;
}

.modal-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  color: #495057;
}

.modal-title {
  color: #495057 !important;
}

.modal-body {
  background-color: #ffffff;
  color: #333;
}

.modal-footer {
  background-color: #f8f9fa;
  border-top: 1px solid #dee2e6;
}

/* Form styling for modal */
.form-label {
  color: #495057;
  font-weight: 500;
}

.form-control, .form-select {
  color: #495057;
  background-color: #ffffff;
  border-color: #ced4da;
}

.form-control:focus, .form-select:focus {
  color: #495057;
  background-color: #ffffff;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-check-input {
  background-color: #ffffff;
  border-color: #ced4da;
}

.form-check-input:checked {
  background-color: #007bff;
  border-color: #007bff;
}

.form-check-input:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-check-label {
  color: #495057;
  margin-left: 8px;
}

.btn-group .btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Fix white-on-white issue in table */
.table {
  color: #333 !important;
}

.table th {
  background-color: #f8f9fa;
  color: #495057;
  border-bottom: 2px solid #dee2e6;
}

.table td {
  color: #333;
  border-top: 1px solid #dee2e6;
}

.table-striped tbody tr:nth-of-type(odd) {
  background-color: rgba(0, 0, 0, 0.05);
}

.table-striped tbody tr:nth-of-type(even) {
  background-color: #ffffff;
}

.table tbody tr:hover {
  background-color: #f8f9fa;
}

/* Ensure badges are visible with proper contrast */
.badge {
  color: white !important;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.75em;
}

/* Role badge specific styling */
.badge.bg-danger {
  background-color: #dc3545 !important;
}

.badge.bg-primary {
  background-color: #007bff !important;
}

.badge.bg-success {
  background-color: #28a745 !important;
}

.badge.bg-secondary {
  background-color: #6c757d !important;
}

/* Status badge specific styling */
.badge.bg-warning {
  background-color: #ffc107 !important;
  color: #212529 !important;
}

.badge.bg-info {
  background-color: #17a2b8 !important;
}

/* Fix button text color and visibility */
.btn-outline-primary {
  color: #007bff !important;
  border-color: #007bff;
  background-color: #007bff;
  padding: 6px 12px;
  min-width: 36px;
  min-height: 36px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-outline-primary:hover {
  background-color: #0056b3;
  color: white !important;
  border-color: #0056b3;
}

.btn-outline-primary:focus {
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn-outline-danger {
  color: white !important;
  border-color: #dc3545;
  background-color: #dc3545;
  padding: 6px 12px;
  min-width: 36px;
  min-height: 36px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-outline-danger:hover {
  background-color: #c82333;
  color: white !important;
  border-color: #c82333;
}

.btn-outline-danger:focus {
  box-shadow: 0 0 0 2px rgba(220, 53, 69, 0.25);
}

.btn-outline-danger:disabled {
  color: #6c757d !important;
  border-color: #6c757d;
  background-color: transparent;
  opacity: 0.6;
}

/* Ensure icons are visible */
.btn i {
  font-size: 14px;
  line-height: 1;
}

/* Button group styling */
.btn-group .btn {
  margin-right: 4px;
}

.btn-group .btn:last-child {
  margin-right: 0;
}
</style>
