<script>
  import Modal from '$lib/components/Modal.svelte';
  import { getStatusInfo, getPriorityInfo, ORDER_STATUS } from '$lib/api/orders.js';
  import { User, FlaskConical, Calendar, FileText, Hash, Building2, UserCircle, Beaker, ClipboardList } from 'lucide-svelte';

  /** @type {{ 
   *   open: boolean,
   *   order: Object | null,
   *   loading: boolean,
   *   onClose: () => void
   * }} */
  let { 
    open = $bindable(false),
    order = null,
    loading = false,
    onClose
  } = $props();

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

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

  $effect(() => {
    if (!open) {
      // Reset when closed
    }
  });
</script>

<Modal 
  bind:open 
  title="Order Details" 
  size="lg"
  onClose={onClose}
>
  {#if loading}
    <div class="flex items-center justify-center py-12">
      <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>
  {:else if order}
    <div class="space-y-4">
      <!-- Order Header -->
      <div class="flex items-start justify-between p-4 bg-base-200 rounded-lg">
        <div>
          <div class="flex items-center gap-2 mb-1">
            <ClipboardList class="w-5 h-5 text-gray-500" />
            <span class="text-lg font-bold">{order.OrderID}</span>
          </div>
          <p class="text-sm text-gray-600">
            Created: {formatDate(order.OrderDate)}
          </p>
        </div>
        <div class="flex flex-col items-end gap-1">
          {#if order.OrderStatus}
            {@const status = getStatusInfo(order.OrderStatus)}
            <span class="badge badge-md {status.color}">
              {status.label}
            </span>
          {/if}
          {#if order.Priority}
            {@const priority = getPriorityInfo(order.Priority)}
            <span class="badge badge-sm {priority.color}">
              {priority.label} Priority
            </span>
          {:else}
            {@const priority = getPriorityInfo('R')}
            <span class="badge badge-sm {priority.color}">
              {priority.label} Priority
            </span>
          {/if}
        </div>
      </div>

      <!-- Patient Info -->
      {#if order.PatientID || order.InternalPID}
        <div class="border border-base-300 rounded-lg p-4">
          <h4 class="font-semibold text-sm mb-3 flex items-center gap-2">
            <User class="w-4 h-4" />
            Patient Information
          </h4>
          <div class="grid grid-cols-2 gap-3 text-sm">
            <div>
              <span class="text-gray-500">Patient ID:</span>
              <span class="ml-1 font-medium">{order.PatientID || '-'}</span>
            </div>
            <div>
              <span class="text-gray-500">Internal PID:</span>
              <span class="ml-1 font-medium">{order.InternalPID}</span>
            </div>
            {#if order.PatientName}
              <div class="col-span-2">
                <span class="text-gray-500">Name:</span>
                <span class="ml-1 font-medium">{order.PatientName}</span>
              </div>
            {/if}
          </div>
        </div>
      {/if}

      <!-- Order Details -->
      <div class="border border-base-300 rounded-lg p-4">
        <h4 class="font-semibold text-sm mb-3 flex items-center gap-2">
          <FileText class="w-4 h-4" />
          Order Information
        </h4>
        <div class="grid grid-cols-2 gap-3 text-sm">
          {#if order.PlacerID}
            <div>
              <span class="text-gray-500">Placer ID:</span>
              <span class="ml-1 font-medium">{order.PlacerID}</span>
            </div>
          {/if}
          {#if order.PatVisitID}
            <div>
              <span class="text-gray-500">Visit ID:</span>
              <span class="ml-1 font-medium">{order.PatVisitID}</span>
            </div>
          {/if}
          {#if order.SiteID}
            <div>
              <span class="text-gray-500">Site ID:</span>
              <span class="ml-1 font-medium">{order.SiteID}</span>
            </div>
          {/if}
          {#if order.ReqApp}
            <div>
              <span class="text-gray-500">Requesting App:</span>
              <span class="ml-1 font-medium">{order.ReqApp}</span>
            </div>
          {/if}
          {#if order.OrderingProvider}
            <div>
              <span class="text-gray-500">Ordering Provider:</span>
              <span class="ml-1 font-medium">{order.OrderingProvider}</span>
            </div>
          {/if}
        </div>
        
        {#if order.Comment}
          <div class="mt-3 pt-3 border-t border-base-200">
            <span class="text-gray-500 text-sm">Comment:</span>
            <p class="mt-1 text-sm">{order.Comment}</p>
          </div>
        {/if}
      </div>

      <!-- Tests -->
      {#if order.Tests && order.Tests.length > 0}
        <div class="border border-base-300 rounded-lg p-4">
          <h4 class="font-semibold text-sm mb-3 flex items-center gap-2">
            <FlaskConical class="w-4 h-4" />
            Tests ({order.Tests.length})
          </h4>
          <div class="overflow-x-auto">
            <table class="table table-compact w-full">
              <thead>
                <tr class="bg-base-200">
                  <th class="text-xs">Test Site ID</th>
                  <th class="text-xs">Test ID</th>
                  <th class="text-xs">Status</th>
                </tr>
              </thead>
              <tbody>
                {#each order.Tests as test, index (test.TestSiteID || index)}
                  {@const testStatus = getStatusInfo(test.Status || order.OrderStatus)}
                  <tr>
                    <td class="text-sm">{test.TestSiteID}</td>
                    <td class="text-sm">{test.TestID || '-'}</td>
                    <td class="text-sm">
                      <span class="badge badge-sm {testStatus.color}">
                        {testStatus.label}
                      </span>
                    </td>
                  </tr>
                {/each}
              </tbody>
            </table>
          </div>
        </div>
      {/if}

      <!-- Specimens -->
      {#if order.Specimens && order.Specimens.length > 0}
        <div class="border border-base-300 rounded-lg p-4">
          <h4 class="font-semibold text-sm mb-3 flex items-center gap-2">
            <Beaker class="w-4 h-4" />
            Specimens ({order.Specimens.length})
          </h4>
          <div class="space-y-2">
            {#each order.Specimens as specimen, index (specimen.SpecimenID || index)}
              <div class="flex items-center gap-3 p-2 bg-base-100 rounded border border-base-200">
                <Beaker class="w-4 h-4 text-gray-400" />
                <div class="flex-1">
                  <p class="text-sm font-medium">{specimen.SpecimenID || 'Specimen'}</p>
                  {#if specimen.ContainerType}
                    <p class="text-xs text-gray-500">Container: {specimen.ContainerType}</p>
                  {/if}
                </div>
                {#if specimen.CollectionDate}
                  <span class="text-xs text-gray-500">
                    {formatShortDate(specimen.CollectionDate)}
                  </span>
                {/if}
              </div>
            {/each}
          </div>
        </div>
      {/if}

      <!-- Status History (if available) -->
      {#if order.StatusHistory && order.StatusHistory.length > 0}
        <div class="border border-base-300 rounded-lg p-4">
          <h4 class="font-semibold text-sm mb-3">Status History</h4>
          <div class="space-y-2">
            {#each order.StatusHistory as history, index (history.Date || index)}
              {@const histStatus = getStatusInfo(history.Status)}
              <div class="flex items-center gap-3 text-sm">
                <span class="text-gray-500 w-24">{formatDate(history.Date)}</span>
                <span class="badge badge-sm {histStatus.color}">{histStatus.label}</span>
                {#if history.By}
                  <span class="text-gray-600">by {history.By}</span>
                {/if}
              </div>
            {/each}
          </div>
        </div>
      {/if}
    </div>
  {:else}
    <div class="text-center py-8 text-gray-500">
      <FileText class="w-12 h-12 mx-auto mb-3 opacity-50" />
      <p>No order data available</p>
    </div>
  {/if}

  {#snippet footer()}
    <button 
      class="btn btn-ghost btn-sm" 
      onclick={onClose}
    >
      Close
    </button>
  {/snippet}
</Modal>
