<script>
  import { createADT, updateADT } from '$lib/api/visits.js';
  import { fetchLocations } from '$lib/api/locations.js';
  import { fetchContacts } from '$lib/api/contacts.js';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
  import Modal from '$lib/components/Modal.svelte';
  import SelectDropdown from '$lib/components/SelectDropdown.svelte';
  import { Activity, MapPin, User, Calendar } from 'lucide-svelte';

  /** @type {{ open: boolean, visit: any | null, adt: any | null, onSave: () => void }} */
  let { open = $bindable(false), visit = null, adt = null, onSave } = $props();

  let loading = $state(false);
  let saving = $state(false);
  let locations = $state([]);
  let contacts = $state([]);
  let formErrors = $state({});

  let formData = $state({
    PVADTID: null,
    InternalPVID: '',
    ADTCode: '',
    LocationID: '',
    LocCode: '',
    AttDoc: '',
    AdmDoc: '',
    RefDoc: '',
    CnsDoc: '',
    CreateDate: '',
    EndDate: '',
  });

  const isEdit = $derived(!!adt?.PVADTID);

  const adtTypeOptions = [
    { value: 'A01', label: 'A01 - Admit' },
    { value: 'A02', label: 'A02 - Transfer' },
    { value: 'A03', label: 'A03 - Discharge' },
    { value: 'A04', label: 'A04 - Registration' },
    { value: 'A08', label: 'A08 - Update' },
  ];

  $effect(() => {
    if (open) {
      loadLocations();
      loadContacts();
      if (adt) {
        formData = {
          PVADTID: adt.PVADTID || null,
          InternalPVID: adt.InternalPVID || visit?.InternalPVID || '',
          ADTCode: adt.ADTCode || '',
          LocationID: adt.LocationID || '',
          LocCode: adt.LocCode || '',
          AttDoc: adt.AttDoc || '',
          AdmDoc: adt.AdmDoc || '',
          RefDoc: adt.RefDoc || '',
          CnsDoc: adt.CnsDoc || '',
          CreateDate: adt.CreateDate || new Date().toISOString().slice(0, 16),
          EndDate: adt.EndDate || '',
        };
      } else {
        formData = {
          PVADTID: null,
          InternalPVID: visit?.InternalPVID || '',
          ADTCode: '',
          LocationID: '',
          LocCode: '',
          AttDoc: '',
          AdmDoc: '',
          RefDoc: '',
          CnsDoc: '',
          CreateDate: new Date().toISOString().slice(0, 16),
          EndDate: '',
        };
      }
    }
  });

  async function loadLocations() {
    try {
      const response = await fetchLocations();
      locations = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      console.error('Failed to load locations:', err);
    }
  }

  async function loadContacts() {
    try {
      const response = await fetchContacts();
      contacts = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      console.error('Failed to load contacts:', err);
    }
  }

  const locationOptions = $derived(
    locations.map((l) => ({
      value: l.LocationID || l.LocCode || '',
      label: l.LocFull || l.LocCode || 'Unknown',
    }))
  );

  const doctorOptions = $derived(
    contacts.map((c) => ({
      value: c.ContactID || c.ContactCode || '',
      label: [c.NamePrefix, c.NameFirst, c.NameMiddle, c.NameLast].filter(Boolean).join(' ') || c.ContactCode || 'Unknown',
    }))
  );

  function validateForm() {
    const errors = {};
    if (!formData.ADTCode?.trim()) {
      errors.ADTCode = 'ADT type is required';
    }
    if (!formData.CreateDate) {
      errors.CreateDate = 'Date is required';
    }
    formErrors = errors;
    return Object.keys(errors).length === 0;
  }

  async function handleSubmit() {
    if (!validateForm()) return;

    saving = true;
    try {
      const payload = { ...formData };

      // Remove empty fields
      Object.keys(payload).forEach((key) => {
        if (payload[key] === '' || payload[key] === null) {
          delete payload[key];
        }
      });

      if (isEdit) {
        const adtId = payload.PVADTID || adt?.PVADTID;
        await updateADT(adtId, payload);
        toastSuccess('ADT record updated successfully');
      } else {
        await createADT(payload);
        toastSuccess('ADT record created successfully');
      }

      open = false;
      onSave?.();
    } catch (err) {
      toastError(err.message || 'Failed to save ADT record');
    } finally {
      saving = false;
    }
  }
</script>

<Modal bind:open title={isEdit ? 'Edit ADT Record' : 'New ADT Record'} size="lg">
  {#if loading}
    <div class="flex items-center justify-center py-12">
      <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>
  {:else}
    <form class="space-y-4" onsubmit={(e) => e.preventDefault()}>
      <!-- Visit Info Display -->
      {#if visit}
        <div class="p-4 bg-base-200 rounded-lg">
          <div class="flex items-center gap-2 text-sm">
            <Activity class="w-4 h-4 text-gray-500" />
            <span class="font-medium">Visit:</span>
            <span>{visit.PVID}</span>
            {#if visit.PatientID}
              <span class="text-gray-500">| Patient: {visit.PatientID}</span>
            {/if}
          </div>
        </div>
      {/if}

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <SelectDropdown
          label="ADT Type"
          name="adtCode"
          bind:value={formData.ADTCode}
          options={adtTypeOptions}
          placeholder="Select ADT type..."
          required={true}
          error={formErrors.ADTCode}
        />

        <div class="form-control">
          <label class="label" for="createDate">
            <span class="label-text font-medium">Date</span>
            <span class="label-text-alt text-error">*</span>
          </label>
          <label class="input input-sm input-bordered flex items-center gap-2 w-full focus-within:input-primary">
            <Calendar class="w-4 h-4 text-gray-400" />
            <input
              id="createDate"
              type="datetime-local"
              class="grow bg-transparent outline-none"
              class:input-error={formErrors.CreateDate}
              bind:value={formData.CreateDate}
            />
          </label>
          {#if formErrors.CreateDate}
            <span class="text-error text-sm mt-1">{formErrors.CreateDate}</span>
          {/if}
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <SelectDropdown
          label="Location"
          name="location"
          bind:value={formData.LocationID}
          options={locationOptions}
          placeholder="Select location..."
        />

        <div class="form-control">
          <label class="label" for="endDate">
            <span class="label-text font-medium">End Date</span>
          </label>
          <label class="input input-sm input-bordered flex items-center gap-2 w-full focus-within:input-primary">
            <Calendar class="w-4 h-4 text-gray-400" />
            <input
              id="endDate"
              type="datetime-local"
              class="grow bg-transparent outline-none"
              bind:value={formData.EndDate}
            />
          </label>
        </div>
      </div>

      <div class="border-t border-base-200 pt-4 mt-4">
        <h4 class="font-medium text-gray-700 mb-4 flex items-center gap-2">
          <User class="w-4 h-4" />
          Doctors
        </h4>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <SelectDropdown
            label="Attending Doctor"
            name="attDoc"
            bind:value={formData.AttDoc}
            options={doctorOptions}
            placeholder="Select attending doctor..."
          />

          <SelectDropdown
            label="Admitting Doctor"
            name="admDoc"
            bind:value={formData.AdmDoc}
            options={doctorOptions}
            placeholder="Select admitting doctor..."
          />

          <SelectDropdown
            label="Referring Doctor"
            name="refDoc"
            bind:value={formData.RefDoc}
            options={doctorOptions}
            placeholder="Select referring doctor..."
          />

          <SelectDropdown
            label="Consulting Doctor"
            name="cnsDoc"
            bind:value={formData.CnsDoc}
            options={doctorOptions}
            placeholder="Select consulting doctor..."
          />
        </div>
      </div>
    </form>
  {/if}

  {#snippet footer()}
    <div class="flex justify-end gap-2">
      <button class="btn btn-ghost btn-sm" onclick={() => (open = false)} type="button">
        Cancel
      </button>
      <button class="btn btn-primary btn-sm" onclick={handleSubmit} disabled={saving} type="button">
        {#if saving}
          <span class="loading loading-spinner loading-sm mr-2"></span>
        {/if}
        {saving ? 'Saving...' : 'Save'}
      </button>
    </div>
  {/snippet}
</Modal>
