<script>
  import { PlusCircle, Calculator, X, ChevronDown, ChevronUp, Info } from 'lucide-svelte';
  import { signOptions, flagOptions, sexOptions, createNumRef } from '../referenceRange.js';

  /**
   * @typedef {Object} Props
   * @property {Array} refnum - Numeric reference ranges array
   * @property {(refnum: Array) => void} onupdateRefnum - Update handler
   */

  /** @type {Props} */
  let {
    refnum = [],
    onupdateRefnum = () => {}
  } = $props();

  // Track expanded state for each range's optional fields
  let expandedRanges = $state({});

  function addRefRange() {
    const newRef = createNumRef();
    // Set smarter defaults
    newRef.Sex = '0'; // Any
    newRef.Flag = 'N'; // Normal
    onupdateRefnum([...refnum, newRef]);
    // Auto-expand the new range
    expandedRanges[refnum.length] = { age: false, interpretation: false };
  }

  function removeRefRange(index) {
    onupdateRefnum(refnum.filter((_, i) => i !== index));
    delete expandedRanges[index];
  }

  function toggleAgeExpand(index) {
    expandedRanges[index] = { ...expandedRanges[index], age: !expandedRanges[index]?.age };
  }

  function toggleInterpExpand(index) {
    expandedRanges[index] = { ...expandedRanges[index], interpretation: !expandedRanges[index]?.interpretation };
  }

  function getSignLabel(value) {
    return signOptions.find(o => o.value === value)?.label || value;
  }

  function getSexLabel(value) {
    return sexOptions.find(o => o.value === value)?.label || 'Any';
  }

  function getFlagColor(flag) {
    const colors = {
      'N': 'badge-success',
      'L': 'badge-warning',
      'H': 'badge-warning',
      'C': 'badge-error'
    };
    return colors[flag] || 'badge-ghost';
  }

  function getFlagLabel(flag) {
    const option = flagOptions.find(o => o.value === flag);
    return option ? `${option.label} (${option.description})` : flag;
  }

  // Generate human-readable preview
  function getRangePreview(ref) {
    const sex = getSexLabel(ref.Sex);
    const ageText = (ref.AgeStart !== 0 || ref.AgeEnd !== 120) 
      ? `Age ${ref.AgeStart}-${ref.AgeEnd}` 
      : 'All ages';
    
    let rangeText = '';
    if (ref.Low !== null && ref.High !== null) {
      rangeText = `${getSignLabel(ref.LowSign)}${ref.Low} to ${getSignLabel(ref.HighSign)}${ref.High}`;
    } else if (ref.Low !== null) {
      rangeText = `${getSignLabel(ref.LowSign)}${ref.Low}`;
    } else if (ref.High !== null) {
      rangeText = `${getSignLabel(ref.HighSign)}${ref.High}`;
    } else {
      rangeText = 'Not set';
    }

    return `${sex}, ${ageText}: ${rangeText}`;
  }
</script>

<div class="space-y-4">
  <div class="flex justify-between items-center">
    <div class="flex items-center gap-2">
      <Calculator class="w-5 h-5 text-primary" />
      <h3 class="font-semibold">Numeric Reference Ranges</h3>
    </div>
    <button type="button" class="btn btn-sm btn-primary" onclick={addRefRange}>
      <PlusCircle class="w-4 h-4 mr-1" />
      Add Range
    </button>
  </div>

  {#if refnum?.length === 0}
    <div class="text-center py-8 bg-base-200 rounded-lg border-2 border-dashed border-base-300">
      <Calculator class="w-12 h-12 mx-auto text-gray-400 mb-2" />
      <p class="text-gray-500">No numeric ranges defined</p>
      <button type="button" class="btn btn-sm btn-outline mt-2" onclick={addRefRange}>
        <PlusCircle class="w-4 h-4 mr-1" />
        Add First Range
      </button>
    </div>
  {/if}

  {#each refnum || [] as ref, index (index)}
    <div class="card bg-base-100 border-2 border-base-200 hover:border-primary/50 transition-colors">
      <div class="card-body p-4">
        <!-- Header with Preview -->
        <div class="flex justify-between items-start mb-4 pb-3 border-b border-base-200">
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-2">
              <span class="badge badge-primary">Range {index + 1}</span>
              <span class="badge {getFlagColor(ref.Flag)}">{getFlagLabel(ref.Flag)}</span>
            </div>
            <!-- Live Preview -->
            <div class="text-sm text-gray-600 bg-base-200 p-2 rounded flex items-center gap-2">
              <Info class="w-4 h-4 text-primary flex-shrink-0" />
              <span>{getRangePreview(ref)}</span>
            </div>
          </div>
          <button type="button" class="btn btn-sm btn-ghost text-error ml-2" onclick={() => removeRefRange(index)}>
            <X class="w-4 h-4" />
          </button>
        </div>

        <!-- Main Fields - Range Values (Most Important) -->
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3">
          <div class="form-control">
            <span class="label-text text-xs mb-1 font-medium">Lower Bound</span>
            <div class="flex gap-2">
              <select class="select select-sm select-bordered w-16" bind:value={ref.LowSign}>
                {#each signOptions as option (option.value)}
                  <option value={option.value}>{option.label}</option>
                {/each}
              </select>
              <input 
                type="number" 
                step="0.01" 
                class="input input-sm input-bordered flex-1" 
                bind:value={ref.Low} 
                placeholder="70" 
              />
            </div>
          </div>

          <div class="form-control">
            <span class="label-text text-xs mb-1 font-medium">Upper Bound</span>
            <div class="flex gap-2">
              <select class="select select-sm select-bordered w-16" bind:value={ref.HighSign}>
                {#each signOptions as option (option.value)}
                  <option value={option.value}>{option.label}</option>
                {/each}
              </select>
              <input 
                type="number" 
                step="0.01" 
                class="input input-sm input-bordered flex-1" 
                bind:value={ref.High} 
                placeholder="100" 
              />
            </div>
          </div>
        </div>

        <!-- Sex & Flag Row -->
        <div class="grid grid-cols-2 gap-3 mb-3">
          <div class="form-control">
            <span class="label-text text-xs mb-1">Sex</span>
            <select class="select select-sm select-bordered w-full" bind:value={ref.Sex}>
              {#each sexOptions as option (option.value)}
                <option value={option.value}>{option.label}</option>
              {/each}
            </select>
          </div>

          <div class="form-control">
            <span class="label-text text-xs mb-1">Flag</span>
            <select class="select select-sm select-bordered w-full" bind:value={ref.Flag}>
              {#each flagOptions as option (option.value)}
                <option value={option.value}>{option.label} - {option.description}</option>
              {/each}
            </select>
          </div>
        </div>

        <!-- Expandable: Age Range -->
        <div class="border border-base-200 rounded-lg mb-2 overflow-hidden">
          <button 
            type="button" 
            class="w-full px-3 py-2 bg-base-200 hover:bg-base-300 flex items-center justify-between text-sm transition-colors"
            onclick={() => toggleAgeExpand(index)}
          >
            <span class="flex items-center gap-2">
              <span class="text-xs">Age Range</span>
              {#if ref.AgeStart !== 0 || ref.AgeEnd !== 120}
                <span class="text-xs text-primary">({ref.AgeStart}-{ref.AgeEnd})</span>
              {:else}
                <span class="text-xs text-gray-500">(All ages)</span>
              {/if}
            </span>
            {#if expandedRanges[index]?.age}
              <ChevronUp class="w-4 h-4" />
            {:else}
              <ChevronDown class="w-4 h-4" />
            {/if}
          </button>
          
          {#if expandedRanges[index]?.age}
            <div class="p-3 bg-base-100">
              <div class="grid grid-cols-2 gap-3">
                <div class="form-control">
                  <span class="label-text text-xs mb-1">From (years)</span>
                  <input type="number" min="0" max="120" class="input input-sm input-bordered w-full" bind:value={ref.AgeStart} />
                </div>
                <div class="form-control">
                  <span class="label-text text-xs mb-1">To (years)</span>
                  <input type="number" min="0" max="120" class="input input-sm input-bordered w-full" bind:value={ref.AgeEnd} />
                </div>
              </div>
            </div>
          {/if}
        </div>

        <!-- Expandable: Interpretation -->
        <div class="border border-base-200 rounded-lg overflow-hidden">
          <button 
            type="button" 
            class="w-full px-3 py-2 bg-base-200 hover:bg-base-300 flex items-center justify-between text-sm transition-colors"
            onclick={() => toggleInterpExpand(index)}
          >
            <span class="flex items-center gap-2">
              <span class="text-xs">Interpretation</span>
              {#if ref.Interpretation}
                <span class="text-xs text-primary truncate max-w-[200px]">({ref.Interpretation})</span>
              {/if}
            </span>
            {#if expandedRanges[index]?.interpretation}
              <ChevronUp class="w-4 h-4" />
            {:else}
              <ChevronDown class="w-4 h-4" />
            {/if}
          </button>
          
          {#if expandedRanges[index]?.interpretation}
            <div class="p-3 bg-base-100">
              <div class="form-control">
                <textarea 
                  class="textarea textarea-bordered w-full text-sm" 
                  rows="2" 
                  bind:value={ref.Interpretation} 
                  placeholder="e.g., Normal fasting glucose range"
                ></textarea>
              </div>
            </div>
          {/if}
        </div>
      </div>
    </div>
  {/each}
</div>
