<script setup>
import { ref, computed, onMounted } from 'vue';
import { useDmsStore } from '~/stores/dms';
import DMSAccessApprovalDialog from '~/components/dms/dialogs/DMSAccessApprovalDialog.vue';

// Store
const dmsStore = useDmsStore();

// Props
const props = defineProps({
  showClosed: {
    type: Boolean,
    default: false
  },
  filterByUser: {
    type: String,
    default: null
  },
  maxItems: {
    type: Number,
    default: 20
  }
});

// Component state
const isLoading = ref(true);
const statusFilter = ref('all'); // all, pending, approved, rejected
const sortBy = ref('requestDate'); // requestDate, documentName, requester, deadline
const sortOrder = ref('desc'); // asc, desc
const accessRequests = ref([]);
const selectedRequest = ref(null);
const showApprovalDialog = ref(false);

// Status options
const statusOptions = [
  { id: 'all', label: 'All Requests', color: 'gray' },
  { id: 'pending', label: 'Pending', color: 'yellow' },
  { id: 'approved', label: 'Approved', color: 'green' },
  { id: 'rejected', label: 'Rejected', color: 'red' }
];

// Date formatters
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { 
    year: 'numeric', 
    month: 'short', 
    day: 'numeric'
  });
};

const formatDatetime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { 
    year: 'numeric', 
    month: 'short', 
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// Duration formatter (e.g. "2 days ago")
const formatTimeAgo = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now - date;
  const diffSec = Math.round(diffMs / 1000);
  const diffMin = Math.round(diffSec / 60);
  const diffHour = Math.round(diffMin / 60);
  const diffDay = Math.round(diffHour / 24);

  if (diffSec < 60) {
    return `${diffSec} second${diffSec !== 1 ? 's' : ''} ago`;
  } else if (diffMin < 60) {
    return `${diffMin} minute${diffMin !== 1 ? 's' : ''} ago`;
  } else if (diffHour < 24) {
    return `${diffHour} hour${diffHour !== 1 ? 's' : ''} ago`;
  } else if (diffDay < 7) {
    return `${diffDay} day${diffDay !== 1 ? 's' : ''} ago`;
  } else {
    return formatDate(dateString);
  }
};

// Calculate deadline status
const getDeadlineStatus = (request) => {
  if (!request.targetResolutionTime) return { status: 'none', text: 'No deadline' };
  if (request.status !== 'pending') return { status: 'none', text: 'Completed' };
  
  const deadline = new Date(request.targetResolutionTime);
  const now = new Date();
  const diffMs = deadline - now;
  const diffHours = diffMs / (1000 * 60 * 60);
  
  if (diffHours < 0) {
    return { 
      status: 'overdue', 
      text: `Overdue by ${Math.abs(Math.floor(diffHours / 24))} days` 
    };
  } else if (diffHours < 24) {
    return { 
      status: 'urgent', 
      text: `Due in ${Math.ceil(diffHours)} hours` 
    };
  } else {
    return { 
      status: 'normal', 
      text: `Due in ${Math.ceil(diffHours / 24)} days` 
    };
  }
};

// Computed
const filteredRequests = computed(() => {
  let result = [...accessRequests.value];
  
  // Apply status filter
  if (statusFilter.value !== 'all') {
    result = result.filter(req => req.status === statusFilter.value);
  }
  
  // Apply show closed filter
  if (!props.showClosed) {
    result = result.filter(req => req.status === 'pending');
  }
  
  // Apply user filter
  if (props.filterByUser) {
    result = result.filter(req => req.requesterId === props.filterByUser || req.approverId === props.filterByUser);
  }
  
  // Apply sorting
  result.sort((a, b) => {
    let comparison = 0;
    switch (sortBy.value) {
      case 'requestDate':
        comparison = new Date(a.requestDate) - new Date(b.requestDate);
        break;
      case 'documentName':
        comparison = a.documentName.localeCompare(b.documentName);
        break;
      case 'requester':
        comparison = a.requesterName.localeCompare(b.requesterName);
        break;
      case 'deadline':
        // Sort by deadline with null values last
        if (!a.targetResolutionTime && !b.targetResolutionTime) comparison = 0;
        else if (!a.targetResolutionTime) comparison = 1;
        else if (!b.targetResolutionTime) comparison = -1;
        else comparison = new Date(a.targetResolutionTime) - new Date(b.targetResolutionTime);
        break;
    }
    
    return sortOrder.value === 'asc' ? comparison : -comparison;
  });
  
  // Apply max items limit
  if (props.maxItems > 0) {
    result = result.slice(0, props.maxItems);
  }
  
  return result;
});

// Get status badge class
const getStatusClass = (status) => {
  switch (status) {
    case 'pending':
      return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
    case 'approved':
      return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
    case 'rejected':
      return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
    default:
      return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300';
  }
};

// Get deadline class
const getDeadlineClass = (deadlineStatus) => {
  switch (deadlineStatus) {
    case 'overdue':
      return 'text-red-600 dark:text-red-400';
    case 'urgent':
      return 'text-orange-600 dark:text-orange-400';
    case 'normal':
      return 'text-blue-600 dark:text-blue-400';
    default:
      return 'text-gray-600 dark:text-gray-400';
  }
};

// Actions
const loadAccessRequests = async () => {
  isLoading.value = true;
  try {
    // In a real implementation, this would come from an API
    // For now, use mock data from the store
    accessRequests.value = await dmsStore.getAccessRequests();
  } catch (error) {
    console.error('Failed to load access requests:', error);
  } finally {
    isLoading.value = false;
  }
};

const openApprovalDialog = (request) => {
  selectedRequest.value = request;
  showApprovalDialog.value = true;
};

const handleApprovalAction = async (result) => {
  if (!selectedRequest.value) return;
  
  if (result.action === 'approve') {
    await dmsStore.approveAccessRequest(selectedRequest.value.id, result.notes);
  } else if (result.action === 'reject') {
    await dmsStore.rejectAccessRequest(selectedRequest.value.id, result.notes);
  }
  
  // Refresh the list
  await loadAccessRequests();
  
  // Close the dialog
  showApprovalDialog.value = false;
  selectedRequest.value = null;
};

// Change sorting
const toggleSort = (field) => {
  if (sortBy.value === field) {
    // Toggle sort direction
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  } else {
    // Set new sort field and default to ascending
    sortBy.value = field;
    sortOrder.value = 'asc';
  }
};

// Lifecycle
onMounted(() => {
  loadAccessRequests();
});
</script>

<template>
  <div class="dms-approval-queue">
    <!-- Header with filters -->
    <div class="flex flex-wrap items-center justify-between mb-4 gap-3">
      <div>
        <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100">Access Requests</h2>
      </div>
      
      <div class="flex items-center space-x-2">
        <!-- Status filter -->
        <div class="inline-flex rounded-md shadow-sm">
          <button
            v-for="option in statusOptions"
            :key="option.id"
            @click="statusFilter = option.id"
            class="relative inline-flex items-center px-3 py-1.5 text-sm font-medium border transition-colors"
            :class="[
              statusFilter === option.id 
                ? `bg-${option.color}-100 border-${option.color}-300 text-${option.color}-800 dark:bg-${option.color}-900/20 dark:border-${option.color}-700 dark:text-${option.color}-300 z-10` 
                : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300',
              option.id === 'all' ? 'rounded-l-md' : '',
              option.id === 'rejected' ? 'rounded-r-md' : ''
            ]"
          >
            {{ option.label }}
          </button>
        </div>
        
        <!-- Refresh button -->
        <button 
          @click="loadAccessRequests"
          class="inline-flex items-center px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          <span class="ml-1">Refresh</span>
        </button>
      </div>
    </div>
    
    <!-- Loading state -->
    <div v-if="isLoading" class="flex items-center justify-center py-12">
      <div class="text-center">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
        <p class="text-gray-600 dark:text-gray-400">Loading access requests...</p>
      </div>
    </div>
    
    <!-- Empty state -->
    <div v-else-if="filteredRequests.length === 0" class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-8 text-center">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-gray-400 dark:text-gray-500 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
      <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-1">No access requests found</h3>
      <p class="text-gray-600 dark:text-gray-400 mb-4">There are no access requests matching your current filters.</p>
      <rs-button 
        @click="statusFilter = 'all'; loadAccessRequests()" 
        variant="secondary"
        size="sm"
      >
        View all requests
      </rs-button>
    </div>
    
    <!-- Requests table -->
    <div v-else class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
      <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
        <thead class="bg-gray-50 dark:bg-gray-900/20">
          <tr>
            <th 
              @click="toggleSort('documentName')"
              scope="col" 
              class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"
            >
              <div class="flex items-center">
                <span>Document</span>
                <svg 
                  v-if="sortBy === 'documentName'" 
                  xmlns="http://www.w3.org/2000/svg" 
                  class="ml-1 h-4 w-4" 
                  fill="none" 
                  viewBox="0 0 24 24" 
                  stroke="currentColor"
                >
                  <path 
                    stroke-linecap="round" 
                    stroke-linejoin="round" 
                    stroke-width="2" 
                    :d="sortOrder === 'asc' ? 'M5 15l7-7 7 7' : 'M19 9l-7 7-7-7'" 
                  />
                </svg>
              </div>
            </th>
            <th 
              @click="toggleSort('requester')"
              scope="col" 
              class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"
            >
              <div class="flex items-center">
                <span>Requester</span>
                <svg 
                  v-if="sortBy === 'requester'" 
                  xmlns="http://www.w3.org/2000/svg" 
                  class="ml-1 h-4 w-4" 
                  fill="none" 
                  viewBox="0 0 24 24" 
                  stroke="currentColor"
                >
                  <path 
                    stroke-linecap="round" 
                    stroke-linejoin="round" 
                    stroke-width="2" 
                    :d="sortOrder === 'asc' ? 'M5 15l7-7 7 7' : 'M19 9l-7 7-7-7'" 
                  />
                </svg>
              </div>
            </th>
            <th 
              @click="toggleSort('requestDate')"
              scope="col" 
              class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"
            >
              <div class="flex items-center">
                <span>Requested</span>
                <svg 
                  v-if="sortBy === 'requestDate'" 
                  xmlns="http://www.w3.org/2000/svg" 
                  class="ml-1 h-4 w-4" 
                  fill="none" 
                  viewBox="0 0 24 24" 
                  stroke="currentColor"
                >
                  <path 
                    stroke-linecap="round" 
                    stroke-linejoin="round" 
                    stroke-width="2" 
                    :d="sortOrder === 'asc' ? 'M5 15l7-7 7 7' : 'M19 9l-7 7-7-7'" 
                  />
                </svg>
              </div>
            </th>
            <th 
              @click="toggleSort('deadline')"
              scope="col" 
              class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"
            >
              <div class="flex items-center">
                <span>Deadline</span>
                <svg 
                  v-if="sortBy === 'deadline'" 
                  xmlns="http://www.w3.org/2000/svg" 
                  class="ml-1 h-4 w-4" 
                  fill="none" 
                  viewBox="0 0 24 24" 
                  stroke="currentColor"
                >
                  <path 
                    stroke-linecap="round" 
                    stroke-linejoin="round" 
                    stroke-width="2" 
                    :d="sortOrder === 'asc' ? 'M5 15l7-7 7 7' : 'M19 9l-7 7-7-7'" 
                  />
                </svg>
              </div>
            </th>
            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              Status
            </th>
            <th scope="col" class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              Actions
            </th>
          </tr>
        </thead>
        <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
          <tr 
            v-for="request in filteredRequests" 
            :key="request.id"
            class="hover:bg-gray-50 dark:hover:bg-gray-900/10 transition-colors"
          >
            <!-- Document -->
            <td class="px-4 py-3 whitespace-nowrap">
              <div class="flex items-center">
                <!-- Document icon based on type -->
                <span class="flex-shrink-0 h-8 w-8 rounded-md bg-blue-100 dark:bg-blue-900/20 flex items-center justify-center text-blue-600 dark:text-blue-400 mr-3">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                </span>
                <div>
                  <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                    {{ request.documentName }}
                  </div>
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ request.documentPath }}
                  </div>
                </div>
              </div>
            </td>
            
            <!-- Requester -->
            <td class="px-4 py-3 whitespace-nowrap">
              <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                {{ request.requesterName }}
              </div>
              <div class="text-xs text-gray-500 dark:text-gray-400">
                {{ request.requesterDepartment }}
              </div>
            </td>
            
            <!-- Request Date -->
            <td class="px-4 py-3 whitespace-nowrap">
              <div class="text-sm text-gray-900 dark:text-gray-100">
                {{ formatDate(request.requestDate) }}
              </div>
              <div class="text-xs text-gray-500 dark:text-gray-400">
                {{ formatTimeAgo(request.requestDate) }}
              </div>
            </td>
            
            <!-- Deadline -->
            <td class="px-4 py-3 whitespace-nowrap">
              <div 
                v-if="request.targetResolutionTime"
                class="text-sm"
                :class="getDeadlineClass(getDeadlineStatus(request).status)"
              >
                {{ formatDate(request.targetResolutionTime) }}
              </div>
              <div 
                class="text-xs"
                :class="getDeadlineClass(getDeadlineStatus(request).status)"
              >
                {{ getDeadlineStatus(request).text }}
              </div>
            </td>
            
            <!-- Status -->
            <td class="px-4 py-3 whitespace-nowrap">
              <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full" :class="getStatusClass(request.status)">
                {{ request.status.charAt(0).toUpperCase() + request.status.slice(1) }}
              </span>
            </td>
            
            <!-- Actions -->
            <td class="px-4 py-3 whitespace-nowrap text-right text-sm font-medium">
              <div class="flex justify-end space-x-2">
                <button 
                  v-if="request.status === 'pending'"
                  @click="openApprovalDialog(request)" 
                  class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-200"
                >
                  Review
                </button>
                <button
                  v-else
                  class="text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200"
                >
                  Details
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- Approval Dialog -->
    <DMSAccessApprovalDialog
      v-if="selectedRequest"
      :visible="showApprovalDialog"
      :request="selectedRequest"
      @close="showApprovalDialog = false"
      @submit="handleApprovalAction"
    />
  </div>
</template>

<style scoped>
.dms-approval-queue {
  width: 100%;
}

/* Dynamic color styles for table header hover effect */
.cursor-pointer {
  transition: background-color 0.15s ease-in-out;
}
</style> 