<template>
  <section class="content-grid">
    <!-- USERS & TEAMS -->
    <template v-if="adminSection === 'admin-users'">
    <v-card class="span-12 panel-pad">
      <div class="toolbar-row mb-4">
        <div>
          <h2 class="section-title">Users and roles</h2>
          <div class="quiet text-body-2">Manage account access, team membership, role assignment, and active status.</div>
        </div>
        <v-spacer />
        <v-btn variant="tonal" prepend-icon="mdi-account-plus" @click="userDialog = true">Add user</v-btn>
      </div>
      <DataTable
        :columns="userColumns"
        :rows="users"
        :page-size="10"
        row-key="id"
        has-actions
        searchable
        search-placeholder="Filter users"
        empty-text="No users."
      >
        <template #cell-name="{ row }">
          <span class="font-weight-bold">{{ row.name }}</span>
        </template>
        <template #cell-team_name="{ row }">{{ row.team_name || 'No team' }}</template>
        <template #cell-role="{ row }">
          <v-chip size="small" variant="tonal">{{ roleName(row.role) }}</v-chip>
        </template>
        <template #cell-status="{ row }">
          <span :class="['status-chip', row.status === 'active' ? 'status-in_service' : 'status-disposed']">{{ row.status }}</span>
          <v-chip v-if="isLocked(row)" size="x-small" color="error" variant="tonal" class="ml-1" prepend-icon="mdi-lock">Locked</v-chip>
          <v-chip v-if="row.must_change_password" size="x-small" color="warning" variant="tonal" class="ml-1" title="Must change password at next sign-in">Pwd reset</v-chip>
        </template>
        <template #actions="{ row }">
          <v-btn v-if="isLocked(row)" icon="mdi-lock-open-variant" size="small" variant="text" color="warning" title="Unlock account" @click="unlockUser(row)" />
          <v-btn icon="mdi-pencil" size="small" variant="text" @click="editUser(row)" />
        </template>
      </DataTable>
    </v-card>

    <v-card class="span-5 panel-pad">
      <div class="toolbar-row mb-4">
        <h2 class="section-title">Teams</h2>
        <v-spacer />
        <v-btn variant="tonal" size="small" prepend-icon="mdi-plus" @click="openNewTeam">Add team</v-btn>
      </div>
      <v-alert v-if="teamNotice" type="error" density="compact" class="mb-3">{{ teamNotice }}</v-alert>
      <DataTable
        :columns="teamColumns"
        :rows="teams"
        row-key="id"
        :page-size="10"
        has-actions
        searchable
        search-placeholder="Filter teams"
        empty-text="No teams."
      >
        <template #cell-name="{ row }">
          <span class="font-weight-bold">{{ row.name }}</span>
        </template>
        <template #cell-description="{ row }">{{ row.description || 'No description' }}</template>
        <template #actions="{ row }">
          <v-btn icon="mdi-pencil" size="small" variant="text" @click="editTeam(row)" />
          <v-btn icon="mdi-delete-outline" size="small" variant="text" color="error" @click="removeTeam(row)" />
        </template>
      </DataTable>
    </v-card>

    <v-card class="span-7 panel-pad">
      <div class="toolbar-row mb-4">
        <div>
          <h2 class="section-title">Roles &amp; permissions</h2>
          <div class="quiet text-body-2">Built-in and custom roles, each granting a set of capabilities.</div>
        </div>
        <v-spacer />
        <v-btn variant="tonal" size="small" prepend-icon="mdi-shield-plus-outline" @click="openNewRole">New role</v-btn>
      </div>
      <DataTable
        :columns="roleColumns"
        :rows="roles"
        row-key="key"
        :page-size="10"
        has-actions
        searchable
        search-placeholder="Filter roles"
        empty-text="No roles."
      >
        <template #cell-name="{ row }">
          <span class="font-weight-bold">{{ row.name }}</span>
          <v-chip v-if="row.is_system" size="x-small" variant="tonal" class="ml-2">Built-in</v-chip>
        </template>
        <template #cell-capabilities="{ row }">{{ capabilitySummary(row) }}</template>
        <template #actions="{ row }">
          <v-btn icon="mdi-pencil" size="small" variant="text" @click="openEditRole(row)" />
          <v-btn v-if="!row.is_system" icon="mdi-delete-outline" size="small" variant="text" color="error" @click="confirmDeleteRole(row)" />
        </template>
      </DataTable>
    </v-card>

    <!-- Role editor -->
    <v-dialog v-model="roleDialog" max-width="640" scrollable>
      <v-card>
        <v-card-title>{{ roleForm.exists ? `Edit role · ${roleForm.name}` : 'New role' }}</v-card-title>
        <v-card-text>
          <div class="form-grid">
            <v-text-field v-model="roleForm.name" label="Role name" :readonly="roleForm.locked" />
            <v-text-field v-if="!roleForm.exists" v-model="roleForm.key" label="Key (optional)" placeholder="auto from name" />
          </div>
          <v-textarea v-model="roleForm.description" label="Description" rows="2" class="mt-2" />
          <v-alert v-if="roleForm.locked" type="info" density="compact" variant="tonal" class="mt-2">
            The Administrator role always has every capability and can’t be restricted.
          </v-alert>
          <template v-else>
            <v-divider class="my-3" />
            <div class="toolbar-row mb-2">
              <h3 class="section-title">Capabilities</h3>
              <v-spacer />
              <span class="quiet text-caption">{{ roleForm.capabilities.length }} selected</span>
            </div>
            <div v-for="group in capabilityGroups" :key="group.name" class="cap-group">
              <div class="cap-group-title">{{ group.name }}</div>
              <v-checkbox
                v-for="cap in group.items"
                :key="cap.key"
                v-model="roleForm.capabilities"
                :value="cap.key"
                :label="cap.label"
                density="compact"
                hide-details
              />
            </div>
          </template>
          <v-alert v-if="roleError" type="error" density="compact" class="mt-3">{{ roleError }}</v-alert>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="roleDialog = false">Cancel</v-btn>
          <v-btn color="primary" prepend-icon="mdi-content-save" :disabled="!roleForm.name.trim()" @click="saveRole">Save role</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="roleDeleteDialog" max-width="460">
      <v-card>
        <v-card-title class="text-error">Delete role</v-card-title>
        <v-card-text>
          <p>Delete the role <strong>“{{ roleDeleteTarget?.name }}”</strong>?</p>
          <v-alert v-if="roleDeleteTarget && roleDeleteTarget.user_count" type="warning" variant="tonal" density="comfortable" class="mt-2">
            {{ roleDeleteTarget.user_count }} user(s) currently have this role and must be reassigned first.
          </v-alert>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="roleDeleteDialog = false">Cancel</v-btn>
          <v-btn color="error" prepend-icon="mdi-delete-outline" @click="performDeleteRole">Delete role</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    </template>

    <!-- PASSWORD & SECURITY -->
    <template v-if="adminSection === 'admin-security'">
    <PasswordPolicySettings :token="token" />
    </template>

    <!-- ACTIVITY & AUDIT TRAIL -->
    <template v-if="adminSection === 'admin-audit'">
    <AuditTrailSettings :token="token" />
    </template>

    <!-- APPLICATION LOGS -->
    <template v-if="adminSection === 'admin-logs'">
    <AppLogsSettings :token="token" />
    </template>

    <!-- APPLICATION CONFIGURATION -->
    <template v-if="adminSection === 'admin-config'">
    <CompanySettings :token="token" @updated="$emit('companies-updated')" />

    <v-card class="span-6 panel-pad">
      <h2 class="section-title mb-4">Application settings</h2>
      <v-text-field v-model="localSettings.server_fqdn" label="Server FQDN" />
      <v-text-field v-model="localSettings.cors_allowed_domains" label="Allowed CORS domains" />
      <v-text-field v-model="localSettings.database_driver" label="Database driver" readonly />
      <v-text-field v-model="localSettings.database_path" label="Database path" readonly />
      <v-btn color="primary" prepend-icon="mdi-content-save" @click="$emit('save-settings', localSettings)">Save settings</v-btn>
    </v-card>

    <AssetClassSettings :token="token" />

    <DepreciationZoneSettings :token="token" />

    <Section179LimitSettings :token="token" />

    <Section280fLimitSettings :token="token" />

    <AssetIdTemplateSettings :token="token" />

    <CategorySettings :token="token" @updated="$emit('categories-updated')" />

    <DepartmentSettings :token="token" @updated="$emit('categories-updated')" />

    <PmCategorySettings :token="token" />

    <PartCategorySettings :token="token" />
    <v-card class="span-6 panel-pad">
      <h2 class="section-title mb-4">Tax rule sets</h2>
      <v-list lines="two">
        <v-list-item v-for="rule in taxRules" :key="rule.id" prepend-icon="mdi-scale-balance">
          <v-list-item-title>{{ rule.name }} · {{ rule.version }}</v-list-item-title>
          <v-list-item-subtitle>{{ rule.jurisdiction }} · {{ rule.effective_date }}</v-list-item-subtitle>
        </v-list-item>
      </v-list>
    </v-card>

    <PmSettings :token="token" />
    </template>

    <!-- INTEGRATIONS -->
    <template v-if="adminSection === 'admin-integrations'">
    <NotificationSettings :token="token" />

    <WebhookSettings :token="token" />

    <TeamsSettings :token="token" />

    <ServiceNowSettings :token="token" />

    <v-card class="span-12 panel-pad">
      <div class="toolbar-row mb-4">
        <div>
          <h2 class="section-title">Workday connector</h2>
          <div class="quiet text-body-2">Configure employee, department, and location sync from your Workday tenant.</div>
        </div>
        <v-spacer />
        <v-btn variant="tonal" prepend-icon="mdi-cloud-sync" :loading="workdaySyncing" @click="$emit('sync-workday')">Sync workers</v-btn>
      </div>
      <div class="form-grid">
        <v-text-field v-model="localWorkday.name" label="Connection name" />
        <v-text-field v-model="localWorkday.tenant" label="Tenant" />
        <v-text-field v-model="localWorkday.base_url" label="Base URL" />
        <v-text-field v-model="localWorkday.token_url" label="Token URL" />
        <v-text-field v-model="localWorkday.client_id" label="Client ID" />
        <v-text-field v-model="localWorkday.client_secret" type="password" label="Client secret" />
        <v-text-field v-model="localWorkday.workers_path" label="Workers path" />
        <v-switch v-model="localWorkday.enabled" label="Enabled" color="primary" density="compact" hide-details />
        <v-switch v-model="localWorkday.sync_enabled" label="Automatic scheduled sync" color="primary" density="compact" hide-details />
        <v-text-field v-model.number="localWorkday.sync_interval_hours" type="number" label="Sync interval (hours)" />
      </div>
      <div class="toolbar-row mt-3">
        <div class="quiet text-body-2">Last sync: {{ workdayConnection.last_sync_at ? shortDate(workdayConnection.last_sync_at) : 'Never' }}</div>
        <v-spacer />
        <v-btn color="primary" prepend-icon="mdi-content-save" :loading="workdaySaving" @click="$emit('save-workday', localWorkday)">Save Workday connection</v-btn>
      </div>
      <v-alert v-if="workdayConnection.last_sync_status" class="mt-3" density="compact" type="info">{{ workdayConnection.last_sync_status }}</v-alert>
    </v-card>
    </template>

    <v-dialog v-model="userDialog" max-width="560">
      <v-card>
        <v-card-title>{{ userForm.id ? 'Edit user' : 'Add user' }}</v-card-title>
        <v-card-text>
          <div class="form-grid">
            <v-text-field v-model="userForm.name" label="Name" />
            <v-text-field v-model="userForm.email" label="Email" />
            <v-select v-model="userForm.team_id" :items="teamOptions" item-title="title" item-value="value" clearable label="Team" />
            <v-select v-model="userForm.role" :items="roleSelectItems" item-title="title" item-value="value" label="Role" />
            <v-select v-model="userForm.status" :items="['active', 'inactive']" label="Status" />
            <v-text-field v-model="userForm.password" type="password" :label="userForm.id ? 'New password' : 'Password'" :hint="userForm.id ? 'Leave blank to keep the current password' : 'Leave blank to issue a temporary password'" persistent-hint />
          </div>
          <v-switch v-model="userForm.must_change_password" color="primary" density="compact" hide-details class="mt-2" label="Require password change at next sign-in" />
          <v-select
            v-model="userForm.company_ids"
            :items="companyItems"
            item-title="title"
            item-value="value"
            label="Company access"
            multiple
            chips
            closable-chips
            class="mt-3"
            hint="Companies this user can see and switch between. Administrators always see every company."
            persistent-hint
          />
          <v-alert v-if="userForm.role" class="mt-3" density="compact" type="info">
            {{ roleSummary(userForm.role) }}
          </v-alert>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="userDialog = false">Cancel</v-btn>
          <v-btn color="primary" prepend-icon="mdi-content-save" :loading="userSaving" @click="saveUser">Save user</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="teamDialog" max-width="460">
      <v-card>
        <v-card-title>{{ teamForm.id ? 'Edit team' : 'Add team' }}</v-card-title>
        <v-card-text>
          <v-text-field v-model="teamForm.name" label="Team name" />
          <v-textarea v-model="teamForm.description" label="Description" rows="2" />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="teamDialog = false">Cancel</v-btn>
          <v-btn color="primary" prepend-icon="mdi-content-save" :loading="teamSaving" @click="saveTeam">Save team</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </section>
</template>

<script>
import AssetClassSettings from '../components/AssetClassSettings.vue';
import AssetIdTemplateSettings from '../components/AssetIdTemplateSettings.vue';
import AppLogsSettings from '../components/AppLogsSettings.vue';
import AuditTrailSettings from '../components/AuditTrailSettings.vue';
import CategorySettings from '../components/CategorySettings.vue';
import CompanySettings from '../components/CompanySettings.vue';
import PasswordPolicySettings from '../components/PasswordPolicySettings.vue';
import DataTable from '../components/DataTable.vue';
import DepartmentSettings from '../components/DepartmentSettings.vue';
import DepreciationZoneSettings from '../components/DepreciationZoneSettings.vue';
import Section179LimitSettings from '../components/Section179LimitSettings.vue';
import Section280fLimitSettings from '../components/Section280fLimitSettings.vue';
import NotificationSettings from '../components/NotificationSettings.vue';
import PartCategorySettings from '../components/PartCategorySettings.vue';
import PmCategorySettings from '../components/PmCategorySettings.vue';
import PmSettings from '../components/PmSettings.vue';
import ServiceNowSettings from '../components/ServiceNowSettings.vue';
import TeamsSettings from '../components/TeamsSettings.vue';
import WebhookSettings from '../components/WebhookSettings.vue';

export default {
  components: { AppLogsSettings, AssetClassSettings, AssetIdTemplateSettings, AuditTrailSettings, CategorySettings, CompanySettings, DataTable, DepartmentSettings, DepreciationZoneSettings, NotificationSettings, PartCategorySettings, PasswordPolicySettings, PmCategorySettings, PmSettings, Section179LimitSettings, Section280fLimitSettings, ServiceNowSettings, TeamsSettings, WebhookSettings },
  props: {
    token: { type: String, default: '' },
    section: { type: String, default: 'admin-users' },
    capabilityCatalog: { type: Array, default: () => [] },
    roles: { type: Array, default: () => [] },
    settings: { type: Object, required: true },
    shortDate: { type: Function, default: (value) => value || '' },
    taxRules: { type: Array, required: true },
    teamSaving: { type: Boolean, default: false },
    teams: { type: Array, default: () => [] },
    teamNotice: { type: String, default: '' },
    companies: { type: Array, default: () => [] },
    userSaving: { type: Boolean, default: false },
    users: { type: Array, default: () => [] },
    workdayConnection: { type: Object, default: () => ({}) },
    workdaySaving: { type: Boolean, default: false },
    workdaySyncing: { type: Boolean, default: false }
  },
  emits: ['create-team', 'update-team', 'delete-team', 'create-user', 'update-user', 'unlock-user', 'create-role', 'update-role', 'delete-role', 'save-settings', 'save-workday', 'sync-workday', 'categories-updated', 'companies-updated'],
  data() {
    return {
      localSettings: { ...this.settings },
      localWorkday: { ...this.workdayConnection, client_secret: '' },
      teamDialog: false,
      teamForm: { id: null, name: '', description: '' },
      userDialog: false,
      userForm: this.blankUser(),
      roleDialog: false,
      roleForm: this.blankRole(),
      roleError: '',
      roleDeleteDialog: false,
      roleDeleteTarget: null,
      userColumns: [
        { key: 'name', label: 'Name' },
        { key: 'email', label: 'Email' },
        { key: 'team_name', label: 'Team' },
        { key: 'role', label: 'Role' },
        { key: 'status', label: 'Status' }
      ],
      teamColumns: [
        { key: 'name', label: 'Team' },
        { key: 'description', label: 'Description' }
      ],
      roleColumns: [
        { key: 'name', label: 'Role' },
        { key: 'capabilities', label: 'Capabilities', sortable: false },
        { key: 'user_count', label: 'Users', format: 'number' }
      ]
    };
  },
  computed: {
    teamOptions() {
      return this.teams.map((team) => ({ title: team.name, value: team.id }));
    },
    companyItems() {
      return this.companies.map((company) => ({ title: company.name, value: company.id }));
    },
    roleSelectItems() {
      return this.roles.map((role) => ({ title: role.name, value: role.key }));
    },
    capabilityGroups() {
      const groups = [];
      for (const cap of this.capabilityCatalog) {
        let group = groups.find((g) => g.name === cap.group);
        if (!group) { group = { name: cap.group, items: [] }; groups.push(group); }
        group.items.push(cap);
      }
      return groups;
    },
    adminSection() {
      return ['admin-users', 'admin-security', 'admin-audit', 'admin-logs', 'admin-config', 'admin-integrations'].includes(this.section) ? this.section : 'admin-users';
    }
  },
  watch: {
    settings: {
      handler(value) {
        this.localSettings = { ...value };
      },
      deep: true
    },
    workdayConnection: {
      handler(value) {
        this.localWorkday = { ...value, client_secret: '' };
      },
      deep: true
    }
  },
  methods: {
    blankUser() {
      return {
        id: null,
        name: '',
        email: '',
        team_id: null,
        role: 'viewer',
        status: 'active',
        password: '',
        must_change_password: false,
        company_ids: []
      };
    },
    editUser(account) {
      this.userForm = {
        id: account.id,
        name: account.name,
        email: account.email,
        team_id: account.team_id,
        role: account.role,
        status: account.status,
        password: '',
        must_change_password: Boolean(account.must_change_password),
        company_ids: Array.isArray(account.company_ids) ? [...account.company_ids] : []
      };
      this.userDialog = true;
    },
    isLocked(account) {
      return Boolean(account.locked_until && new Date(account.locked_until).getTime() > Date.now());
    },
    unlockUser(account) {
      this.$emit('unlock-user', account);
    },
    roleName(roleKey) {
      return (this.roles.find((r) => r.key === roleKey) || {}).name || roleKey;
    },
    roleSummary(roleKey) {
      const role = this.roles.find((r) => r.key === roleKey);
      if (!role) return '';
      return role.description || this.capabilitySummary(role);
    },
    capabilitySummary(role) {
      if ((role.capabilities || []).includes('*')) return 'All capabilities';
      return `${(role.capabilities || []).length} capabilit${(role.capabilities || []).length === 1 ? 'y' : 'ies'}`;
    },
    blankRole() {
      return { exists: false, locked: false, key: '', name: '', description: '', capabilities: [] };
    },
    openNewRole() {
      this.roleForm = this.blankRole();
      this.roleError = '';
      this.roleDialog = true;
    },
    openEditRole(role) {
      this.roleForm = {
        exists: true,
        locked: Boolean(role.locked),
        key: role.key,
        name: role.name,
        description: role.description || '',
        capabilities: [...(role.capabilities || [])].filter((c) => c !== '*')
      };
      this.roleError = '';
      this.roleDialog = true;
    },
    saveRole() {
      if (!this.roleForm.name.trim()) return;
      const payload = {
        key: this.roleForm.key,
        name: this.roleForm.name.trim(),
        description: this.roleForm.description,
        capabilities: this.roleForm.capabilities
      };
      this.$emit(this.roleForm.exists ? 'update-role' : 'create-role', payload);
      this.roleDialog = false;
    },
    confirmDeleteRole(role) {
      this.roleDeleteTarget = role;
      this.roleDeleteDialog = true;
    },
    performDeleteRole() {
      if (this.roleDeleteTarget) this.$emit('delete-role', this.roleDeleteTarget.key);
      this.roleDeleteDialog = false;
      this.roleDeleteTarget = null;
    },
    openNewTeam() {
      this.teamForm = { id: null, name: '', description: '' };
      this.teamDialog = true;
    },
    editTeam(team) {
      this.teamForm = { id: team.id, name: team.name, description: team.description || '' };
      this.teamDialog = true;
    },
    removeTeam(team) {
      if (window.confirm(`Delete team "${team.name}"?`)) this.$emit('delete-team', team.id);
    },
    saveTeam() {
      this.$emit(this.teamForm.id ? 'update-team' : 'create-team', { ...this.teamForm });
      this.teamDialog = false;
      this.teamForm = { id: null, name: '', description: '' };
    },
    saveUser() {
      const payload = { ...this.userForm };
      if (!payload.password) delete payload.password;
      this.$emit(payload.id ? 'update-user' : 'create-user', payload);
      this.userDialog = false;
      this.userForm = this.blankUser();
    }
  }
};
</script>

<style scoped>
.cap-group {
  margin-bottom: 12px;
}
.cap-group-title {
  font-weight: 700;
  font-size: 0.8rem;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  opacity: 0.7;
  margin: 6px 0 2px;
}
</style>
