<script>
import { onMount } from 'svelte';
  import { 
    Search, 
    FileText, 
    Printer, 
    Eye, 
    ChevronLeft,
    ChevronRight,
    AlertCircle,
    CheckCircle2,
    Clock,
    Download,
    Lock
  } from 'lucide-svelte';
  import { fetchOrders } from '$lib/api/orders.js';
  import { getReportUrl } from '$lib/api/reports.js';
  import { error as toastError } from '$lib/utils/toast.js';
  import ReportViewerModal from './ReportViewerModal.svelte';

  // State
  let orders = $state([]);
  let loading = $state(false);
  let currentPage = $state(1);
  let perPage = $state(20);
  let totalItems = $state(0);
  
  // Filters
  let filterStatus = $state('');
  let filterOrderId = $state('');
  let filterPatientId = $state('');
  
  // Modal state
  let selectedOrder = $state(null);
  let showReportModal = $state(false);
  
  // Minimum status required to view/print reports
  const MIN_REPORT_STATUS = ['VER', 'REV', 'REP'];

  const orderStatuses = [
    { value: 'ORD', label: 'Ordered', color: 'badge-neutral' },
    { value: 'SCH', label: 'Scheduled', color: 'badge-info' },
    { value: 'ANA', label: 'Analysis', color: 'badge-warning' },
    { value: 'VER', label: 'Verified', color: 'badge-success' },
    { value: 'REV', label: 'Reviewed', color: 'badge-primary' },
    { value: 'REP', label: 'Reported', color: 'badge-secondary' }
  ];

  async function loadOrders() {
    loading = true;
    try {
      const params = {
        page: currentPage,
        perPage: perPage
      };
      
      if (filterStatus) params.OrderStatus = filterStatus;
      if (filterOrderId) params.OrderID = filterOrderId;
      if (filterPatientId) params.InternalPID = filterPatientId;
      
      const response = await fetchOrders(params);
      
      if (response.status === 'success') {
        orders = response.data || [];
        totalItems = response.total || orders.length;
      } else {
        orders = [];
        totalItems = 0;
      }
    } catch (err) {
      toastError(err.message || 'Failed to load orders');
      orders = [];
    } finally {
      loading = false;
    }
  }

  function handleViewReport(order) {
    selectedOrder = order;
    showReportModal = true;
  }

  function handlePrintReport(order) {
    if (!isReportAvailable(order.OrderStatus)) {
      toastError(`Reports can only be printed for orders with status: Verified, Reviewed, or Reported. Current status: ${getStatusLabel(order.OrderStatus)}`);
      return;
    }
    
    const url = getReportUrl(order.OrderID);
    const printWindow = window.open(url, '_blank');
    if (printWindow) {
      printWindow.onload = () => {
        printWindow.print();
      };
    }
  }

  function isReportAvailable(status) {
    return MIN_REPORT_STATUS.includes(status);
  }

  function handlePageChange(newPage) {
    currentPage = newPage;
    loadOrders();
  }

  function applyFilters() {
    currentPage = 1;
    loadOrders();
  }

  function clearFilters() {
    filterStatus = '';
    filterOrderId = '';
    filterPatientId = '';
    currentPage = 1;
    loadOrders();
  }

  function getStatusBadge(status) {
    const statusConfig = orderStatuses.find(s => s.value === status);
    return statusConfig?.color || 'badge-neutral';
  }

  function getStatusLabel(status) {
    const statusConfig = orderStatuses.find(s => s.value === status);
    return statusConfig?.label || status;
  }

  onMount(() => {
    loadOrders();
  });

  const totalPages = $derived(Math.ceil(totalItems / perPage));
</script>

<div class="p-4 space-y-4">
  <!-- Header -->
  <div class="flex items-center justify-between">
    <h1 class="text-2xl font-bold text-primary flex items-center gap-2">
      <FileText class="w-6 h-6" />
      Lab Reports
    </h1>
    <div class="text-sm text-base-content/60">
      Total: {totalItems} orders
    </div>
  </div>

  <!-- Filters -->
  <div class="card bg-base-100 shadow compact-card">
    <div class="card-body p-3">
      <div class="flex flex-wrap gap-3 items-end">
        <div class="form-control w-32">
          <label class="label compact-label">
            <span class="label-text text-xs">Order ID</span>
          </label>
          <input 
            type="text" 
            class="input input-sm input-bordered"
            placeholder="Search..."
            bind:value={filterOrderId}
          />
        </div>
        
        <div class="form-control w-32">
          <label class="label compact-label">
            <span class="label-text text-xs">Patient ID</span>
          </label>
          <input 
            type="text" 
            class="input input-sm input-bordered"
            placeholder="Filter..."
            bind:value={filterPatientId}
          />
        </div>

        <div class="form-control w-36">
          <label class="label compact-label">
            <span class="label-text text-xs">Status</span>
          </label>
          <select class="select select-sm select-bordered" bind:value={filterStatus}>
            <option value="">All Statuses</option>
            {#each orderStatuses as status}
              <option value={status.value}>{status.label}</option>
            {/each}
          </select>
        </div>
        
        <div class="flex gap-2 ml-auto">
          <button class="btn btn-sm btn-primary" onclick={applyFilters}>
            <Search class="w-4 h-4" />
            Search
          </button>
          <button class="btn btn-sm btn-ghost" onclick={clearFilters}>
            Clear
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Orders Table -->
  <div class="card bg-base-100 shadow compact-card">
    <div class="card-body p-0">
      {#if loading}
        <div class="flex justify-center p-8">
          <span class="loading loading-spinner loading-md text-primary"></span>
        </div>
      {:else if orders.length === 0}
        <div class="text-center p-8 text-base-content/50">
          <FileText class="w-12 h-12 mx-auto mb-2 opacity-30" />
          <p>No orders found</p>
        </div>
      {:else}
        <div class="overflow-x-auto">
          <table class="table table-sm">
            <thead>
              <tr class="bg-base-200">
                <th class="text-xs font-semibold">Order ID</th>
                <th class="text-xs font-semibold">Patient ID</th>
                <th class="text-xs font-semibold">Visit ID</th>
                <th class="text-xs font-semibold">Status</th>
                <th class="text-xs font-semibold">Priority</th>
                <th class="text-xs font-semibold">Created</th>
                <th class="text-xs font-semibold text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {#each orders as order}
                <tr class="hover:bg-base-200/50 transition-colors">
                  <td class="text-xs font-mono font-medium">{order.OrderID}</td>
                  <td class="text-xs">{order.InternalPID || '-'}</td>
                  <td class="text-xs">{order.PatVisitID || '-'}</td>
                  <td class="text-xs">
                    <span class="badge {getStatusBadge(order.OrderStatus)} badge-sm">
                      {getStatusLabel(order.OrderStatus)}
                    </span>
                  </td>
                  <td class="text-xs">
                    {#if order.Priority === 'U'}
                      <span class="badge badge-error badge-sm">Urgent</span>
                    {:else if order.Priority === 'S'}
                      <span class="badge badge-warning badge-sm">Stat</span>
                    {:else}
                      <span class="badge badge-neutral badge-sm">Routine</span>
                    {/if}
                  </td>
                  <td class="text-xs text-base-content/60">
                    {order.CreateDate ? new Date(order.CreateDate).toLocaleDateString() : '-'}
                  </td>
                  <td class="text-right">
                    <div class="flex gap-1 justify-end">
                      <button 
                        class="btn btn-ghost btn-xs {isReportAvailable(order.OrderStatus) ? 'text-primary' : 'text-base-content/30'}" 
                        title={isReportAvailable(order.OrderStatus) ? 'View Report' : 'Report not available - Order must be Verified, Reviewed, or Reported'}
                        onclick={() => handleViewReport(order)}
                      >
                        {#if isReportAvailable(order.OrderStatus)}
                          <Eye class="w-3 h-3" />
                        {:else}
                          <Lock class="w-3 h-3" />
                        {/if}
                      </button>
                      <button 
                        class="btn btn-ghost btn-xs {isReportAvailable(order.OrderStatus) ? '' : 'text-base-content/30'}" 
                        title={isReportAvailable(order.OrderStatus) ? 'Print Report' : 'Cannot print - Order must be Verified, Reviewed, or Reported'}
                        onclick={() => handlePrintReport(order)}
                        disabled={!isReportAvailable(order.OrderStatus)}
                      >
                        <Printer class="w-3 h-3" />
                      </button>
                    </div>
                  </td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        {#if totalPages > 1}
          <div class="flex justify-center p-3 border-t border-base-200">
            <div class="join">
              <button 
                class="join-item btn btn-sm" 
                disabled={currentPage === 1}
                onclick={() => handlePageChange(currentPage - 1)}
              >
                <ChevronLeft class="w-4 h-4" />
              </button>
              <span class="join-item btn btn-sm btn-ghost">
                Page {currentPage} of {totalPages}
              </span>
              <button 
                class="join-item btn btn-sm" 
                disabled={currentPage >= totalPages}
                onclick={() => handlePageChange(currentPage + 1)}
              >
                <ChevronRight class="w-4 h-4" />
              </button>
            </div>
          </div>
        {/if}
      {/if}
    </div>
  </div>

  <!-- Status Legend -->
  <div class="card bg-base-100 shadow compact-card">
    <div class="card-body p-3">
      <h3 class="text-sm font-semibold mb-2">Order Status Pipeline</h3>
      <div class="flex flex-wrap gap-2 text-xs">
        {#each orderStatuses as status}
          <div class="flex items-center gap-1">
            <span class="badge {status.color} badge-sm">{status.label}</span>
          </div>
        {/each}
      </div>
    </div>
  </div>
</div>

<!-- Report Viewer Modal -->
{#if showReportModal && selectedOrder}
  <ReportViewerModal 
    orderId={selectedOrder.OrderID}
    orderStatus={selectedOrder.OrderStatus}
    bind:open={showReportModal}
  />
{/if}
