<script>
  import { FileText, Printer, Download, X, ExternalLink, RefreshCw, AlertTriangle, Lock } from 'lucide-svelte';
  import { getReportUrl } from '$lib/api/reports.js';
  import Modal from '$lib/components/Modal.svelte';

  let { 
    orderId = $bindable(),
    orderStatus = $bindable(''),
    open = $bindable(false)
  } = $props();

  let reportUrl = $state('');
  let loading = $state(true);
  let error = $state('');
  let retryCount = $state(0);
  const MAX_RETRIES = 3;

  // Minimum status required to view report
  const MIN_REPORT_STATUS = ['VER', 'REV', 'REP'];

  $effect(() => {
    if (open && orderId) {
      loadReport();
    }
  });

  function loadReport() {
    loading = true;
    error = '';
    
    // Validate order status
    if (!isReportAvailable()) {
      loading = false;
      return;
    }
    
    // Build report URL using config
    reportUrl = getReportUrl(orderId);
  }

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

  function getStatusLabel(status) {
    const statusMap = {
      'ORD': 'Ordered',
      'SCH': 'Scheduled', 
      'ANA': 'Analysis',
      'VER': 'Verified',
      'REV': 'Reviewed',
      'REP': 'Reported'
    };
    return statusMap[status] || status;
  }

  function handlePrint() {
    const printWindow = window.open(reportUrl, '_blank');
    if (printWindow) {
      printWindow.onload = () => {
        printWindow.print();
      };
    }
  }

  function handleOpenInNewTab() {
    window.open(reportUrl, '_blank');
  }

  function handleClose() {
    open = false;
    error = '';
    retryCount = 0;
  }

  function handleIframeLoad() {
    loading = false;
    retryCount = 0;
  }

  function handleIframeError() {
    loading = false;
    
    if (retryCount < MAX_RETRIES) {
      retryCount++;
      // Retry after a short delay
      setTimeout(() => {
        loadReport();
      }, 1000);
    } else {
      error = `Failed to load report after ${MAX_RETRIES} attempts. The order may not have results yet or the report service is unavailable.`;
    }
  }

  function handleRetry() {
    retryCount = 0;
    loadReport();
  }
</script>

<Modal bind:open={open} title="Lab Report" size="xl">
  {#snippet children()}
    <div class="flex flex-col h-[80vh]">
      <!-- Toolbar -->
      <div class="flex items-center justify-between gap-3 pb-3 border-b border-base-200 mb-3">
        <div class="flex items-center gap-2">
          <FileText class="w-5 h-5 text-primary" />
          <span class="font-semibold">Order: {orderId}</span>
          {#if orderStatus}
            <span class="badge badge-sm badge-outline">{getStatusLabel(orderStatus)}</span>
          {/if}
        </div>
        <div class="flex gap-2">
          {#if isReportAvailable()}
            <button 
              class="btn btn-sm btn-ghost" 
              onclick={handleOpenInNewTab}
              title="Open in new tab"
            >
              <ExternalLink class="w-4 h-4" />
            </button>
            <button 
              class="btn btn-sm btn-ghost" 
              onclick={handlePrint}
              title="Print report"
            >
              <Printer class="w-4 h-4" />
            </button>
          {/if}
        </div>
      </div>

      <!-- Report Content -->
      <div class="flex-1 relative bg-white rounded-lg border border-base-200 overflow-hidden">
        {#if !isReportAvailable()}
          <!-- Status Validation Error -->
          <div class="absolute inset-0 flex items-center justify-center bg-base-100 p-8">
            <div class="text-center max-w-md">
              <div class="w-16 h-16 mx-auto mb-4 rounded-full bg-warning/10 flex items-center justify-center">
                <Lock class="w-8 h-8 text-warning" />
              </div>
              <h3 class="text-lg font-semibold text-warning mb-2">Report Not Available</h3>
              <p class="text-base-content/60 mb-4">
                Reports can only be viewed for orders with status: <strong>Verified</strong>, <strong>Reviewed</strong>, or <strong>Reported</strong>.
              </p>
              <div class="flex items-center justify-center gap-2 text-sm">
                <span class="text-base-content/40">Current status:</span>
                <span class="badge badge-sm badge-error">{getStatusLabel(orderStatus)}</span>
              </div>
              <div class="mt-4 text-xs text-base-content/40">
                Status pipeline: ORD → SCH → ANA → <strong>VER</strong> → REV → REP
              </div>
            </div>
          </div>
        {:else if loading}
          <div class="absolute inset-0 flex items-center justify-center bg-base-100">
            <div class="text-center">
              <span class="loading loading-spinner loading-lg text-primary mb-4"></span>
              <p class="text-base-content/60">Loading report...</p>
              {#if retryCount > 0}
                <p class="text-xs text-base-content/40 mt-2">Retry attempt {retryCount}/{MAX_RETRIES}...</p>
              {/if}
            </div>
          </div>
        {:else if error}
          <div class="absolute inset-0 flex items-center justify-center bg-base-100 p-8">
            <div class="text-center max-w-md">
              <div class="w-16 h-16 mx-auto mb-4 rounded-full bg-error/10 flex items-center justify-center">
                <AlertTriangle class="w-8 h-8 text-error" />
              </div>
              <h3 class="text-lg font-semibold text-error mb-2">Report Error</h3>
              <p class="text-base-content/60 mb-4">{error}</p>
              <div class="flex gap-2 justify-center">
                <button class="btn btn-primary btn-sm" onclick={handleRetry}>
                  <RefreshCw class="w-4 h-4" />
                  Retry
                </button>
                <button class="btn btn-ghost btn-sm" onclick={handleOpenInNewTab}>
                  <ExternalLink class="w-4 h-4" />
                  Open in New Tab
                </button>
              </div>
            </div>
          </div>
        {:else}
          <iframe
            src={reportUrl}
            class="w-full h-full border-0"
            title="Lab Report"
            onload={handleIframeLoad}
            onerror={handleIframeError}
            sandbox="allow-same-origin allow-scripts"
          ></iframe>
        {/if}
      </div>
    </div>
  {/snippet}

  {#snippet footer()}
    <button class="btn btn-ghost btn-sm" onclick={handleClose}>
      <X class="w-4 h-4" />
      Close
    </button>
    {#if isReportAvailable()}
      <button class="btn btn-primary btn-sm" onclick={handlePrint}>
        <Printer class="w-4 h-4" />
        Print Report
      </button>
    {:else}
      <button class="btn btn-sm btn-disabled" disabled>
        <Lock class="w-4 h-4" />
        Not Available
      </button>
    {/if}
  {/snippet}
</Modal>
