<template>
  <section class="content-grid">
    <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>
      <div style="overflow-x:auto">
        <table class="asset-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Team</th>
              <th>Role</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="account in users" :key="account.id">
              <td class="font-weight-bold">{{ account.name }}</td>
              <td>{{ account.email }}</td>
              <td>{{ account.team_name || 'No team' }}</td>
              <td><v-chip size="small" variant="tonal">{{ account.role }}</v-chip></td>
              <td><span :class="['status-chip', account.status === 'active' ? 'status-in_service' : 'status-disposed']">{{ account.status }}</span></td>
              <td class="text-right">
                <v-btn icon="mdi-pencil" size="small" variant="text" @click="editUser(account)" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </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="teamDialog = true">Add team</v-btn>
      </div>
      <v-list lines="two">
        <v-list-item v-for="team in teams" :key="team.id" prepend-icon="mdi-account-group">
          <v-list-item-title>{{ team.name }}</v-list-item-title>
          <v-list-item-subtitle>{{ team.description || 'No description' }}</v-list-item-subtitle>
        </v-list-item>
      </v-list>
    </v-card>

    <v-card class="span-7 panel-pad">
      <h2 class="section-title mb-4">Role permissions</h2>
      <div style="overflow-x:auto">
        <table class="asset-table">
          <thead>
            <tr>
              <th>Capability</th>
              <th v-for="role in roles" :key="role">{{ role }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="capability in roleCapabilities" :key="capability.key">
              <td>{{ capability.label }}</td>
              <td v-for="role in roles" :key="role">
                <v-icon :color="capability.roles.includes(role) ? 'success' : 'disabled'" :icon="capability.roles.includes(role) ? 'mdi-check-circle' : 'mdi-minus-circle'" size="18" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </v-card>

    <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>
    <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>
    <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 />
      </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>

    <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="roles" 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'" />
          </div>
          <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>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>
export default {
  props: {
    roleCapabilities: { type: Array, default: () => [] },
    rolePermissions: { type: Object, 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: () => [] },
    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', 'create-user', 'save-settings', 'save-workday', 'sync-workday', 'update-user'],
  data() {
    return {
      localSettings: { ...this.settings },
      localWorkday: { ...this.workdayConnection, client_secret: '' },
      teamDialog: false,
      teamForm: { name: '', description: '' },
      userDialog: false,
      userForm: this.blankUser()
    };
  },
  computed: {
    teamOptions() {
      return this.teams.map((team) => ({ title: team.name, value: team.id }));
    }
  },
  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: ''
      };
    },
    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: ''
      };
      this.userDialog = true;
    },
    roleSummary(role) {
      return (this.rolePermissions[role] || []).join(' · ');
    },
    saveTeam() {
      this.$emit('create-team', { ...this.teamForm });
      this.teamDialog = false;
      this.teamForm = { 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>
