<template>
  <div class="about" v-if="isAdmin">

    <!-- Manage User modal -->
    <div v-if="showCard" class="modal d-block" tabindex="-1" style="background:rgba(0,0,0,0.5);" @click.self="showCard=false">
      <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Manage User</h5>
            <button type="button" class="btn-close" aria-label="Close" @click="showCard=false"></button>
          </div>
          <div class="modal-body">

            <div class="row mb-2">
              <div class="col-12">
                <table class="table table-striped table-inverse table-responsive">
                    <tbody>
                      <tr>
                        <td scope="row">
                          <strong>
                            Name
                          </strong>
                        </td>
                        <td>
                          {{ rowData.fname }} {{ rowData.lname }}
                        </td>                        
                      </tr>
                      <tr>
                        <td scope="row"><strong>Username</strong></td>
                        <td>
                          <span class="text-bold ms-2">{{ rowData.username }}</span>                          
                        </td>
                      </tr>
                      <tr>
                        <td>
                          <label class="col-sm-4 col-form-label fw-bold">Status</label>
                        </td>
                        <td scope="row">
                          <select class="form-select" v-model="selectedStatus">
                            <option value="active">active</option>
                            <option value="inactive">inactive</option>
                            <option value="pending">pending</option>
                          </select>
                        </td>
                      </tr>
                    </tbody>
                </table>
              </div>
            </div>

            <!-- Status update -->
            
            <button class="btn btn-primary me-2" :disabled="statusLoading" @click="saveStatus">
              <span v-if="statusLoading" class="spinner-border spinner-border-sm me-1"></span>
              Save Status
            </button>
            <button class="btn btn-warning" @click="showResetModal=true">Reset Password</button>

            <hr class="my-3" />

            <div class="row mb-2">
              <label class="col-12 col-form-label fw-bold text-start">User Groups</label>
              <div class="col-12">
                <div v-if="groupLoading" class="text-muted">Loading groups...</div>
                <div v-else-if="groupOptions.length===0" class="text-muted">No groups found.</div>
                <div v-else class="border rounded p-2" style="max-height:220px; overflow:auto;">
                  <div class="form-check text-start" v-for="g in groupOptions" :key="g.id">
                    <input
                      class="form-check-input"
                      type="checkbox"
                      :id="'group-'+g.id"
                      :value="g.id"
                      v-model="selectedGroupIds"
                    />
                    <label class="form-check-label" :for="'group-'+g.id">
                      {{ g.name }}
                      <small class="text-muted ms-1">({{ g.status }})</small>
                    </label>
                  </div>
                </div>
              </div>
            </div>
            <button class="btn btn-info text-white mt-2" :disabled="groupLoading || groupSaving" @click="saveGroups">
              <span v-if="groupSaving" class="spinner-border spinner-border-sm me-1"></span>
              Save Groups
            </button>

          </div>
          <div class="modal-footer">
            <button class="btn btn-secondary" @click="showCard=false">Close</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Password reset modal -->
    <div v-if="showResetModal && showCard" class="modal d-block" tabindex="-1" style="background:rgba(0,0,0,0.5);" @click.self="showResetModal=false">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Reset Password -- {{ rowData.username }}</h5>
            <button type="button" class="btn-close" @click="showResetModal=false"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label fw-bold">New Password</label>
              <input type="password" class="form-control" v-model="resetPassword" placeholder="Min. 8 characters"/>
            </div>
            <div class="mb-3">
              <label class="form-label fw-bold">Confirm Password</label>
              <input type="password" class="form-control" v-model="resetConfirm" placeholder="Repeat password"/>
            </div>
            <div v-if="resetError" class="alert alert-danger py-2">{{ resetError }}</div>
          </div>
          <div class="modal-footer">
            <button class="btn btn-secondary" @click="showResetModal=false">Cancel</button>
            <button class="btn btn-warning" @click="submitPasswordReset" :disabled="resetLoading">
              <span v-if="resetLoading" class="spinner-border spinner-border-sm me-1"></span>
              Reset Password
            </button>
          </div>
        </div>
      </div>
    </div>

    <TransitionGroup>

      <!-- Create card shown when New is clicked -->
      <div class="card mx-auto my-5 shadow" style="min-width:18rem; max-width:42rem; overflow:auto;" v-if="showCreateCard" :key="'create-card'">
        <div class="card-body">
          <h5 class="card-title">Create User</h5>
          <button type="button" class="btn-close position-absolute fs-4" aria-label="Close"
            style="right:5px; top:5px;" @click.prevent="cancelCreateCard"></button>

          <div class="row">
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">First Name</label>
              <input type="text" class="form-control" v-model="newUser.fname" />
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Middle Name</label>
              <input type="text" class="form-control" v-model="newUser.mname" />
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Last Name</label>
              <input type="text" class="form-control" v-model="newUser.lname" />
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Gender</label>
              <select class="form-select" v-model="newUser.gender">
                <option value="unspecified">unspecified</option>
                <option value="male">male</option>
                <option value="female">female</option>
                <option value="other">other</option>
              </select>
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Username</label>
              <input type="text" class="form-control" v-model="newUser.username" />
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Email</label>
              <input type="email" class="form-control" v-model="newUser.email" />
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Phone</label>
              <input type="text" class="form-control" v-model="newUser.phone" />
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label fw-bold">Status</label>
              <select class="form-select" v-model="newUser.status">
                <option value="active">active</option>
                <option value="inactive">inactive</option>
                <option value="pending">pending</option>
              </select>
            </div>
            <div class="col-12 mb-2">
              <label class="form-label fw-bold">Password</label>
              <input type="password" class="form-control" v-model="newUser.password" placeholder="Min. 8 characters" />
            </div>
          </div>

          <div v-if="createError" class="alert alert-danger py-2 mt-2">{{ createError }}</div>

          <button class="btn btn-primary me-2" :disabled="createLoading" @click="createUser">
            <span v-if="createLoading" class="spinner-border spinner-border-sm me-1"></span>
            Create User
          </button>
          <button class="btn btn-secondary" @click="cancelCreateCard">Cancel</button>
        </div>
      </div>

      <!-- Users table -->
      <cdTable
        v-else
        :key="'table-'+tableRefreshKey"
        :links="links"
        title="Users"
        table-name="user"
        :hidden="hidden"
        :headers="headers"
        :gen-form="false"
        :allow-new="true"
        @popForm="setRowData"
      />

    </TransitionGroup>
  </div>
</template>

<script>
import cdTable from '@/components/cddatatables/cdTable.vue';
import { userLinks } from '@/cd-links';

export default {
  name: 'AdminUsersView',
  components: { cdTable },
  data() {
    return {
      links: userLinks,
      headers: {
        id:       'ID',
        fname:    'First Name',
        lname:    'Last Name',
        username: 'Username',
        email:    'Email',
        phone:    'Phone',
        status:   'Status',
      },
      hidden: ['creatorId', 'createdAt', 'updatedAt', 'mname', 'gender'],
      showCreateCard: false,
      tableRefreshKey: 0,
      showCard: false,
      rowData: {},
      selectedStatus: 'active',
      statusLoading: false,
      newUser: {
        fname: '',
        mname: '',
        lname: '',
        gender: 'unspecified',
        username: '',
        email: '',
        phone: '',
        password: '',
        status: 'active'
      },
      createLoading: false,
      createError: null,
      showResetModal: false,
      resetPassword: '',
      resetConfirm: '',
      resetError: null,
      resetLoading: false,
      groupOptions: [],
      selectedGroupIds: [],
      groupLoading: false,
      groupSaving: false,
    };
  },
  computed: {
    isAdmin() {
      return this.$store.getters.isAdmin;
    },
    isLoggedIn() {
      return this.$store.getters.isLoggedIn;
    }
  },
  watch: {
    isAdmin() {
      this.enforceAdminAccess();
    },
    isLoggedIn() {
      this.enforceAdminAccess();
    }
  },
  mounted() {
    this.enforceAdminAccess();
  },
  methods: {
    enforceAdminAccess() {
      if (this.isLoggedIn && this.isAdmin) return;

      this.showCard = false;
      this.showCreateCard = false;
      this.showResetModal = false;

      if (this.$route?.path === '/admin/users') {
        this.$router.replace('/');
      }
    },
    openCreateCard() {
      this.newUser = {
        fname: '',
        mname: '',
        lname: '',
        gender: 'unspecified',
        username: '',
        email: '',
        phone: '',
        password: '',
        status: 'active'
      };
      this.createError = null;
      this.showResetModal = false;
      this.showCard = false;
      this.showCreateCard = true;
    },
    cancelCreateCard() {
      this.showCreateCard = false;
      this.createError = null;
    },
    setRowData({ rowData }) {
      if (!rowData || !rowData.id) {
        this.openCreateCard();
        return;
      }
      this.rowData = rowData;
      this.selectedStatus = rowData.status || 'active';
      this.showResetModal = false;
      this.resetPassword = '';
      this.resetConfirm = '';
      this.resetError = null;
      this.groupOptions = [];
      this.selectedGroupIds = [];
      this.showCreateCard = false;
      this.showCard = true;
      this.loadUserGroups();
    },
    async loadUserGroups() {
      this.groupLoading = true;
      try {
        const resp = await this.$store.getters.getAxios.post(userLinks.readGroups, {
          id: this.rowData.id,
        });
        if (!resp.data.isLoggedIn) { this.$store.dispatch('loggedOut'); return; }

        if (resp.data.success) {
          this.groupOptions = resp.data.data?.groups || [];
          this.selectedGroupIds = (resp.data.data?.selectedGroupIds || []).map((id) => Number(id));
        } else {
          this.$store.commit('addAlert', {
            title: resp.data.title || 'Error',
            message: resp.data.msg || 'Failed to load user groups.',
            type: 'danger'
          });
        }
      } catch {
        this.$store.commit('addAlert', { title: 'Error', message: 'Failed to load user groups.', type: 'danger' });
      } finally {
        this.groupLoading = false;
      }
    },
    async saveGroups() {
      this.groupSaving = true;
      try {
        const payload = {
          id: this.rowData.id,
          groupIds: this.selectedGroupIds.map((id) => Number(id))
        };
        const resp = await this.$store.getters.getAxios.put(userLinks.updateGroups, payload);
        if (!resp.data.isLoggedIn) { this.$store.dispatch('loggedOut'); return; }

        this.$store.commit('addAlert', {
          title: resp.data.title,
          message: resp.data.msg,
          type: resp.data.success ? 'success' : 'danger'
        });
      } catch {
        this.$store.commit('addAlert', { title: 'Error', message: 'Failed to update user groups.', type: 'danger' });
      } finally {
        this.groupSaving = false;
      }
    },
    async createUser() {
      this.createError = null;
      const required = ['fname', 'lname', 'username', 'email', 'phone', 'password'];
      const missing = required.find((k) => !String(this.newUser[k] || '').trim());
      if (missing) {
        this.createError = 'Please fill all required fields.';
        return;
      }
      if (String(this.newUser.password).length < 8) {
        this.createError = 'Password must be at least 8 characters.';
        return;
      }

      this.createLoading = true;
      try {
        const payload = {
          ...this.newUser,
          username: String(this.newUser.username).trim().toLowerCase()
        };
        const resp = await this.$store.getters.getAxios.post(userLinks.post, payload);
        if (!resp.data.isLoggedIn) { this.$store.dispatch('loggedOut'); return; }

        this.$store.commit('addAlert', {
          title: resp.data.title,
          message: resp.data.msg,
          type: resp.data.success ? 'success' : 'danger'
        });

        if (resp.data.success) {
          this.showCreateCard = false;
          this.tableRefreshKey += 1;
        } else {
          this.createError = resp.data.msg || 'Failed to create user.';
        }
      } catch {
        this.createError = 'Failed to create user.';
      } finally {
        this.createLoading = false;
      }
    },
    async saveStatus() {
      this.statusLoading = true;
      try {
        const resp = await this.$store.getters.getAxios.put(userLinks.updateStatus, {
          id: this.rowData.id,
          status: this.selectedStatus
        });
        if (!resp.data.isLoggedIn) { this.$store.dispatch('loggedOut'); return; }
        this.$store.commit('addAlert', {
          title: resp.data.title,
          message: resp.data.msg,
          type: resp.data.success ? 'info' : 'danger'
        });
        if (resp.data.success) this.rowData.status = this.selectedStatus;
      } catch {
        this.$store.commit('addAlert', { title: 'Error', message: 'Failed to update status.', type: 'danger' });
      } finally {
        this.statusLoading = false;
      }
    },
    async submitPasswordReset() {
      this.resetError = null;
      if (this.resetPassword.length < 8) {
        this.resetError = 'Password must be at least 8 characters.';
        return;
      }
      if (this.resetPassword !== this.resetConfirm) {
        this.resetError = 'Passwords do not match.';
        return;
      }
      this.resetLoading = true;
      try {
        const resp = await this.$store.getters.getAxios.put(userLinks.resetPassword, {
          id: this.rowData.id,
          password: this.resetPassword
        });
        if (!resp.data.isLoggedIn) { this.$store.dispatch('loggedOut'); return; }
        this.$store.commit('addAlert', {
          title: resp.data.title,
          message: resp.data.msg,
          type: resp.data.success ? 'success' : 'danger'
        });
        if (resp.data.success) {
          this.showResetModal = false;
          this.resetPassword = '';
          this.resetConfirm = '';
        } else {
          this.resetError = resp.data.msg;
        }
      } catch {
        this.resetError = 'Failed to reset password.';
      } finally {
        this.resetLoading = false;
      }
    }
  }
};
</script>
