<script>
  import { onMount } from 'svelte';
  import { 
    Filter, 
    FileText, 
    CheckCircle2,
    ChevronLeft,
    ChevronRight,
    User,
    FlaskConical,
    Edit3,
    ClipboardList
  } from 'lucide-svelte';
  import { fetchOrders, fetchOrderById, getStatusInfo, getPriorityInfo } from '$lib/api/orders.js';
  import { error as toastError, success as toastSuccess } from '$lib/utils/toast.js';
  import ResultEntryModal from './ResultEntryModal.svelte';

  // State
  let orders = $state([]);
  let loading = $state(false);
  let currentPage = $state(1);
  let perPage = $state(20);
  let totalItems = $state(0);
  
  // Filters
  let filterOrderId = $state('');
  let filterPatientId = $state('');
  let filterStatus = $state(''); // Empty = all statuses
  
  // Modal state
  let selectedOrder = $state(null);
  let showEntryModal = $state(false);
  let detailLoadingOrderId = $state('');

  async function loadOrders() {
    loading = true;
    try {
      const params = {
        page: currentPage,
        perPage: perPage
      };
      
      if (filterOrderId) params.OrderID = filterOrderId;
      if (filterPatientId) params.InternalPID = parseInt(filterPatientId);
      if (filterStatus) params.OrderStatus = filterStatus;
      
      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;
    }
  }

  async function handleEnterResults(order) {
    detailLoadingOrderId = order.OrderID;
    selectedOrder = null;
    showEntryModal = false;
    try {
      const response = await fetchOrderById(order.OrderID);
      if (response.status === 'success' && response.data) {
        selectedOrder = response.data;
        showEntryModal = true;
      } else {
        toastError('Order details unavailable');
      }
    } catch (err) {
      toastError(err.message || 'Failed to load order details');
    } finally {
      detailLoadingOrderId = '';
    }
  }

  function handleResultsSaved() {
    showEntryModal = false;
    selectedOrder = null;
    loadOrders();
    toastSuccess('Results saved successfully');
  }

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

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

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

  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">
      <FlaskConical class="w-6 h-6" />
      Results Entry
    </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-48">
          <span class="label-text text-xs mb-1">Order ID</span>
          <label class="input input-sm input-bordered flex items-center gap-2">
            <FileText class="w-3 h-3 text-gray-400" />
            <input 
              type="text" 
              id="filter-order-id"
              class="grow bg-transparent outline-none text-sm" 
              placeholder="Filter by Order ID..."
              bind:value={filterOrderId}
            />
          </label>
        </div>
        
        <div class="form-control w-40">
          <span class="label-text text-xs mb-1">Patient ID</span>
          <label class="input input-sm input-bordered flex items-center gap-2">
            <User class="w-3 h-3 text-gray-400" />
            <input 
              type="text" 
              id="filter-patient-id"
              class="grow bg-transparent outline-none text-sm" 
              placeholder="Filter..."
              bind:value={filterPatientId}
            />
          </label>
        </div>

        <div class="form-control w-40">
          <label class="label-text text-xs mb-1" for="filter-status">Status</label>
          <select 
            id="filter-status"
            class="select select-sm select-bordered"
            bind:value={filterStatus}
          >
            <option value="">All Statuses</option>
            <option value="ORD">Ordered</option>
            <option value="SCH">Scheduled</option>
            <option value="ANA">Analysis</option>
            <option value="VER">Verified</option>
          </select>
        </div>
        
        <div class="flex gap-2 ml-auto">
          <button class="btn btn-sm btn-primary" onclick={applyFilters}>
            <Filter class="w-4 h-4" />
            Apply
          </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">
          <ClipboardList 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</th>
                <th class="text-xs font-semibold">Order Date</th>
                <th class="text-xs font-semibold">Status</th>
                <th class="text-xs font-semibold">Priority</th>
                <th class="text-xs font-semibold">Tests</th>
                <th class="text-xs font-semibold text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {#each orders as order (order.OrderID)}
                {@const statusInfo = getStatusInfo(order.OrderStatus)}
                {@const priorityInfo = getPriorityInfo(order.Priority)}
                {@const hasTests = Array.isArray(order.Tests)}
                <tr class="hover:bg-base-200/50 transition-colors">
                  <td class="text-xs font-mono font-medium">{order.OrderID}</td>
                  <td class="text-xs">
                    <div class="flex flex-col">
                      <span class="font-medium">{order.PatientName || '-'}</span>
                      <span class="text-base-content/50">ID: {order.InternalPID}</span>
                    </div>
                  </td>
                  <td class="text-xs text-base-content/70">
                    {order.OrderDateTime ? new Date(order.OrderDateTime).toLocaleDateString() : '-'}
                  </td>
                  <td class="text-xs">
                    <span class="badge {statusInfo.color} badge-sm">{statusInfo.label}</span>
                  </td>
                  <td class="text-xs">
                    <span class="badge {priorityInfo.color} badge-sm">{priorityInfo.label}</span>
                  </td>
                  <td class="text-xs">
                    {#if hasTests}
                      {@const testCount = order.Tests.length}
                      {@const pendingCount = order.Tests.filter(t => !t.Result || t.Result === '').length}
                      <div class="flex items-center gap-1">
                        <span class="font-medium">{testCount}</span>
                        {#if pendingCount > 0}
                          <span class="text-warning">({pendingCount} pending)</span>
                        {:else}
                          <CheckCircle2 class="w-3 h-3 text-success" />
                        {/if}
                      </div>
                    {:else}
                      <span class="text-xs text-base-content/50">Details only</span>
                    {/if}
                  </td>
                  <td class="text-right">
                    <button 
                      class="btn btn-primary btn-sm" 
                      title="Enter Results"
                      onclick={() => handleEnterResults(order)}
                      disabled={detailLoadingOrderId === order.OrderID}
                    >
                      <Edit3 class="w-3 h-3" />
                      {#if detailLoadingOrderId === order.OrderID}
                        Loading...
                      {:else}
                        Enter Results
                      {/if}
                    </button>
                  </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>
</div>

<!-- Result Entry Modal -->
{#if showEntryModal && selectedOrder}
  <ResultEntryModal 
    order={selectedOrder}
    bind:open={showEntryModal}
    onSaved={handleResultsSaved}
  />
{/if}
