<script>
  import Modal from '$lib/components/Modal.svelte';
  import { Beaker, Hash, Calendar, User, FileText, FlaskConical } from 'lucide-svelte';
  import { onMount } from 'svelte';
  import { fetchSpecimenTypes } from '$lib/api/specimens.js';

  /** @type {{ 
   *   open: boolean,
   *   specimen: Object | null,
   *   loading: boolean,
   *   onSave: (data: Object) => void,
   *   onCancel: () => void
   * }} */
  let { 
    open = $bindable(false),
    specimen = null,
    loading = false,
    onSave,
    onCancel
  } = $props();

  // Form state
  let formData = $state({
    SpecimenID: '',
    SpecimenType: '',
    OrderID: '',
    Status: 'COLLECTED',
    CollectionDate: '',
    CollectedBy: '',
    ContainerType: '',
    Volume: '',
    Units: '',
    Comment: ''
  });

  let formLoading = $state(false);
  let formError = $state('');
  let specimenTypes = $state([]);
  let typesLoading = $state(false);

  const statusOptions = [
    { value: 'COLLECTED', label: 'Collected' },
    { value: 'RECEIVED', label: 'Received' },
    { value: 'PROCESSING', label: 'Processing' },
    { value: 'COMPLETED', label: 'Completed' },
    { value: 'REJECTED', label: 'Rejected' }
  ];

  // Load specimen types on mount
  onMount(async () => {
    await loadSpecimenTypes();
  });

  async function loadSpecimenTypes() {
    typesLoading = true;
    try {
      const response = await fetchSpecimenTypes();
      specimenTypes = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      console.error('Failed to load specimen types:', err);
      specimenTypes = [];
    } finally {
      typesLoading = false;
    }
  }

  // Reset form when modal opens
  $effect(() => {
    if (open) {
      if (specimen) {
        // Edit mode - populate form
        formData = {
          SpecimenID: specimen.SpecimenID || '',
          SpecimenType: specimen.SpecimenType || '',
          OrderID: specimen.OrderID || '',
          Status: specimen.Status || 'COLLECTED',
          CollectionDate: specimen.CollectionDate 
            ? new Date(specimen.CollectionDate).toISOString().slice(0, 16)
            : '',
          CollectedBy: specimen.CollectedBy || '',
          ContainerType: specimen.ContainerType || '',
          Volume: specimen.Volume || '',
          Units: specimen.Units || '',
          Comment: specimen.Comment || ''
        };
      } else {
        // Create mode - reset form
        formData = {
          SpecimenID: '',
          SpecimenType: '',
          OrderID: '',
          Status: 'COLLECTED',
          CollectionDate: new Date().toISOString().slice(0, 16),
          CollectedBy: '',
          ContainerType: '',
          Volume: '',
          Units: '',
          Comment: ''
        };
      }
      formError = '';
    }
  });

  function validateForm() {
    formError = '';
    
    if (!formData.SpecimenID?.trim()) {
      formError = 'Specimen ID is required';
      return false;
    }
    if (!formData.SpecimenType?.trim()) {
      formError = 'Specimen type is required';
      return false;
    }
    
    return true;
  }

  function handleSubmit() {
    if (!validateForm()) return;
    
    formLoading = true;
    
    // Prepare data for submission
    const submitData = {
      ...formData,
      CollectionDate: formData.CollectionDate 
        ? new Date(formData.CollectionDate).toISOString()
        : null
    };
    
    onSave?.(submitData);
    formLoading = false;
  }

  function handleClose() {
    formError = '';
    onCancel?.();
  }
</script>

<Modal 
  bind:open 
  title={specimen ? 'Edit Specimen' : 'New Specimen'} 
  size="lg"
  onClose={handleClose}
>
  <div class="space-y-4">
    {#if formError}
      <div class="alert alert-error alert-sm">
        <span>{formError}</span>
      </div>
    {/if}

    <div class="grid grid-cols-2 gap-4">
      <!-- Specimen ID -->
      <label class="form-control">
        <span class="label-text text-sm">
          Specimen ID <span class="text-error">*</span>
        </span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Hash class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Enter specimen ID..."
            bind:value={formData.SpecimenID}
            disabled={!!specimen}
          />
        </label>
      </label>

      <!-- Specimen Type -->
      <label class="form-control">
        <span class="label-text text-sm">
          Specimen Type <span class="text-error">*</span>
        </span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Beaker class="w-4 h-4 text-gray-400" />
          <select 
            class="grow bg-transparent outline-none"
            bind:value={formData.SpecimenType}
            disabled={typesLoading}
          >
            <option value="">Select type...</option>
            {#each specimenTypes as type}
              <option value={type.SpecimenType}>{type.Description || type.SpecimenType}</option>
            {/each}
          </select>
        </label>
        {#if typesLoading}
          <span class="label-text-alt">Loading types...</span>
        {/if}
      </label>

      <!-- Order ID -->
      <label class="form-control">
        <span class="label-text text-sm">Order ID</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <FileText class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Associated order..."
            bind:value={formData.OrderID}
          />
        </label>
      </label>

      <!-- Status -->
      <label class="form-control">
        <span class="label-text text-sm">Status</span>
        <select 
          class="select select-sm select-bordered mt-1 w-full"
          bind:value={formData.Status}
        >
          {#each statusOptions as option}
            <option value={option.value}>{option.label}</option>
          {/each}
        </select>
      </label>

      <!-- Collection Date -->
      <label class="form-control">
        <span class="label-text text-sm">Collection Date</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Calendar class="w-4 h-4 text-gray-400" />
          <input
            type="datetime-local"
            class="grow bg-transparent outline-none"
            bind:value={formData.CollectionDate}
          />
        </label>
      </label>

      <!-- Collected By -->
      <label class="form-control">
        <span class="label-text text-sm">Collected By</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <User class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Collector name/ID..."
            bind:value={formData.CollectedBy}
          />
        </label>
      </label>

      <!-- Container Type -->
      <label class="form-control">
        <span class="label-text text-sm">Container Type</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <FlaskConical class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Container type..."
            bind:value={formData.ContainerType}
          />
        </label>
      </label>

      <!-- Volume -->
      <label class="form-control">
        <span class="label-text text-sm">Volume</span>
        <div class="flex gap-2 mt-1">
          <label class="input input-sm input-bordered flex items-center gap-2 flex-1">
            <input
              type="number"
              step="0.01"
              class="grow bg-transparent outline-none"
              placeholder="Amount..."
              bind:value={formData.Volume}
            />
          </label>
          <select 
            class="select select-sm select-bordered w-24"
            bind:value={formData.Units}
          >
            <option value="">Unit</option>
            <option value="mL">mL</option>
            <option value="L">L</option>
            <option value="uL">uL</option>
            <option value="g">g</option>
            <option value="mg">mg</option>
          </select>
        </div>
      </label>
    </div>

    <!-- Comment -->
    <label class="form-control">
      <span class="label-text text-sm">Comment</span>
      <textarea
        class="textarea textarea-bordered textarea-sm mt-1 w-full"
        placeholder="Additional notes..."
        rows="3"
        bind:value={formData.Comment}
      ></textarea>
    </label>
  </div>

  {#snippet footer()}
    <button 
      class="btn btn-ghost btn-sm" 
      onclick={handleClose}
      disabled={loading || formLoading}
    >
      Cancel
    </button>
    <button 
      class="btn btn-primary btn-sm" 
      onclick={handleSubmit}
      disabled={loading || formLoading}
    >
      {#if loading || formLoading}
        <span class="loading loading-spinner loading-sm mr-2"></span>
      {/if}
      {specimen ? 'Update' : 'Create'}
    </button>
  {/snippet}
</Modal>
