<script>
  import Modal from '$lib/components/Modal.svelte';
  import { fetchVisitADTHistory } from '$lib/api/visits.js';
  import { Calendar, MapPin, User, Activity, ClipboardList } from 'lucide-svelte';

  let { open = $bindable(false), visit = null, patientName = '' } = $props();
  
  let adtHistory = $state([]);
  let loading = $state(false);
  let error = $state('');

  $effect(() => {
    if (open && visit) {
      loadADTHistory();
    }
  });

  async function loadADTHistory() {
    if (!visit?.InternalPVID) return;
    
    loading = true;
    error = '';
    try {
      const response = await fetchVisitADTHistory(visit.InternalPVID);
      if (Array.isArray(response)) {
        adtHistory = response;
      } else if (response.data && Array.isArray(response.data)) {
        adtHistory = response.data;
      } else {
        adtHistory = [];
      }
    } catch (err) {
      error = err.message || 'Failed to load ADT history';
      adtHistory = [];
    } finally {
      loading = false;
    }
  }

  function getADTLabel(code) {
    const labels = {
      'A01': 'Admitted',
      'A02': 'Transferred',
      'A03': 'Discharged',
      'A04': 'Registered',
      'A08': 'Updated'
    };
    return labels[code] || code;
  }

  function getADTColor(code) {
    const colors = {
      'A01': 'bg-success/20 text-success border-success/50',
      'A02': 'bg-warning/20 text-warning border-warning/50',
      'A03': 'bg-error/20 text-error border-error/50',
      'A04': 'bg-info/20 text-info border-info/50',
      'A08': 'bg-neutral/20 text-neutral border-neutral/50'
    };
    return colors[code] || 'bg-base-200 text-base-content border-base-300';
  }

  function getADTBadge(code) {
    const badges = {
      'A01': 'badge-success',
      'A02': 'badge-warning',
      'A03': 'badge-error',
      'A04': 'badge-info',
      'A08': 'badge-neutral'
    };
    return badges[code] || 'badge-ghost';
  }

  function formatDate(dateStr) {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString('en-US', {
      weekday: 'short',
      month: 'short',
      day: 'numeric',
      year: 'numeric'
    });
  }

  function formatTime(dateStr) {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  function getDoctorName(adt) {
    const names = [];
    if (adt.AttDocFirstName) names.push(`Dr. ${adt.AttDocFirstName} ${adt.AttDocLastName || ''}`.trim());
    else if (adt.AdmDocFirstName) names.push(`Dr. ${adt.AdmDocFirstName} ${adt.AdmDocLastName || ''}`.trim());
    else if (adt.RefDocFirstName) names.push(`Dr. ${adt.RefDocFirstName} ${adt.RefDocLastName || ''}`.trim());
    else if (adt.CnsDocFirstName) names.push(`Dr. ${adt.CnsDocFirstName} ${adt.CnsDocLastName || ''}`.trim());
    return names[0] || '-';
  }
</script>

<Modal bind:open title="ADT History" size="lg">
  <div class="py-2">
    {#if patientName}
      <div class="mb-4 pb-3 border-b border-base-200">
        <p class="text-sm text-gray-500">Patient</p>
        <p class="font-semibold text-lg">{patientName}</p>
        <p class="text-xs text-gray-400 mt-1">Visit ID: {visit?.PVID || visit?.InternalPVID || '-'}</p>
      </div>
    {/if}

    {#if loading}
      <div class="flex items-center justify-center py-12">
        <span class="loading loading-spinner loading-lg text-primary"></span>
      </div>
    {:else if error}
      <div class="alert alert-error">
        <span>{error}</span>
      </div>
    {:else if adtHistory.length === 0}
      <div class="text-center py-12 text-gray-500">
        <ClipboardList class="w-16 h-16 mx-auto mb-4 opacity-50" />
        <p class="text-lg">No ADT history found</p>
        <p class="text-sm">This visit has no admission/discharge/transfer records.</p>
      </div>
    {:else}
      <div class="space-y-0">
        {#each adtHistory as adt, index}
          <div class="relative flex gap-4">
            {#if index < adtHistory.length - 1}
              <div class="absolute left-6 top-12 w-0.5 h-full bg-base-300 -translate-x-1/2"></div>
            {/if}
            
            <div class="relative z-10 flex-shrink-0">
              <div class="w-12 h-12 rounded-full border-2 flex items-center justify-center {getADTColor(adt.ADTCode)}">
                <Activity class="w-5 h-5" />
              </div>
            </div>
            
            <div class="flex-1 pb-6">
              <div class="bg-base-100 border border-base-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                <div class="flex items-start justify-between gap-4">
                  <div class="flex-1">
                    <div class="flex items-center gap-2 mb-3">
                      <span class="badge {getADTBadge(adt.ADTCode)} badge-lg">
                        {getADTLabel(adt.ADTCode)}
                      </span>
                      <span class="text-xs text-gray-400">#{adt.PVADTID}</span>
                    </div>
                    
                    <div class="flex items-center gap-4 text-sm mb-3">
                      <div class="flex items-center gap-1.5 text-gray-600">
                        <Calendar class="w-4 h-4" />
                        <span class="font-medium">{formatDate(adt.CreateDate)}</span>
                      </div>
                      <div class="flex items-center gap-1.5 text-gray-500">
                        <span class="w-1 h-1 bg-gray-400 rounded-full"></span>
                        <span>{formatTime(adt.CreateDate)}</span>
                      </div>
                    </div>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                      {#if adt.LocCode || adt.LocationID}
                        <div class="flex items-center gap-2">
                          <MapPin class="w-4 h-4 text-gray-400" />
                          <span class="text-gray-500">Location:</span>
                          <span class="font-medium">{adt.LocCode || adt.LocationID || '-'}</span>
                        </div>
                      {/if}
                      
                      {#if getDoctorName(adt) !== '-'}
                        <div class="flex items-center gap-2">
                          <User class="w-4 h-4 text-gray-400" />
                          <span class="text-gray-500">Doctor:</span>
                          <span class="font-medium">{getDoctorName(adt)}</span>
                        </div>
                      {/if}
                    </div>
                  </div>
                  
                  {#if index === 0}
                    <div class="flex-shrink-0">
                      <span class="badge badge-sm badge-primary">Latest</span>
                    </div>
                  {/if}
                </div>
              </div>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  </div>
</Modal>
