<script>
  import { onMount } from 'svelte';
  import { fetchVisits, deleteVisit, updateVisit, createADT } from '$lib/api/visits.js';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
  import VisitSearchBar from './VisitSearchBar.svelte';
  import VisitList from './VisitList.svelte';
  import VisitFormModal from './VisitFormModal.svelte';
  import VisitADTHistoryModal from './VisitADTHistoryModal.svelte';
  import ADTFormModal from './ADTFormModal.svelte';
  import Modal from '$lib/components/Modal.svelte';
  import { Plus, LayoutGrid, List } from 'lucide-svelte';

  // Search state
  let searchFilters = $state({
    patientId: '',
    patientName: '',
    visitDate: '',
    status: '',
    location: ''
  });

  // List state
  let loading = $state(false);
  let visits = $state([]);
  let currentPage = $state(1);
  let perPage = $state(20);
  let totalItems = $state(0);
  let totalPages = $state(1);
  let viewMode = $state('table'); // 'table' | 'cards'

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

  let adtHistory = $state({
    open: false,
    visit: null,
    patientName: ''
  });

  let dischargeModal = $state({
    open: false,
    visit: null,
    dischargeDate: ''
  });

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

  let adtForm = $state({
    open: false,
    visit: null,
    adt: null
  });

  onMount(() => {
    // Don't auto-load - wait for search
    visits = [];
  });

  async function handleSearch() {
    loading = true;
    currentPage = 1;

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

      // Add filters
      if (searchFilters.patientId.trim()) {
        params.PatientID = searchFilters.patientId.trim();
      }
      if (searchFilters.patientName.trim()) {
        params.Name = searchFilters.patientName.trim();
      }
      if (searchFilters.visitDate) {
        params.VisitDate = searchFilters.visitDate;
      }
      if (searchFilters.status) {
        params.Status = searchFilters.status;
      }
      if (searchFilters.location) {
        params.Location = searchFilters.location;
      }

      const response = await fetchVisits(params);
      visits = Array.isArray(response.data) ? response.data : [];
      totalItems = response.total || visits.length;
      totalPages = Math.ceil(totalItems / perPage) || 1;
    } catch (err) {
      toastError(err.message || 'Failed to load visits');
      visits = [];
    } finally {
      loading = false;
    }
  }

  function handleClear() {
    searchFilters = {
      patientId: '',
      patientName: '',
      visitDate: '',
      status: '',
      location: ''
    };
    visits = [];
    currentPage = 1;
    totalPages = 1;
    totalItems = 0;
  }

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

  // Visit actions
  function openCreateModal() {
    visitForm = { open: true, visit: null, patient: null, loading: false };
  }

  function openEditModal(visit) {
    visitForm = { open: true, visit: visit, patient: null, loading: false };
  }

  function handleVisitSaved() {
    handleSearch();
  }

  // ADT History
  function openADTHistory(visit) {
    adtHistory = {
      open: true,
      visit: visit,
      patientName: visit.PatientName || visit.PatientID
    };
  }

  // Discharge
  function openDischargeModal(visit) {
    dischargeModal = {
      open: true,
      visit: visit,
      dischargeDate: new Date().toISOString().slice(0, 16)
    };
  }

  async function handleDischarge() {
    if (!dischargeModal.visit?.InternalPVID) return;
    
    try {
      // Update visit with EndDate
      const updatePayload = {
        InternalPVID: dischargeModal.visit.InternalPVID,
        EndDate: dischargeModal.dischargeDate,
      };
      await updateVisit(dischargeModal.visit.InternalPVID, updatePayload);
      
      // Create A03 ADT record
      try {
        const adtPayload = {
          InternalPVID: dischargeModal.visit.InternalPVID,
          ADTCode: 'A03',
          LocationID: dischargeModal.visit.LocationID,
          LocCode: dischargeModal.visit.LocCode,
          AttDoc: dischargeModal.visit.AttDoc,
          AdmDoc: dischargeModal.visit.AdmDoc,
          RefDoc: dischargeModal.visit.RefDoc,
          CnsDoc: dischargeModal.visit.CnsDoc,
        };
        await createADT(adtPayload);
      } catch (adtErr) {
        console.warn('Failed to create ADT record:', adtErr);
      }
      
      toastSuccess('Patient discharged successfully');
      dischargeModal = { open: false, visit: null, dischargeDate: '' };
      await handleSearch();
    } catch (err) {
      toastError(err.message || 'Failed to discharge patient');
    }
  }

  // Delete
  function confirmDelete(visit) {
    deleteModal = { open: true, visit };
  }

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

  // ADT Form
  function openADTForm(visit) {
    adtForm = { open: true, visit, adt: null };
  }

  function handleADTSaved() {
    handleSearch();
  }
</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">Visit Management</h1>
      <p class="text-sm text-gray-600">Manage patient visits, admissions, and transfers</p>
    </div>
    <div class="flex gap-2">
      <div class="join">
        <button 
          class="btn btn-sm join-item {viewMode === 'table' ? 'btn-active' : ''}"
          onclick={() => viewMode = 'table'}
        >
          <List class="w-4 h-4" />
        </button>
        <button 
          class="btn btn-sm join-item {viewMode === 'cards' ? 'btn-active' : ''}"
          onclick={() => viewMode = 'cards'}
        >
          <LayoutGrid class="w-4 h-4" />
        </button>
      </div>
      <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
        <Plus class="w-4 h-4 mr-1" />
        New Visit
      </button>
    </div>
  </div>

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

  <!-- Visit List -->
  <div class="flex-1 min-h-0">
    <VisitList
      {visits}
      {loading}
      {viewMode}
      {currentPage}
      {totalPages}
      {totalItems}
      {perPage}
      onPageChange={handlePageChange}
      onEditVisit={openEditModal}
      onDeleteVisit={confirmDelete}
      onViewHistory={openADTHistory}
      onDischarge={openDischargeModal}
      onAddADT={openADTForm}
    />
  </div>
</div>

<!-- Visit Form Modal -->
<VisitFormModal
  bind:open={visitForm.open}
  visit={visitForm.visit}
  patient={visitForm.patient}
  onSave={handleVisitSaved}
  loading={visitForm.loading}
/>

<!-- ADT History Modal -->
<VisitADTHistoryModal
  bind:open={adtHistory.open}
  visit={adtHistory.visit}
  patientName={adtHistory.patientName}
/>

<!-- Discharge Modal -->
<Modal bind:open={dischargeModal.open} title="Discharge Patient" size="sm">
  <div class="py-2 space-y-3">
    <p>Discharge visit <strong>{dischargeModal.visit?.PVID}</strong>?</p>
    
    <div class="form-control">
      <label class="label" for="dischargeDate">
        <span class="label-text font-medium">Discharge Date</span>
        <span class="label-text-alt text-error">*</span>
      </label>
      <input
        id="dischargeDate"
        type="datetime-local"
        class="input input-sm input-bordered w-full"
        bind:value={dischargeModal.dischargeDate}
      />
    </div>
    
    <p class="text-sm text-warning">This will set the visit End Date and create an A03 ADT record.</p>
  </div>
  {#snippet footer()}
    <button 
      class="btn btn-ghost btn-sm" 
      onclick={() => dischargeModal.open = false}
    >
      Cancel
    </button>
    <button 
      class="btn btn-warning btn-sm" 
      onclick={handleDischarge}
    >
      Discharge
    </button>
  {/snippet}
</Modal>

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

<!-- ADT Form Modal -->
<ADTFormModal
  bind:open={adtForm.open}
  visit={adtForm.visit}
  adt={adtForm.adt}
  onSave={handleADTSaved}
/>
