<script setup>
import { useDmsStore } from '~/stores/dms';
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';

// Define page metadata
definePageMeta({
  title: "Switch User Role",
  middleware: ["auth"],
  requiresAuth: true,
  breadcrumb: [
    {
      name: "DMS",
      path: "/dms",
    },
    {
      name: "Switch Role",
      path: "/dms/switch-roles",
    },
  ],
});

// Get the DMS store and router
const dmsStore = useDmsStore();
const router = useRouter();

// Original user backup
const originalUser = ref(null);
const currentRole = ref('');
const message = ref('');
const isLoading = ref(false);

// Get available roles from the store
const availableRoles = computed(() => {
  return dmsStore.systemRoles || [];
});

// Check current role on mount
onMounted(() => {
  // Store original user for restoration later
  originalUser.value = { ...dmsStore.currentUser };
  currentRole.value = dmsStore.currentUser.role;
});

// Get role details by ID
const getRoleById = (roleId) => {
  return availableRoles.value.find(role => role.id === roleId) || {};
};

// Switch to a specific role
const switchToRole = (roleId) => {
  if (currentRole.value === roleId) return;
  
  isLoading.value = true;
  message.value = `Switching to ${getRoleById(roleId).name} role...`;
  
  // User data based on role
  const userData = {
    superadmin: {
      id: 'superadmin1',
      name: 'Super Admin User',
      email: 'superadmin@example.com',
      role: 'superadmin',
      department: 'IT Department'
    },
    admin: {
      id: 'admin1',
      name: 'Admin User',
      email: 'admin@example.com',
      role: 'admin',
      department: 'IT Department'
    },
    user: {
      id: 'user1',
      name: 'Regular User',
      email: 'user@example.com',
      role: 'user',
      department: 'General Department'
    }
  };
  
  // Keep original fields that we don't want to change
  const originalFields = {};
  if (originalUser.value && originalUser.value.role === roleId) {
    // If switching back to the original role, use all original data
    dmsStore.currentUser = { ...originalUser.value };
  } else {
    // Otherwise use the role-specific data
    dmsStore.currentUser = {
      ...originalFields,
      ...userData[roleId]
    };
  }
  
  // Update current role display
  currentRole.value = roleId;
  
  setTimeout(() => {
    message.value = `Successfully switched to ${getRoleById(roleId).name} role!`;
    isLoading.value = false;
  }, 800);
};

// Switch back to original role
const switchToOriginal = () => {
  isLoading.value = true;
  message.value = 'Switching back to original role...';
  
  if (originalUser.value) {
    dmsStore.currentUser = { ...originalUser.value };
    currentRole.value = originalUser.value.role;
  }
  
  setTimeout(() => {
    message.value = 'Successfully switched back to original role!';
    isLoading.value = false;
  }, 800);
};

// Navigate back to DMS homepage
const goToDms = () => {
  router.push('/dms');
};
</script>

<template>
  <div class="switch-role-page">
    <LayoutsBreadcrumb />
    
    <rs-card class="h-full">
      <template #body>
        <div class="p-6">
          <h1 class="text-2xl font-semibold mb-4">Switch User Role</h1>
          
          <div class="bg-blue-50 dark:bg-blue-900/10 rounded-lg p-5 mb-6 border border-blue-200 dark:border-blue-800">
            <div class="flex items-center mb-4">
              <div class="w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center mr-4">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
              <div>
                <h2 class="text-xl font-medium text-blue-900 dark:text-blue-100">
                  Current Role: <span class="font-bold">{{ getRoleById(currentRole).name || currentRole }}</span>
                </h2>
                <p class="text-blue-700 dark:text-blue-300">
                  This tool allows you to temporarily switch your role to view the system from different perspectives
                </p>
              </div>
            </div>
            
            <!-- Animated Status Message -->
            <div v-if="message" class="mb-4 p-4 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700">
              <div class="flex items-center">
                <div v-if="isLoading" class="mr-3 h-4 w-4 rounded-full border-2 border-blue-600 border-t-transparent animate-spin"></div>
                <div v-else class="mr-3 h-4 w-4 rounded-full bg-green-500"></div>
                <p>{{ message }}</p>
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <!-- Superadmin Role Card -->
              <div class="bg-white dark:bg-gray-800 rounded-lg p-5 border border-purple-100 dark:border-purple-900/20">
                <div class="flex items-center mb-3">
                  <div class="w-8 h-8 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center mr-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-purple-600 dark:text-purple-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-9.618 5.04L12 21.012l9.618-13.028A11.955 11.955 0 0112 2.944z" />
                    </svg>
                  </div>
                  <h3 class="text-lg font-medium text-purple-600 dark:text-purple-400">Superadmin Role</h3>
                </div>
                <p class="text-gray-600 dark:text-gray-400 mb-4 text-sm h-20 overflow-auto">
                  Full system access with complete control over users, settings, and content. Ability to manage all aspects of the system including user roles and permissions.
                </p>
                <button 
                  @click="switchToRole('superadmin')" 
                  class="w-full px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-md text-sm font-medium transition-colors"
                  :disabled="currentRole === 'superadmin' || isLoading"
                  :class="{'opacity-50': currentRole === 'superadmin' || isLoading}"
                >
                  Switch to Superadmin
                </button>
              </div>
              
              <!-- Admin Role Card -->
              <div class="bg-white dark:bg-gray-800 rounded-lg p-5 border border-blue-100 dark:border-blue-900/20">
                <div class="flex items-center mb-3">
                  <div class="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center mr-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                  </div>
                  <h3 class="text-lg font-medium text-blue-600 dark:text-blue-400">Admin Role</h3>
                </div>
                <p class="text-gray-600 dark:text-gray-400 mb-4 text-sm h-20 overflow-auto">
                  Administrative access with ability to manage content, approve requests, and view performance metrics. Access to dashboards and management tools.
                </p>
                <button 
                  @click="switchToRole('admin')" 
                  class="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium transition-colors"
                  :disabled="currentRole === 'admin' || isLoading"
                  :class="{'opacity-50': currentRole === 'admin' || isLoading}"
                >
                  Switch to Admin
                </button>
              </div>
              
              <!-- User Role Card -->
              <div class="bg-white dark:bg-gray-800 rounded-lg p-5 border border-green-100 dark:border-green-900/20">
                <div class="flex items-center mb-3">
                  <div class="w-8 h-8 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center mr-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-green-600 dark:text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                    </svg>
                  </div>
                  <h3 class="text-lg font-medium text-green-600 dark:text-green-400">User Role</h3>
                </div>
                <p class="text-gray-600 dark:text-gray-400 mb-4 text-sm h-20 overflow-auto">
                  Standard user access with ability to view permitted documents, request access to restricted content, and perform basic operations within granted permissions.
                </p>
                <button 
                  @click="switchToRole('user')" 
                  class="w-full px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md text-sm font-medium transition-colors"
                  :disabled="currentRole === 'user' || isLoading"
                  :class="{'opacity-50': currentRole === 'user' || isLoading}"
                >
                  Switch to User
                </button>
              </div>
            </div>
            
            <!-- Original Role Button -->
            <div v-if="originalUser && currentRole !== originalUser.role" class="mt-4">
              <button 
                @click="switchToOriginal" 
                class="w-full px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-md text-sm font-medium transition-colors"
                :disabled="isLoading"
              >
                Restore Original Role ({{ getRoleById(originalUser.role).name || originalUser.role }})
              </button>
            </div>
          </div>
          
          <div class="mt-8 bg-yellow-50 dark:bg-yellow-900/10 rounded-lg p-5 border border-yellow-200 dark:border-yellow-800">
            <h3 class="text-lg font-medium mb-3 text-yellow-800 dark:text-yellow-400">Important Note</h3>
            <p class="text-yellow-700 dark:text-yellow-300 mb-4">
              This role switch is temporary and will reset when you refresh the page. This tool is for testing and demonstration purposes only.
            </p>
            
            <div class="mt-6 flex justify-center">
              <button 
                @click="goToDms" 
                class="px-6 py-3 bg-yellow-600 hover:bg-yellow-700 text-white rounded-md text-sm font-medium transition-colors"
              >
                Return to DMS with New Role
              </button>
            </div>
          </div>
        </div>
      </template>
    </rs-card>
  </div>
</template>

<style scoped>
.switch-role-page {
  height: calc(100vh - 64px);
}
</style> 