<script>
  import { onMount } from 'svelte';
  import { fetchPatients, fetchPatient, deletePatient } from '$lib/api/patients.js';
  import { fetchOrders, createOrder } from '$lib/api/orders.js';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
import { printPatientWristband, printSpecimenLabel } from '$lib/utils/barcode.js';
  import PatientSearchBar from './PatientSearchBar.svelte';
  import PatientList from './PatientList.svelte';
  import OrderList from './OrderList.svelte';
  import PatientFormModal from './PatientFormModal.svelte';
  import OrderFormModal from '../orders/OrderFormModal.svelte';
  import OrderDetailModal from '../orders/OrderDetailModal.svelte';
  import Modal from '$lib/components/Modal.svelte';
  import { Plus, Edit2, Trash2 } from 'lucide-svelte';

  // Search state (only PatientID and Name are supported by API)
  let searchFilters = $state({
    patientId: '',
    patientName: ''
  });

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

  // Selected patient and orders
  let selectedPatient = $state(null);
  let orders = $state([]);
  let ordersLoading = $state(false);

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

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

  // Order form state
  let orderForm = $state({
    open: false,
    order: null,
    patient: null,
    loading: false
  });

  // View order modal state
  let viewOrderModal = $state({
    open: false,
    order: null,
    loading: false
  });

  // Load patients on mount (empty on init)
  onMount(() => {
    // Don't auto-load - wait for search
    patients = [];
  });

  async function handleSearch() {
    loading = true;
    selectedPatient = null;
    orders = [];
    currentPage = 1;

    try {
      const params = { 
        page: currentPage, 
        perPage 
      };

      // Add filters (API expects these exact parameter names)
      if (searchFilters.patientId.trim()) {
        params.PatientID = searchFilters.patientId.trim();
      }
      if (searchFilters.patientName.trim()) {
        params.Name = searchFilters.patientName.trim();
      }

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

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

  function handleClear() {
    searchFilters = {
      patientId: '',
      patientName: ''
    };
    patients = [];
    selectedPatient = null;
    orders = [];
    currentPage = 1;
    totalPages = 1;
    totalItems = 0;
  }

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

  // Load orders when patient is selected
  async function loadOrders(patient) {
    if (!patient?.InternalPID) {
      orders = [];
      return;
    }

    ordersLoading = true;
    try {
      const response = await fetchOrders({ InternalPID: patient.InternalPID });
      orders = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      toastError(err.message || 'Failed to load orders');
      orders = [];
    } finally {
      ordersLoading = false;
    }
  }

  function handleShowOrders(patient) {
    selectedPatient = patient;
    loadOrders(patient);
  }

  // Patient CRUD
  function openCreateModal() {
    patientForm = { open: true, patient: null, loading: false };
  }

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

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

  async function handleDelete() {
    if (!deleteModal.patient?.InternalPID) return;
    
    try {
      await deletePatient(deleteModal.patient.InternalPID);
      toastSuccess('Patient deleted successfully');
      deleteModal = { open: false, patient: null };
      await handleSearch();
    } catch (err) {
      toastError(err.message || 'Failed to delete patient');
    }
  }

  function handlePatientSaved() {
    handleSearch();
  }

  // Order actions
  function openCreateOrder() {
    if (!selectedPatient) {
      toastError('Please select a patient first');
      return;
    }
    orderForm = { open: true, order: null, patient: selectedPatient, loading: false };
  }

  async function handleOrderSaved(formData) {
    orderForm.loading = true;
    try {
      await createOrder(formData);
      toastSuccess('Order created successfully');
      orderForm.open = false;
      // Refresh orders list
      if (selectedPatient) {
        await loadOrders(selectedPatient);
      }
    } catch (err) {
      toastError(err.message || 'Failed to create order');
    } finally {
      orderForm.loading = false;
    }
  }

  function handleOrderCancel() {
    orderForm.open = false;
  }

  function handleViewOrder(order) {
    viewOrderModal = { open: true, order, loading: false };
  }

  function handlePrintBarcode(order) {
    printSpecimenLabel(order);
  }

  function handleRefreshOrders() {
    if (selectedPatient) {
      loadOrders(selectedPatient);
    }
  }

  function handleCloseOrderDetail() {
    viewOrderModal = { open: false, order: null, loading: false };
  }
</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">Patient Search</h1>
      <p class="text-sm text-gray-600">Search patients and manage lab orders</p>
    </div>
    <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-1" />
      Add Patient
    </button>
  </div>

  <!-- Search Bar -->
  <PatientSearchBar
    bind:patientId={searchFilters.patientId}
    bind:patientName={searchFilters.patientName}
    {loading}
    onSearch={handleSearch}
    onClear={handleClear}
  />

  <!-- Main Content -->
  <div class="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-3 min-h-0">
    <!-- Left: Patient List -->
    <div class="min-h-0">
      <div class="flex items-center justify-between mb-2">
        <h2 class="text-sm font-semibold text-gray-700">Patients</h2>
        {#if patients.length > 0}
          <span class="text-xs text-gray-500">{totalItems} found</span>
        {/if}
      </div>
      <PatientList
        {patients}
        {loading}
        {selectedPatient}
        {currentPage}
        {totalPages}
        {totalItems}
        {perPage}
        onPageChange={handlePageChange}
        onSelectPatient={handleShowOrders}
        onEditPatient={openEditModal}
      />
    </div>

    <!-- Right: Order List -->
    <div class="min-h-0">
      <div class="flex items-center justify-between mb-2">
        <h2 class="text-sm font-semibold text-gray-700">Lab Orders</h2>
        {#if selectedPatient}
          <span class="text-xs text-gray-500">{orders.length} orders</span>
        {/if}
      </div>
      <OrderList
        patient={selectedPatient}
        {orders}
        loading={ordersLoading}
        onCreateOrder={openCreateOrder}
        onViewOrder={handleViewOrder}
        onPrintBarcode={handlePrintBarcode}
        onRefresh={handleRefreshOrders}
      />
    </div>
  </div>
</div>

<!-- Patient Form Modal -->
<PatientFormModal
  bind:open={patientForm.open}
  patient={patientForm.patient}
  onSave={handlePatientSaved}
  loading={patientForm.loading}
/>

<!-- Order Form Modal -->
<OrderFormModal
  bind:open={orderForm.open}
  order={orderForm.order}
  patient={orderForm.patient}
  onSave={handleOrderSaved}
  onCancel={handleOrderCancel}
  loading={orderForm.loading}
/>

<!-- Order Detail Modal -->
<OrderDetailModal
  bind:open={viewOrderModal.open}
  order={viewOrderModal.order}
  loading={viewOrderModal.loading}
  onClose={handleCloseOrderDetail}
/>

<!-- Delete Confirmation Modal -->
<Modal bind:open={deleteModal.open} title="Confirm Delete" size="sm">
  <div class="py-2">
    <p>
      Delete patient 
      <strong>{deleteModal.patient?.PatientID}</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>
