<script>
  import { Edit2, Trash2, Eye, ChevronLeft, ChevronRight, FileText, AlertTriangle, CheckCircle2, FlaskConical } from 'lucide-svelte';
  import DataTable from '$lib/components/DataTable.svelte';
  import { getStatusInfo, getPriorityInfo } from '$lib/api/orders.js';

  /**
   * @typedef {Object} Order
   * @property {string} OrderID
   * @property {string} [OrderNumber]
   * @property {number} InternalPID
   * @property {string} [PatientID]
   * @property {string} [PatientName]
   * @property {string} OrderStatus
   * @property {string} [Priority]
   * @property {string} [OrderDate]
   * @property {string} [OrderingProvider]
   * @property {Array} [Specimens]
   * @property {Array} [Tests]
   */

  /** @type {{ 
   *   orders: Order[], 
   *   loading: boolean,
   *   currentPage: number,
   *   totalPages: number,
   *   totalItems: number,
   *   perPage: number,
   *   onPageChange: (page: number) => void,
   *   onView: (order: Order) => void,
   *   onEdit: (order: Order) => void,
   *   onDelete: (order: Order) => void
   * }} */
  let { 
    orders = [], 
    loading = false,
    currentPage = 1,
    totalPages = 1,
    totalItems = 0,
    perPage = 20,
    onPageChange,
    onView,
    onEdit,
    onDelete
  } = $props();

  const columns = [
    { key: 'OrderID', label: 'Order ID', class: 'w-32' },
    { key: 'PatientID', label: 'Patient ID', class: 'w-28' },
    { key: 'PatientName', label: 'Patient Name', class: 'w-40' },
    { key: 'OrderStatus', label: 'Status', class: 'w-28' },
    { key: 'Priority', label: 'Priority', class: 'w-24' },
    { key: 'Results', label: 'Results', class: 'w-32' },
    { key: 'OrderDate', label: 'Order Date', class: 'w-28' },
    { key: 'OrderingProvider', label: 'Provider', class: 'w-28' },
    { key: 'actions', label: 'Actions', class: 'w-24 text-center' }
  ];

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

  function calculateResultSummary(tests) {
    if (!tests || tests.length === 0) {
      return { total: 0, pending: 0, abnormal: 0, complete: false };
    }
    
    const total = tests.length;
    const pending = tests.filter(t => !t.Result || t.Result === '').length;
    const abnormal = tests.filter(t => {
      if (!t.Result || !t.Low || !t.High) return false;
      const val = parseFloat(t.Result);
      return !isNaN(val) && (val < t.Low || val > t.High);
    }).length;
    
    return {
      total,
      pending,
      abnormal,
      complete: pending === 0
    };
  }

  function handlePreviousPage() {
    if (currentPage > 1) {
      onPageChange(currentPage - 1);
    }
  }

  function handleNextPage() {
    if (currentPage < totalPages) {
      onPageChange(currentPage + 1);
    }
  }
</script>

<div class="bg-base-100 rounded-lg shadow border border-base-200 flex flex-col h-full overflow-hidden">
  <!-- Table Container -->
  <div class="flex-1 overflow-auto">
    <DataTable
      {columns}
      data={orders}
      {loading}
      emptyMessage="No orders found. Use the search filters above to find orders."
      striped={true}
      hover={true}
    >
      {#snippet cell({ column, row, value })}
        {#if column.key === 'OrderStatus'}
          {@const status = getStatusInfo(value)}
          <span class="badge badge-sm {status.color}">
            {status.label}
          </span>
        {:else if column.key === 'Priority'}
          {@const priority = getPriorityInfo(value || 'R')}
          <span class="badge badge-sm {priority.color}">
            {priority.label}
          </span>
        {:else if column.key === 'OrderDate'}
          {formatDate(value)}
        {:else if column.key === 'PatientName'}
          <span class="truncate block max-w-[150px]" title={value}>
            {value || '-'}
          </span>
        {:else if column.key === 'OrderingProvider'}
          <span class="truncate block max-w-[120px]" title={value}>
            {value || '-'}
          </span>
        {:else if column.key === 'Results'}
          {@const summary = calculateResultSummary(row.Tests)}
          <div class="flex items-center gap-2">
            <FlaskConical class="w-3.5 h-3.5 text-base-content/40" />
            <span class="text-xs">
              {#if summary.total === 0}
                <span class="text-base-content/40">No tests</span>
              {:else if summary.complete}
                <span class="text-success flex items-center gap-1">
                  <CheckCircle2 class="w-3 h-3" />
                  {summary.total} complete
                  {#if summary.abnormal > 0}
                    <span class="text-error">({summary.abnormal} abnormal)</span>
                  {/if}
                </span>
              {:else}
                <span class="text-warning">
                  {summary.total - summary.pending}/{summary.total} done
                  {#if summary.abnormal > 0}
                    <span class="text-error">({summary.abnormal} abnormal)</span>
                  {/if}
                </span>
              {/if}
            </span>
          </div>
        {:else if column.key === 'actions'}
          <div class="flex items-center justify-center gap-1">
            <button 
              class="btn btn-ghost btn-xs btn-square" 
              title="View details"
              onclick={() => onView(row)}
            >
              <Eye class="w-3.5 h-3.5" />
            </button>
            <button 
              class="btn btn-ghost btn-xs btn-square" 
              title="Edit order"
              onclick={() => onEdit(row)}
            >
              <Edit2 class="w-3.5 h-3.5" />
            </button>
            <button 
              class="btn btn-ghost btn-xs btn-square text-error hover:bg-error/10" 
              title="Delete order"
              onclick={() => onDelete(row)}
            >
              <Trash2 class="w-3.5 h-3.5" />
            </button>
          </div>
        {:else}
          <span class="truncate block max-w-[150px]" title={value}>
            {value || '-'}
          </span>
        {/if}
      {/snippet}
    </DataTable>
  </div>

  <!-- Pagination -->
  {#if totalItems > 0}
    <div class="border-t border-base-200 p-3 flex items-center justify-between bg-base-100">
      <div class="text-sm text-gray-600">
        Showing <span class="font-semibold">{(currentPage - 1) * perPage + 1}</span> - 
        <span class="font-semibold">{Math.min(currentPage * perPage, totalItems)}</span> of 
        <span class="font-semibold">{totalItems}</span> orders
      </div>
      
      <div class="flex items-center gap-2">
        <button 
          class="btn btn-sm btn-ghost btn-square"
          onclick={handlePreviousPage}
          disabled={currentPage <= 1 || loading}
        >
          <ChevronLeft class="w-4 h-4" />
        </button>
        
        <span class="text-sm text-gray-600 min-w-[80px] text-center">
          Page {currentPage} of {totalPages}
        </span>
        
        <button 
          class="btn btn-sm btn-ghost btn-square"
          onclick={handleNextPage}
          disabled={currentPage >= totalPages || loading}
        >
          <ChevronRight class="w-4 h-4" />
        </button>
      </div>
    </div>
  {/if}
</div>
