<script>
  import { Search, Plus, X, Microscope } from 'lucide-svelte';

  /**
   * @typedef {Object} Props
   * @property {Object} formData - Form data object
   * @property {Array} availableTests - Available tests for selection
   * @property {(formData: Object) => void} onupdateFormData - Update handler
   */

  /** @type {Props} */
  let {
    formData = $bindable({}),
    availableTests = [],
    onupdateFormData = () => {}
  } = $props();

  let searchQuery = $state('');

  // Filter out the current test and already selected tests
  let filteredTests = $derived(
    availableTests.filter(test =>
      test.TestSiteID !== formData.TestSiteID &&
      !formData.groupMembers?.some(member => member.TestSiteID === test.TestSiteID) &&
      (test.TestSiteName.toLowerCase().includes(searchQuery.toLowerCase()) ||
       test.TestSiteCode.toLowerCase().includes(searchQuery.toLowerCase()))
    )
  );

  function addMember(test) {
    const newMembers = [
      ...(formData.groupMembers || []),
      {
        TestSiteID: test.TestSiteID,
        TestSiteCode: test.TestSiteCode,
        TestSiteName: test.TestSiteName,
        TestType: test.TestType
      }
    ];
    onupdateFormData({ ...formData, groupMembers: newMembers });
    searchQuery = '';
  }

  function removeMember(index) {
    const newMembers = formData.groupMembers.filter((_, i) => i !== index);
    onupdateFormData({ ...formData, groupMembers: newMembers });
  }

  function getTestTypeBadge(testType) {
    const badges = {
      'TEST': 'badge-primary',
      'PARAM': 'badge-secondary',
      'CALC': 'badge-accent',
      'GROUP': 'badge-info',
      'TITLE': 'badge-ghost'
    };
    return badges[testType] || 'badge-ghost';
  }
</script>

<div class="grid grid-cols-1 md:grid-cols-2 gap-4 h-[500px]">
  <!-- Left: Search for Tests -->
  <div class="bg-base-100 rounded-lg border border-base-200 p-4 flex flex-col">
    <div class="flex items-center gap-2 mb-4">
      <Microscope class="w-5 h-5 text-primary" />
      <h3 class="font-semibold">Add Group Members</h3>
    </div>

    <div class="form-control mb-3">
      <div class="relative">
        <Search class="w-5 h-5 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
        <input
          type="text"
          class="input input-bordered w-full pl-10"
          bind:value={searchQuery}
          placeholder="Search by test name or code..."
        />
      </div>
    </div>

    <div class="flex-1 overflow-y-auto border border-base-200 rounded-lg">
      {#if searchQuery}
        {#if filteredTests.length === 0}
          <div class="p-4 text-center text-gray-500">
            No tests found matching "{searchQuery}"
          </div>
        {:else}
          {#each filteredTests as test}
            <button
              type="button"
              class="w-full text-left p-3 hover:bg-base-200 flex items-center justify-between group border-b border-base-200 last:border-0"
              onclick={() => addMember(test)}
            >
              <div class="flex items-center gap-3">
                <span class="font-mono text-sm text-gray-600">{test.TestSiteCode}</span>
                <span class="font-medium">{test.TestSiteName}</span>
                <span class="badge badge-sm {getTestTypeBadge(test.TestType)}">
                  {test.TestType}
                </span>
              </div>
              <Plus class="w-4 h-4 text-gray-400 group-hover:text-primary" />
            </button>
          {/each}
        {/if}
      {:else}
        <div class="p-8 text-center text-gray-400">
          <Search class="w-12 h-12 mx-auto mb-2 opacity-50" />
          <p>Type to search for tests</p>
        </div>
      {/if}
    </div>
  </div>

  <!-- Right: Selected Members -->
  <div class="bg-base-100 rounded-lg border border-base-200 p-2 flex flex-col">
    <div class="flex items-center justify-between mb-2 px-1">
      <div class="flex items-center gap-2">
        <span class="font-semibold text-sm">Group Members</span>
        <span class="badge badge-xs badge-primary">{formData.groupMembers?.length || 0}</span>
      </div>
    </div>

    <div class="flex-1 overflow-y-auto">
      {#if !formData.groupMembers || formData.groupMembers.length === 0}
        <div class="h-full flex flex-col items-center justify-center text-center py-6 bg-base-200 rounded-lg border-2 border-dashed border-base-300">
          <Microscope class="w-8 h-8 text-gray-400 mb-1" />
          <p class="text-gray-500 text-sm">No members added yet</p>
          <p class="text-xs text-gray-400 mt-0.5">Search and add tests from the left</p>
        </div>
      {:else}
        <div class="space-y-1">
          {#each formData.groupMembers as member, index (`${member.TestSiteID}-${index}`)}
            <div class="flex items-center gap-2 px-2 py-1.5 bg-base-100 border border-base-200 rounded hover:border-primary/50 transition-colors">
              <div class="flex-1 min-w-0">
                <div class="flex items-center gap-1.5">
                  <span class="font-mono text-xs text-gray-600">{member.TestSiteCode}</span>
                  <span class="text-sm truncate">{member.TestSiteName}</span>
                </div>
              </div>

              <span class="badge badge-xs {getTestTypeBadge(member.TestType)}">
                {member.TestType}
              </span>

              <button
                type="button"
                class="btn btn-xs btn-ghost text-error p-0 min-h-0 h-6 w-6"
                onclick={() => removeMember(index)}
              >
                <X class="w-3 h-3" />
              </button>
            </div>
          {/each}
        </div>
      {/if}
    </div>
  </div>
</div>
