<script>
  import { onMount } from 'svelte';
  import { fetchVisitsByPatient } from '$lib/api/visits.js';
  import { error as toastError } from '$lib/utils/toast.js';
  import Modal from '$lib/components/Modal.svelte';
  import { Calendar, Clock, MapPin, FileText, Plus } from 'lucide-svelte';

  /** @type {{ open: boolean, patient: any | null }} */
  let { open = $bindable(false), patient = null } = $props();

  let visits = $state([]);
  let loading = $state(false);

  onMount(() => {
    if (patient && open) {
      loadVisits();
    }
  });

  $effect(() => {
    if (open && patient) {
      loadVisits();
    }
  });

  async function loadVisits() {
    if (!patient?.InternalPID) return;
    
    loading = true;
    try {
      const response = await fetchVisitsByPatient(patient.InternalPID);
      visits = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      toastError(err.message || 'Failed to load visits');
      visits = [];
    } finally {
      loading = false;
    }
  }

  function formatDate(dateStr) {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString();
  }

  function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString();
  }
</script>

<Modal bind:open title="Patient Visits" size="xl">
  {#if patient}
    <div class="mb-4 p-4 bg-base-200 rounded-lg">
      <div class="flex items-center gap-4">
        <div>
          <h3 class="font-bold text-lg">
            {[patient.Prefix, patient.NameFirst, patient.NameMiddle, patient.NameLast].filter(Boolean).join(' ')}
          </h3>
          <p class="text-sm text-gray-600">Patient ID: {patient.PatientID}</p>
        </div>
      </div>
    </div>

    {#if loading}
      <div class="flex items-center justify-center py-12">
        <span class="loading loading-spinner loading-lg text-primary"></span>
      </div>
    {:else if visits.length === 0}
      <div class="text-center py-12 text-gray-500">
        <Calendar class="w-16 h-16 mx-auto mb-4 opacity-50" />
        <p class="text-lg">No visits found</p>
        <p class="text-sm">This patient has no visit records.</p>
      </div>
    {:else}
      <div class="space-y-4">
        {#each visits as visit}
          <div class="card bg-base-100 shadow border border-base-200 hover:shadow-md transition-shadow">
            <div class="card-body p-4">
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <div class="flex items-center gap-2 mb-2">
                    <Calendar class="w-4 h-4 text-primary" />
                    <span class="font-semibold">{formatDate(visit.AdmissionDateTime)}</span>
                    {#if visit.VisitStatus}
                      <span class="badge badge-sm {visit.VisitStatus === 'Active' ? 'badge-success' : 'badge-ghost'}">
                        {visit.VisitStatus}
                      </span>
                    {/if}
                  </div>
                  
                  <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    {#if visit.AdmissionType}
                      <div>
                        <span class="text-gray-500">Type:</span>
                        <span class="ml-1">{visit.AdmissionType}</span>
                      </div>
                    {/if}
                    
                    {#if visit.Location}
                      <div class="flex items-center gap-1">
                        <MapPin class="w-3 h-3 text-gray-400" />
                        <span class="text-gray-500">Location:</span>
                        <span class="ml-1">{visit.Location}</span>
                      </div>
                    {/if}
                    
                    {#if visit.DoctorName}
                      <div>
                        <span class="text-gray-500">Doctor:</span>
                        <span class="ml-1">{visit.DoctorName}</span>
                      </div>
                    {/if}
                    
                    {#if visit.AdmissionDateTime}
                      <div class="flex items-center gap-1">
                        <Clock class="w-3 h-3 text-gray-400" />
                        <span class="text-gray-500">Time:</span>
                        <span class="ml-1">{formatDateTime(visit.AdmissionDateTime)}</span>
                      </div>
                    {/if}
                  </div>

                  {#if visit.Diagnosis}
                    <div class="mt-3 pt-3 border-t border-base-200">
                      <div class="flex items-start gap-2">
                        <FileText class="w-4 h-4 text-gray-400 mt-0.5" />
                        <div>
                          <span class="text-gray-500 text-sm">Diagnosis:</span>
                          <p class="text-sm mt-1">{visit.Diagnosis}</p>
                        </div>
                      </div>
                    </div>
                  {/if}
                </div>
              </div>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  {/if}

  {#snippet footer()}
    <div class="flex justify-between items-center w-full">
      <button class="btn btn-primary btn-sm" onclick={() => {}} disabled>
        <Plus class="w-4 h-4 mr-1" />
        New Visit
      </button>
      <button class="btn btn-ghost" onclick={() => (open = false)} type="button">Close</button>
    </div>
  {/snippet}
</Modal>
