<template>
  <div class="profile-management">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>Profiilin hallinta</h2>
    </div>

    <div class="row">
      <div class="col-md-8">
        <!-- Profile Form -->
        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">Perustiedot</h5>
          </div>
          <div class="card-body">
            <form @submit.prevent="saveProfile">
              <div class="row">
                <div class="col-md-6 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
                  >
                  <small class="form-text text-muted">Käyttäjänimeä ei voi muuttaa</small>
                </div>
                <div class="col-md-6 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>
              
              <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 class="mb-3">
                <label for="role" class="form-label">Rooli</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="role" 
                  :value="getRoleLabel(formData.role)" 
                  disabled
                >
                <small class="form-text text-muted">Roolin voi muuttaa vain ylläpitäjä</small>
              </div>
              
              <div class="d-flex justify-content-between">
                <div>
                  <h6>Tilin tiedot</h6>
                  <p class="text-muted">
                    <strong>Luotu:</strong> {{ formatDate(formData.created_at) }}<br>
                    <strong>Päivitetty:</strong> {{ formatDate(formData.updated_at) }}<br>
                    <strong>Viimeksi kirjautunut:</strong> {{ formatDate(formData.last_login) }}
                  </p>
                </div>
                <div>
                  <button type="submit" class="btn btn-primary" :disabled="loading">
                    <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                    Tallenna muutokset
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
      
      <div class="col-md-4">
        <!-- Password Change -->
        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">Salasanan vaihto</h5>
          </div>
          <div class="card-body">
            <form @submit.prevent="changePassword">
              <div class="mb-3">
                <label for="currentPassword" class="form-label">Nykyinen salasana</label>
                <input 
                  type="password" 
                  class="form-control" 
                  id="currentPassword" 
                  v-model="passwordForm.current_password" 
                  required
                >
              </div>
              
              <div class="mb-3">
                <label for="newPassword" class="form-label">Uusi salasana</label>
                <input 
                  type="password" 
                  class="form-control" 
                  id="newPassword" 
                  v-model="passwordForm.password" 
                  required
                  minlength="8"
                >
                <small class="form-text text-muted">Vähintään 8 merkkiä</small>
              </div>
              
              <div class="mb-3">
                <label for="confirmPassword" class="form-label">Vahvista uusi salasana</label>
                <input 
                  type="password" 
                  class="form-control" 
                  id="confirmPassword" 
                  v-model="passwordForm.confirm_password" 
                  required
                >
              </div>
              
              <button type="submit" class="btn btn-warning w-100" :disabled="passwordLoading">
                <span v-if="passwordLoading" class="spinner-border spinner-border-sm me-2"></span>
                Vaihda salasana
              </button>
            </form>
          </div>
        </div>
        
        <!-- Account Status -->
        <div class="card mt-3">
          <div class="card-header">
            <h5 class="mb-0">Tilin tila</h5>
          </div>
          <div class="card-body">
            <div class="d-flex align-items-center">
              <span :class="getStatusBadgeClass(formData.is_active)" class="me-2">
                {{ formData.is_active ? 'Aktiivinen' : 'Passiivinen' }}
              </span>
              <small class="text-muted" v-if="!formData.is_active">
                Tili on passiivinen. Ota yhteyttä ylläpitäjään.
              </small>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'ProfileManagement',
  props: {
    currentUser: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      passwordLoading: false,
      formData: {
        id: null,
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        role: '',
        is_active: false,
        created_at: null,
        updated_at: null,
        last_login: null
      },
      passwordForm: {
        current_password: '',
        password: '',
        confirm_password: ''
      }
    }
  },
  
  async mounted() {
    await this.loadProfile()
  },
  
  methods: {
    async loadProfile() {
      this.loading = true
      try {
        // Use currentUser prop instead of making API call
        if (!this.currentUser || !this.currentUser.id) {
          this.$emit('error', 'Käyttäjätietoja ei löytynyt')
          return
        }
        
        // Load full user profile
        const profileResponse = await api.get(`/users.php?id=${this.currentUser.id}`)
        this.formData = profileResponse.data
      } catch (error) {
        console.error('Error loading profile:', error)
        this.$emit('error', 'Profiilin lataaminen epäonnistui')
      } finally {
        this.loading = false
      }
    },
    
    async saveProfile() {
      this.loading = true
      try {
        await api.put('/users', this.formData)
        this.$emit('success', 'Profiili päivitetty onnistuneesti')
        await this.loadProfile()
      } catch (error) {
        console.error('Error saving profile:', error)
        const message = error.response?.data?.message || 'Profiilin tallentaminen epäonnistui'
        this.$emit('error', message)
      } finally {
        this.loading = false
      }
    },
    
    async changePassword() {
      if (this.passwordForm.password !== this.passwordForm.confirm_password) {
        this.$emit('error', 'Salasanat eivät täsmää')
        return
      }
      
      if (this.passwordForm.password.length < 8) {
        this.$emit('error', 'Salasanan tulee olla vähintään 8 merkkiä pitkä')
        return
      }
      
      this.passwordLoading = true
      try {
        await api.put('/users', {
          ...this.formData,
          password: this.passwordForm.password,
          current_password: this.passwordForm.current_password
        })
        
        this.$emit('success', 'Salasana vaihdettu onnistuneesti')
        
        // Clear password form
        this.passwordForm = {
          current_password: '',
          password: '',
          confirm_password: ''
        }
      } catch (error) {
        console.error('Error changing password:', error)
        const message = error.response?.data?.message || 'Salasanan vaihtaminen epäonnistui'
        this.$emit('error', message)
      } finally {
        this.passwordLoading = false
      }
    },
    
    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>
.profile-management {
  padding: 20px;
  color: #333 !important;
}

.card {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  background-color: #ffffff;
  color: #333;
}

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

.card-body {
  color: #333;
}

.form-label {
  color: #495057;
  font-weight: 500;
}

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

.form-control:disabled {
  background-color: #e9ecef;
  color: #6c757d;
}

.form-text {
  font-size: 0.875em;
  color: #6c757d !important;
}

.btn {
  color: #ffffff;
}

.btn-primary {
  background-color: #007bff;
  border-color: #007bff;
}

.btn-primary:hover {
  background-color: #0056b3;
  border-color: #004085;
}

.btn-secondary {
  background-color: #6c757d;
  border-color: #6c757d;
}

.btn-secondary:hover {
  background-color: #545b62;
  border-color: #545b62;
}

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

h2, h5 {
  color: white !important;
}

.text-muted {
  color: #6c757d !important;
}

.alert {
  color: #333;
}

.alert-success {
  background-color: #d4edda;
  border-color: #c3e6cb;
  color: #155724;
}

.alert-danger {
  background-color: #f8d7da;
  border-color: #f5c6cb;
  color: #721c24;
}
</style>
