<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 VisitFormModal from './VisitFormModal.svelte';
  import { Calendar, Clock, MapPin, FileText, Plus, Edit2 } from 'lucide-svelte';

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

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

  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);
      console.log('Visit API response:', response);
      
      // Handle different response structures
      if (Array.isArray(response)) {
        visits = response;
      } else if (response.data && Array.isArray(response.data)) {
        visits = response.data;
      } else if (response.visits && Array.isArray(response.visits)) {
        visits = response.visits;
      } else {
        visits = [];
      }
      
      console.log('Processed visits:', visits);
    } 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();
  }

  function openCreateModal() {
    selectedVisit = null;
    visitFormOpen = true;
  }

  function openEditModal(visit) {
    selectedVisit = visit;
    visitFormOpen = true;
  }

  function handleVisitSaved() {
    loadVisits();
  }
</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 justify-between">
        <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>
        <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
          <Plus class="w-4 h-4 mr-1" />
          New Visit
        </button>
      </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.PVACreateDate || visit.PVCreateDate)}</span>
                    {#if !visit.EndDate && !visit.ArchivedDate}
                      <span class="badge badge-sm badge-success">Active</span>
                    {:else}
                      <span class="badge badge-sm badge-ghost">Closed</span>
                    {/if}
                  </div>
                  
                  <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    {#if visit.ADTCode}
                      <div>
                        <span class="text-gray-500">Type:</span>
                        <span class="ml-1">{visit.ADTCode}</span>
                      </div>
                    {/if}
                    
                    {#if visit.LocCode || visit.LocationID}
                      <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.LocCode || visit.LocationID || '-'}</span>
                      </div>
                    {/if}
                    
                    {#if visit.AttDoc || visit.AdmDoc || visit.RefDoc || visit.CnsDoc}
                      <div>
                        <span class="text-gray-500">Doctor:</span>
                        <span class="ml-1">{visit.AttDoc || visit.AdmDoc || visit.RefDoc || visit.CnsDoc || '-'}</span>
                      </div>
                    {/if}
                    
                    {#if visit.PVACreateDate || visit.PVCreateDate}
                      <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.PVACreateDate || visit.PVCreateDate)}</span>
                      </div>
                    {/if}
                  </div>

                  {#if visit.DiagCode || 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.DiagCode || visit.Diagnosis || '-'}</p>
                        </div>
                      </div>
                    </div>
                  {/if}
                  
                  <div class="mt-2 text-xs text-gray-400">
                    Visit ID: {visit.PVID || visit.InternalPVID || '-'}
                  </div>
                </div>
                <div class="flex gap-1 ml-4">
                  <button
                    class="btn btn-sm btn-ghost"
                    title="Edit"
                    onclick={() => openEditModal(visit)}
                  >
                    <Edit2 class="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  {/if}

  <VisitFormModal bind:open={visitFormOpen} {patient} visit={selectedVisit} onSave={handleVisitSaved} />

  {#snippet footer()}
    <button class="btn btn-ghost" onclick={() => (open = false)} type="button">Close</button>
  {/snippet}
</Modal>
