<script>
  import Modal from '$lib/components/Modal.svelte';
  import BasicInfoForm from './test-modal/BasicInfoForm.svelte';
  import ReferenceRangeSection from './test-modal/ReferenceRangeSection.svelte';
  import TechnicalConfigForm from './test-modal/TechnicalConfigForm.svelte';
  import GroupMembersTab from './test-modal/GroupMembersTab.svelte';

  /**
   * @typedef {Object} Props
   * @property {boolean} open - Whether modal is open
   * @property {string} mode - 'create' or 'edit'
   * @property {Object} formData - Form data object
   * @property {boolean} canHaveRefRange - Whether test can have reference ranges
   * @property {boolean} canHaveFormula - Whether test can have a formula
   * @property {boolean} canHaveTechnical - Whether test can have technical config
   * @property {boolean} isGroupTest - Whether test is a group test
   * @property {Array<{value: string, label: string}>} disciplineOptions - Discipline dropdown options
   * @property {Array<{value: string, label: string}>} departmentOptions - Department dropdown options
   * @property {Array} availableTests - Available tests for group member selection
   * @property {boolean} [saving] - Whether save is in progress
   */

  /** @type {Props & { onsave?: () => void, oncancel?: () => void, onupdateFormData?: (formData: Object) => void }} */
  let {
    open = $bindable(false),
    mode = 'create',
    formData = $bindable({}),
    canHaveRefRange = false,
    canHaveFormula = false,
    canHaveTechnical = false,
    isGroupTest = false,
    disciplineOptions = [],
    departmentOptions = [],
    availableTests = [],
    saving = false,
    onsave = () => {},
    oncancel = () => {},
    onupdateFormData = () => {}
  } = $props();

  // Local state
  let activeTab = $state('basic');

  function handleCancel() {
    activeTab = 'basic';
    oncancel();
  }

  function handleSave() {
    onsave();
  }

  // Reactive update when modal opens
  $effect(() => {
    if (open) {
      activeTab = 'basic';
    }
  });

  // Get tab count badge for reference range
  function getRefRangeCount() {
    return (formData.refnum?.length || 0) + (formData.reftxt?.length || 0);
  }

  // Get tab count badge for group members
  function getGroupMemberCount() {
    return formData.groupMembers?.length || 0;
  }
</script>

<Modal bind:open title={mode === 'create' ? 'Add Test' : 'Edit Test'} size="xl" position="top">
  <!-- Tabs -->
  <div class="tabs tabs-bordered mb-4">
    <button
      type="button"
      class="tab tab-lg {activeTab === 'basic' ? 'tab-active' : ''}"
      onclick={() => activeTab = 'basic'}
    >
      Basic Information
    </button>
    {#if canHaveTechnical}
      <button
        type="button"
        class="tab tab-lg {activeTab === 'technical' ? 'tab-active' : ''}"
        onclick={() => activeTab = 'technical'}
      >
        Technical
      </button>
    {/if}
    {#if canHaveRefRange}
      <button
        type="button"
        class="tab tab-lg {activeTab === 'refrange' ? 'tab-active' : ''}"
        onclick={() => activeTab = 'refrange'}
      >
        Reference Range
        {#if getRefRangeCount() > 0}
          <span class="badge badge-sm badge-primary ml-2">{getRefRangeCount()}</span>
        {/if}
      </button>
    {/if}
    {#if isGroupTest}
      <button
        type="button"
        class="tab tab-lg {activeTab === 'members' ? 'tab-active' : ''}"
        onclick={() => activeTab = 'members'}
      >
        Group Members
        {#if getGroupMemberCount() > 0}
          <span class="badge badge-sm badge-primary ml-2">{getGroupMemberCount()}</span>
        {/if}
      </button>
    {/if}
  </div>

  {#if activeTab === 'basic'}
    <BasicInfoForm
      bind:formData
      {canHaveFormula}
      {disciplineOptions}
      {departmentOptions}
      onsave={handleSave}
    />
  {:else if activeTab === 'technical' && canHaveTechnical}
    <TechnicalConfigForm
      bind:formData
      testType={formData.TestType}
      {onupdateFormData}
    />
  {:else if activeTab === 'refrange' && canHaveRefRange}
    <ReferenceRangeSection
      bind:formData
      testType={formData.TestType}
      {onupdateFormData}
    />
  {:else if activeTab === 'members' && isGroupTest}
    <GroupMembersTab
      bind:formData
      {availableTests}
      {onupdateFormData}
    />
  {/if}

  {#snippet footer()}
    <button class="btn btn-ghost" onclick={handleCancel} type="button">Cancel</button>
    <button class="btn btn-primary" onclick={handleSave} disabled={saving} type="button">
      {#if saving}
        <span class="loading loading-spinner loading-sm mr-2"></span>
      {/if}
      {saving ? 'Saving...' : 'Save'}
    </button>
  {/snippet}
</Modal>
