<template>
  <div class="permission-manager-container">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">{{ t('Role Permissions Manager') }}</h1>
      </div>
      <div class="header-right">
        <n-space>
          <n-button @click="goToUserPermissions">
            <template #icon>
              <n-icon><Icon icon="tabler:user-cog" /></n-icon>
            </template>
            {{ t('Set User Permissions') }}
          </n-button>
          <n-button type="primary" class="add-btn-brand" @click="openAddModal">
            <template #icon>
              <n-icon><Icon icon="tabler:plus" /></n-icon>
            </template>
            {{ t('Add A New Rule') }}
          </n-button>
        </n-space>
      </div>
    </div>

    <n-card class="filter-card" :bordered="false" size="small">
      <n-grid :cols="2" :x-gap="24">
        <n-gi>
          <n-form-item :label="t('Document Type')" :show-feedback="false">
            <n-select
              v-model:value="filters.pagetype"
              :options="pagetypeOptions"
              clearable
              filterable
              :filter="filterOption"
              :placeholder="t('Select Document Type')"
              @update:value="fetchPermissions"
            />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item :label="t('Role')" :show-feedback="false">
            <n-select
              v-model:value="filters.role"
              :options="roleOptions"
              clearable
              filterable
              :filter="filterOption"
              :placeholder="t('Select Role')"
              @update:value="fetchPermissions"
            />
          </n-form-item>
        </n-gi>
      </n-grid>
    </n-card>

    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
    </div>

    <div v-else-if="permissions.length > 0" class="permissions-content">
      <div class="rules-table">
        <div class="table-header">
          <div class="col-pagetype">{{ t('Document Type') }}</div>
          <div class="col-role">{{ t('Role') }}</div>
          <div class="col-level">{{ t('Level') }}</div>
          <div class="col-perms">{{ t('Permissions') }}</div>
          <div class="col-actions"></div>
        </div>
        
        <div class="table-body">
          <div v-for="(perm, index) in permissions" :key="index" class="rule-row">
            <!-- Pagetype -->
            <div class="col-pagetype">
              <span class="pagetype-text">{{ t(perm.parent) }}</span>
            </div>

            <!-- Role & Only If Creator -->
            <div class="col-role">
              <div class="role-name">{{ t(perm.role) }}</div>
              <div class="owner-option">
                <n-checkbox
                  v-model:checked="perm.if_owner"
                  :checked-value="1"
                  :unchecked-value="0"
                  size="small"
                  @update:checked="(val: any) => updatePerm(perm, 'if_owner', val)"
                >
                  <span class="owner-label">{{ t('Only If Creator') }}</span>
                </n-checkbox>
              </div>
            </div>

            <!-- Level -->
            <div class="col-level">
              <n-tag size="small" :bordered="false" type="info" round>{{ perm.permlevel }}</n-tag>
            </div>

            <!-- Permissions (Horizontal) -->
            <div class="col-perms">
              <div class="rights-flex-container">
                <div v-for="right in getVisibleRights(perm)" :key="right" class="right-checkbox-wrapper">
                  <n-checkbox
                    v-model:checked="perm[right]"
                    :checked-value="1"
                    :unchecked-value="0"
                    size="small"
                    @update:checked="(val: any) => updatePerm(perm, right, val)"
                  >
                    <span class="right-label">{{ t(right.charAt(0).toUpperCase() + right.slice(1)) }}</span>
                  </n-checkbox>
                </div>
              </div>
            </div>

            <!-- Delete -->
            <div class="col-actions">
              <n-popconfirm 
                @positive-click="removePermission(perm)"
                :positive-text="t('Yes')"
                :negative-text="t('No')"
              >
                <template #trigger>
                  <n-button quaternary circle type="error" size="small">
                    <template #icon>
                      <n-icon><Icon icon="tabler:trash" /></n-icon>
                    </template>
                  </n-button>
                </template>
                {{ t('Are you sure you want to delete') }}
              </n-popconfirm>
            </div>
          </div>
        </div>
      </div>

    </div>

    <n-empty v-else :description="t('Select Document Type or Role to start.')" style="margin-top: 64px" />

    <!-- Add New Rule Modal -->
    <n-modal v-model:show="showAddModal" preset="dialog" :title="t('Add A New Rule')" style="width: 600px;">
      <n-form :model="newRule" label-placement="left" label-width="120" style="margin-top: 16px">
        <n-form-item :label="t('Document Type')">
          <n-select 
            v-model:value="newRule.pagetype" 
            :options="pagetypeOptions" 
            clearable
            filterable 
            :filter="filterOption"
            :clear-filter-after-select="false"
          />
        </n-form-item>
        <n-form-item :label="t('Role')">
          <n-select 
            v-model:value="newRule.role" 
            :options="roleOptions" 
            clearable
            filterable 
            :filter="filterOption"
            :clear-filter-after-select="false"
          />
        </n-form-item>
        <n-form-item :label="t('Permission Level')">
          <n-input-number v-model:value="newRule.level" :min="0" :max="9" />
        </n-form-item>
        <n-form-item label=" ">
          <div class="level-help-text">{{ t('Level 0 is for page level permissions, higher levels for field level permissions.') }}</div>
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showAddModal = false">{{ t('Cancel') }}</n-button>
        <n-button type="primary" @click="addRule" :loading="adding">{{ t('Add') }}</n-button>
      </template>
    </n-modal>

    <div class="help-section">
      <h4>{{ t('Quick Help for Setting Permissions') }}:</h4>
      <ol>
        <li>{{ t('Permissions are set on Roles and Document Types (called PageTypes) by setting rights like Read, Write, Create, Delete, Submit, Cancel, Amend, Report, Import, Export, Print, Email and Set User Permissions.') }}</li>
        <li>{{ t('Permissions get applied on Users based on what Roles they are assigned.') }}</li>
        <li>{{ t('Roles can be set for users from their User page.') }} <a href="/app/user">{{ t('Setup > User') }}</a></li>
        <li>{{ t('The system provides many pre-defined roles. You can add new roles to set finer permissions.') }} <a href="/app/role">{{ t('Add a New Role') }}</a></li>
        <li>{{ t('Permissions are automatically applied to Standard Reports and searches.') }}</li>
        <li>{{ t('As a best practice, do not assign the same set of permission rule to different Roles. Instead, set multiple Roles to the same User.') }}</li>
      </ol>
      
      <hr class="divider" />
      
      <h4>{{ t('Meaning of Submit, Cancel, Amend') }}:</h4>
      <ol>
        <li>{{ t('Certain documents, like an Invoice, should not be changed once final. The final state for such documents is called Submitted. You can restrict which roles can Submit.') }}</li>
        <li>{{ t('You can change Submitted documents by cancelling them and then, amending them.') }}</li>
        <li>{{ t('When you Amend a document after Cancel and save it, it will get a new number that is a version of the old number.') }}</li>
        <li>{{ t('For example if you cancel and amend INV004 it will become a new document INV004-1. This helps you to keep track of each amendment.') }}</li>
      </ol>
      
      <hr class="divider" />
      
      <h4>{{ t('Permission Levels') }}:</h4>
      <ol>
        <li>{{ t('Permissions at level 0 are Document Level permissions, i.e. they are primary for access to the document.') }}</li>
        <li>{{ t('If a Role does not have access at Level 0, then higher levels are meaningless.') }}</li>
        <li>{{ t('Permissions at higher levels are Field Level permissions. All Fields have a Permission Level set against them and the rules defined at that permissions apply to the field. This is useful in case you want to hide or make certain field read-only for certain Roles.') }}</li>
        <li>{{ t('You can use Customize Form to set levels on fields.') }} <a href="/app/customize-form">{{ t('Setup > Customize Form') }}</a></li>
      </ol>
      
      <hr class="divider" />
      
      <h4>{{ t('User Permissions') }}:</h4>
      <ol>
        <li>{{ t('User Permissions are used to limit users to specific records.') }} <a href="/app/user-permission">{{ t('Setup > User Permissions') }}</a></li>
        <li>{{ t('Select Document Types to set which User Permissions are used to limit access.') }}</li>
        <li>{{ t('Once you have set this, the users will only be able access documents (eg. Blog Post) where the link exists (eg. Blogger).') }}</li>
        <li>{{ t('Apart from System Manager, roles with Set User Permissions right can set permissions for other users for that Document Type.') }}</li>
      </ol>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  NCard, NGrid, NGi, NFormItem, NSelect, NButton, NSpace, NIcon, NSpin,
  NCheckbox, NTag, NPopconfirm, NEmpty, NModal, NForm, NInputNumber,
  useMessage
} from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { api } from '@/shared/api/common'

const router = useRouter()
const route = useRoute()
const message = useMessage()

const loading = ref(false)
const adding = ref(false)
const showAddModal = ref(false)
const permissions = ref<any[]>([])

const filters = reactive({
  pagetype: '',
  role: ''
})

const newRule = reactive({
  pagetype: '',
  role: '',
  level: 0
})

const pagetypeOptions = ref<{ label: string; value: string }[]>([])
const roleOptions = ref<{ label: string; value: string }[]>([])

/**
 * 自定义过滤函数：同时支持原始值（value）和翻译值（label）搜索
 */
const filterOption = (pattern: string, option: { label: string; value: string }) => {
  const searchText = pattern.toLowerCase()
  return (
    option.label.toLowerCase().includes(searchText) ||
    option.value.toLowerCase().includes(searchText)
  )
}

// 权限项定义
const standardRights = ['select', 'read', 'write', 'create', 'delete', 'print', 'email', 'report', 'import', 'export', 'share']
const submittableRights = ['submit', 'cancel', 'amend']

/**
 * 根据 PageType 是否可提交动态获取显示的权限项
 */
const getVisibleRights = (perm: any) => {
  if (perm.is_submittable) {
    return [...standardRights, ...submittableRights]
  }
  return standardRights
}

const fetchMeta = async () => {
  try {
    const res = await api.call('jingrow.core.page.permission_manager.permission_manager.get_roles_and_pagetypes')
    if (res && res.message) {
      pagetypeOptions.value = res.message.pagetypes
      roleOptions.value = res.message.roles
      
      // 检查 URL 参数，如果有 role 参数，自动选择该角色
      const roleFromQuery = route.query.role as string
      if (roleFromQuery) {
        filters.role = roleFromQuery
        // 自动加载该角色的权限
        await fetchPermissions()
      }
    }
  } catch (error) {
    message.error(t('Failed to fetch options'))
  }
}

const fetchPermissions = async () => {
  if (!filters.pagetype && !filters.role) {
    permissions.value = []
    return
  }

  loading.value = true
  try {
    const res = await api.call('jingrow.core.page.permission_manager.permission_manager.get_permissions', {
      pagetype: filters.pagetype || undefined,
      role: filters.role || undefined
    })
    permissions.value = res.message || []
  } catch (error) {
    message.error(t('Failed to load permissions'))
  } finally {
    loading.value = false
  }
}

const updatePerm = async (perm: any, ptype: string, value: any) => {
  try {
    // 当 ptype 为 'if_owner' 时，v-model 已将 perm.if_owner 更新为新值，
    // 但后端 update_permission_property 需要用原始 if_owner 值定位数据库记录，
    // 因此必须传旧值（取反）
    const ifOwnerForQuery = ptype === 'if_owner' ? (value ? 0 : 1) : perm.if_owner
    await api.call('jingrow.core.page.permission_manager.permission_manager.update', {
      pagetype: perm.parent,
      role: perm.role,
      permlevel: perm.permlevel,
      ptype: ptype,
      value: value,
      if_owner: ifOwnerForQuery
    })
    // 权限更新成功，已自动生效
  } catch (error: any) {
    message.error(error.message || t('Failed to update permission'))
    fetchPermissions()
  }
}

const removePermission = async (perm: any) => {
  try {
    await api.call('jingrow.core.page.permission_manager.permission_manager.remove', {
      pagetype: perm.parent,
      role: perm.role,
      permlevel: perm.permlevel,
      if_owner: perm.if_owner
    })
    message.success(t('Permission rule removed'))
    fetchPermissions()
  } catch (error: any) {
    message.error(error.message || t('Failed to remove permission'))
  }
}

const addRule = async () => {
  if (!newRule.pagetype || !newRule.role) {
    message.warning(t('Please select both Document Type and Role'))
    return
  }

  adding.value = true
  try {
    await api.call('jingrow.core.page.permission_manager.permission_manager.add', {
      parent: newRule.pagetype,
      role: newRule.role,
      permlevel: newRule.level
    })
    message.success(t('New rule added'))
    showAddModal.value = false
    if (filters.pagetype === newRule.pagetype || filters.role === newRule.role) {
      fetchPermissions()
    } else {
      filters.pagetype = newRule.pagetype
      filters.role = ''
      fetchPermissions()
    }
  } catch (error: any) {
    message.error(error.message || t('Failed to add rule'))
  } finally {
    adding.value = false
  }
}

const openAddModal = () => {
  // 当页面类型或角色有值时，自动赋值到新规则表单
  newRule.pagetype = filters.pagetype || ''
  newRule.role = filters.role || ''
  newRule.level = 0
  showAddModal.value = true
}

const resetToStandard = async () => {
  if (!filters.pagetype) return
  
  try {
    await api.call('jingrow.core.page.permission_manager.permission_manager.reset', {
      pagetype: filters.pagetype
    })
    message.success(t('Permissions reset to standard'))
    fetchPermissions()
  } catch (error) {
    message.error(t('Failed to reset permissions'))
  }
}

const goToUserPermissions = () => {
  router.push({ name: 'PageTypeList', params: { entity: 'user-permission' } })
}

onMounted(() => {
  fetchMeta()
})
</script>

<style scoped>
.permission-manager-container {
  padding: 20px 28px;
  width: 100%;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0;
  color: #1f2937;
}

.add-btn-brand {
  background: #e6f8f0 !important;
  border: 1px solid #1fc76f !important;
  color: #0d684b !important;
}

.add-btn-brand :deep(.n-button__border),
.add-btn-brand :deep(.n-button__state-border) {
  border: none !important;
}

.add-btn-brand:hover:not(:disabled) {
  background: #dcfce7 !important;
  color: #166534 !important;
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15) !important;
}

.filter-card {
  margin-bottom: 32px;
  background: #f8fafc;
  border: 1px solid #f1f5f9;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 80px;
}

/* Rules Table Layout */
.rules-table {
  width: 100%;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  font-weight: 600;
  color: #334155;
  font-size: 14px;
  letter-spacing: 0.01em;
}

.rule-row {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f1f5f9;
  transition: background 0.2s;
  align-items: center;
}

.rule-row:nth-child(even) {
  background: #f8fafc;
}

.rule-row:nth-child(odd) {
  background: #ffffff;
}

.rule-row:hover {
  background: #f1f5f9 !important;
}

/* Column Widths */
.col-pagetype { width: 180px; flex-shrink: 0; padding-right: 16px; }
.col-role { width: 220px; flex-shrink: 0; padding-right: 16px; }
.col-level { width: 80px; flex-shrink: 0; text-align: center; padding-right: 32px; }
.col-perms { flex: 1; padding: 0 16px; min-width: 0; padding-left: 32px; }
.col-actions { width: 50px; flex-shrink: 0; text-align: right; }

.pagetype-text {
  font-weight: 600;
  color: #334155;
}

.role-name {
  font-weight: 600;
  color: #334155;
  margin-bottom: 4px;
}

.owner-option {
  margin-top: 0;
}

.owner-label {
  font-size: 12px;
  color: #64748b;
}

/* Horizontal Permissions Layout */
.rights-flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 2px;
}

.right-checkbox-wrapper {
  display: flex;
  align-items: center;
  min-width: 80px;
}

.right-label {
  font-size: 12px;
  color: #475569;
}

.level-help-text {
  font-size: 13px;
  color: #475569;
  line-height: 1.5;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
  border-left: 3px solid #1fc76f;
}

.reset-container {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}

.help-section {
  margin-top: 64px;
  padding: 24px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #f1f5f9;
}

.help-section h4 {
  font-size: 15px;
  font-weight: 700;
  color: #334155;
  margin-bottom: 16px;
  margin-top: 24px;
}

.help-section h4:first-child {
  margin-top: 0;
}

.help-section ol {
  padding-left: 20px;
  color: #64748b;
  font-size: 13px;
  margin-bottom: 0;
}

.help-section li {
  margin-bottom: 10px;
}

.help-section a {
  color: #1fc76f;
  text-decoration: none;
}

.help-section a:hover {
  text-decoration: underline;
}

.divider {
  border: none;
  border-top: 1px solid #e5e7eb;
  margin: 24px 0;
}

/* Responsive adjustments */
@media (max-width: 1200px) {
  .col-perms {
    flex-direction: column;
  }
}

/* Mobile responsive design - Best practices */
@media (max-width: 768px) {
  .permission-manager-container {
    padding: 16px 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-right {
    width: 100%;
  }
  
  .header-right :deep(.n-space) {
    width: 100%;
    justify-content: space-between;
  }
  
  .filter-card {
    margin-bottom: 24px;
  }
  
  .filter-card :deep(.n-grid) {
    grid-template-columns: 1fr !important;
    gap: 16px !important;
  }
  
  /* Mobile table layout - Individual card design */
  .rules-table {
    border: none;
    border-radius: 0;
    box-shadow: none;
    background: transparent;
  }
  
  .table-header {
    display: none;
  }
  
  .table-body {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 0;
  }
  
  /* Individual card for each permission rule */
  .rule-row {
    display: flex;
    flex-direction: column;
    padding: 20px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: 1px solid #f1f5f9;
    gap: 16px;
    align-items: stretch;
    margin-bottom: 0;
  }
  
  .rule-row:nth-child(even),
  .rule-row:nth-child(odd) {
    background: #ffffff;
  }
  
  .rule-row:hover {
    background: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
    transition: all 0.2s ease;
  }
  
  /* Mobile card sections with clear separation */
  .col-pagetype, .col-role, .col-level, .col-perms, .col-actions {
    width: 100%;
    padding: 0;
    text-align: left;
  }
  
  .col-pagetype {
    order: 1;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f1f5f9;
  }
  
  .col-role {
    order: 2;
    margin-bottom: 16px;
  }
  
  .col-level {
    order: 3;
    text-align: left;
    margin-bottom: 16px;
    padding-top: 16px;
    border-top: 1px solid #f1f5f9;
  }
  
  .col-perms {
    order: 4;
    padding: 0;
    margin-bottom: 16px;
  }
  
  .col-actions {
    order: 5;
    text-align: left;
    display: flex;
    justify-content: flex-start;
    padding-top: 16px;
    border-top: 1px solid #f1f5f9;
  }
  
  /* Mobile typography adjustments */
  .pagetype-text {
    font-size: 18px;
    font-weight: 700;
    color: #1f2937;
  }
  
  .role-name {
    font-size: 16px;
    font-weight: 600;
    color: #334155;
    margin-bottom: 8px;
  }
  
  .owner-option {
    margin-top: 0;
  }
  
  .owner-label {
    font-size: 14px;
  }
  
  /* Mobile permissions layout */
  .rights-flex-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px 8px;
  }
  
  .right-checkbox-wrapper {
    min-width: auto;
    justify-content: flex-start;
  }
  
  .right-label {
    font-size: 13px;
  }
  
  /* Action button mobile styling */
  .col-actions :deep(.n-button) {
    width: 44px;
    height: 44px;
  }
  
  /* Help section mobile adjustments */
  .help-section {
    margin-top: 40px;
    padding: 20px;
  }
  
  .help-section h4 {
    font-size: 16px;
  }
  
  .help-section ol {
    font-size: 14px;
  }
}

/* Extra small devices (phones, 480px and down) */
@media (max-width: 480px) {
  .permission-manager-container {
    padding: 12px 12px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .rule-row {
    padding: 16px 12px;
    gap: 12px;
  }
  
  .pagetype-text {
    font-size: 16px;
  }
  
  .role-name {
    font-size: 15px;
  }
  
  .rights-flex-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px 6px;
  }
  
  .right-label {
    font-size: 12px;
  }
  
  .help-section {
    padding: 16px;
  }
  
  .help-section ol {
    font-size: 13px;
  }
}
</style>
