<script>
  import { onMount } from 'svelte';
  import { Plus, Trash2, RefreshCw, FileText } from 'lucide-svelte';
  import { 
    fetchOrders, 
    fetchOrderById, 
    createOrder, 
    updateOrder, 
    deleteOrder,
    updateOrderStatus 
  } from '$lib/api/orders.js';
import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
import { printSpecimenLabel } from '$lib/utils/barcode.js';
import OrderSearchBar from './OrderSearchBar.svelte';
  import OrderList from './OrderList.svelte';
  import OrderFormModal from './OrderFormModal.svelte';
  import OrderDetailModal from './OrderDetailModal.svelte';
  import Modal from '$lib/components/Modal.svelte';

  // Search state
  let searchFilters = $state({
    orderId: '',
    patientId: '',
    orderStatus: '',
    dateFrom: '',
    dateTo: ''
  });

  // List state
  let loading = $state(false);
  let orders = $state([]);
  let currentPage = $state(1);
  let perPage = $state(20);
  let totalItems = $state(0);
  let totalPages = $state(1);

  // Modal states
  let orderForm = $state({
    open: false,
    order: null,
    loading: false
  });

  let orderDetail = $state({
    open: false,
    order: null,
    loading: false
  });

  let deleteModal = $state({
    open: false,
    order: null
  });

  let statusModal = $state({
    open: false,
    order: null,
    newStatus: ''
  });

  // Load orders on mount
  onMount(() => {
    loadOrders();
  });

  async function loadOrders() {
    loading = true;
    
    try {
      const params = { 
        page: currentPage, 
        perPage,
        include: 'details'
      };

      // Add filters
      if (searchFilters.orderId.trim()) {
        params.OrderID = searchFilters.orderId.trim();
      }
      if (searchFilters.patientId.trim()) {
        params.InternalPID = searchFilters.patientId.trim();
      }
      if (searchFilters.orderStatus) {
        params.OrderStatus = searchFilters.orderStatus;
      }

      const response = await fetchOrders(params);
      orders = Array.isArray(response.data) ? response.data : [];

      if (response.pagination) {
        totalItems = response.pagination.total || 0;
        totalPages = Math.ceil(totalItems / perPage) || 1;
      } else {
        totalItems = orders.length;
        totalPages = 1;
      }
    } catch (err) {
      toastError(err.message || 'Failed to load orders');
      orders = [];
    } finally {
      loading = false;
    }
  }

  async function handleSearch() {
    currentPage = 1;
    await loadOrders();
  }

  function handleClear() {
    searchFilters = {
      orderId: '',
      patientId: '',
      orderStatus: '',
      dateFrom: '',
      dateTo: ''
    };
    currentPage = 1;
    loadOrders();
  }

  function handlePageChange(newPage) {
    if (newPage >= 1 && newPage <= totalPages) {
      currentPage = newPage;
      loadOrders();
    }
  }

  // CRUD Operations
  function openCreateModal() {
    orderForm = { open: true, order: null, loading: false };
  }

  async function openEditModal(order) {
    orderForm = { open: true, order: null, loading: true };
    try {
      const response = await fetchOrderById(order.OrderID);
      orderForm = { 
        ...orderForm, 
        order: response.data || order, 
        loading: false 
      };
    } catch (err) {
      toastError(err.message || 'Failed to load order details');
      orderForm = { 
        ...orderForm, 
        order: order, 
        loading: false 
      };
    }
  }

  async function openViewModal(order) {
    orderDetail = { open: true, order: null, loading: true };
    try {
      const response = await fetchOrderById(order.OrderID);
      orderDetail = { 
        ...orderDetail, 
        order: response.data || order, 
        loading: false 
      };
    } catch (err) {
      toastError(err.message || 'Failed to load order details');
      orderDetail = { 
        ...orderDetail, 
        order: order, 
        loading: false 
      };
    }
  }

  async function handleSaveOrder(formData) {
    orderForm.loading = true;
    
    try {
      if (orderForm.order) {
        // Update existing order
        await updateOrder(orderForm.order.OrderID, formData);
        toastSuccess('Order updated successfully');
      } else {
        // Create new order
        await createOrder(formData);
        toastSuccess('Order created successfully');
      }
      
      orderForm = { open: false, order: null, loading: false };
      await loadOrders();
    } catch (err) {
      toastError(err.message || 'Failed to save order');
      orderForm.loading = false;
    }
  }

  function confirmDelete(order) {
    deleteModal = { open: true, order };
  }

  async function handleDelete() {
    if (!deleteModal.order?.OrderID) return;
    
    try {
      await deleteOrder(deleteModal.order.OrderID);
      toastSuccess('Order deleted successfully');
      deleteModal = { open: false, order: null };
      await loadOrders();
    } catch (err) {
      toastError(err.message || 'Failed to delete order');
    }
  }

  // Status management
  function openStatusModal(order) {
    statusModal = { 
      open: true, 
      order, 
      newStatus: order.OrderStatus 
    };
  }

  async function handleStatusUpdate() {
    if (!statusModal.order?.OrderID || !statusModal.newStatus) return;
    
    try {
      await updateOrderStatus({
        OrderID: statusModal.order.OrderID,
        OrderStatus: statusModal.newStatus
      });
      toastSuccess('Order status updated successfully');
      statusModal = { open: false, order: null, newStatus: '' };
      await loadOrders();
    } catch (err) {
      toastError(err.message || 'Failed to update order status');
    }
  }

  function handleRefresh() {
    loadOrders();
  }

  function handlePrintBarcode(order) {
    printSpecimenLabel(order);
  }
</script>

<div class="h-[calc(100vh-4rem)] flex flex-col p-4 gap-3">
  <!-- Header -->
  <div class="flex items-center justify-between">
    <div>
      <h1 class="text-2xl font-bold text-gray-800">Orders Management</h1>
      <p class="text-sm text-gray-600">Manage laboratory orders and track status</p>
    </div>
    <div class="flex gap-2">
      <button 
        class="btn btn-ghost btn-sm" 
        onclick={handleRefresh}
        disabled={loading}
      >
        <RefreshCw class="w-4 h-4 mr-1" />
        Refresh
      </button>
      <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
        <Plus class="w-4 h-4 mr-1" />
        New Order
      </button>
    </div>
  </div>

  <!-- Search Bar -->
  <OrderSearchBar
    bind:orderId={searchFilters.orderId}
    bind:patientId={searchFilters.patientId}
    bind:orderStatus={searchFilters.orderStatus}
    bind:dateFrom={searchFilters.dateFrom}
    bind:dateTo={searchFilters.dateTo}
    {loading}
    onSearch={handleSearch}
    onClear={handleClear}
  />

  <!-- Order List -->
  <div class="flex-1 min-h-0">
    <OrderList
      {orders}
      {loading}
      {currentPage}
      {totalPages}
      {totalItems}
      {perPage}
      onPageChange={handlePageChange}
      onView={openViewModal}
      onEdit={openEditModal}
      onDelete={confirmDelete}
    />
  </div>
</div>

<!-- Order Form Modal -->
<OrderFormModal
  bind:open={orderForm.open}
  order={orderForm.order}
  loading={orderForm.loading}
  onSave={handleSaveOrder}
  onCancel={() => orderForm = { open: false, order: null, loading: false }}
/>

<!-- Order Detail Modal -->
<OrderDetailModal
  bind:open={orderDetail.open}
  order={orderDetail.order}
  loading={orderDetail.loading}
  onClose={() => orderDetail = { open: false, order: null, loading: false }}
/>

<!-- Delete Confirmation Modal -->
<Modal bind:open={deleteModal.open} title="Confirm Delete" size="sm">
  <div class="py-2">
    <p>
      Delete order 
      <strong>{deleteModal.order?.OrderID}</strong>?
    </p>
    <p class="text-sm text-error mt-2">This action cannot be undone.</p>
  </div>
  {#snippet footer()}
    <button 
      class="btn btn-ghost btn-sm" 
      onclick={() => deleteModal.open = false}
    >
      Cancel
    </button>
    <button 
      class="btn btn-error btn-sm" 
      onclick={handleDelete}
    >
      <Trash2 class="w-4 h-4 mr-1" />
      Delete
    </button>
  {/snippet}
</Modal>
