<!-- #region PolicyForm [C:3] [TYPE Component] [SEMANTICS health, policy, form, validation, schedule] -->
<!-- @BRIEF Component component: lib/components/health/PolicyForm.svelte -->
<!-- @LAYER UI -->
<!--
@PURPOSE: Form for creating and editing validation policies.
@LAYER UI
@RELATION DEPENDS_ON -> [ValidationPolicy]
@PRE: Parent provides callable onSave/onCancel handlers and an environments collection that may be empty but remains array-like.
@POST: Form submission forwards the current draft to onSave and cancel delegates dismissal to the parent callback without mutating external state directly.

@UX_STATE: Idle -> Displays the policy form.
@UX_STATE: Submitting -> Disables inputs and shows a loading state.
@UX_FEEDBACK: Success -> Parent flow can close the form after a successful save.
@UX_FEEDBACK: Error -> Invalid field or submit failures keep the draft visible for correction.
@UX_REACTIVITY: Uses $state for mutable form data and $derived values for window health checks.
-->
<script lang="ts">
  /** @type {{ policy: any, environments: any[], onSave: (p: any) => void, onCancel: () => void }} */
  let { policy = null, environments = [], onSave, onCancel } = $props();

  function getSafePolicy() {
    return policy && typeof policy === 'object' ? policy : {};
  }

  function getSafeEnvironments() {
    return Array.isArray(environments) ? environments : [];
  }

  function buildFormData(currentPolicy, currentEnvironments) {
    return {
      name: currentPolicy.name || '',
      environment_id: currentPolicy.environment_id || (currentEnvironments[0]?.id || ''),
      dashboard_ids: Array.isArray(currentPolicy.dashboard_ids) ? currentPolicy.dashboard_ids : [],
      schedule_days: Array.isArray(currentPolicy.schedule_days) ? currentPolicy.schedule_days : [1, 2, 3, 4, 5], // Default Mon-Fri
      window_start: currentPolicy.window_start || '01:00',
      window_end: currentPolicy.window_end || '05:00',
      notify_owners: currentPolicy.notify_owners ?? true,
      alert_condition: currentPolicy.alert_condition || 'FAIL_ONLY'
    };
  }

  let formData = $state(buildFormData({}, []));
  let isSubmitting = $state(false);

  $effect(() => {
    formData = buildFormData(getSafePolicy(), getSafeEnvironments());
  });

  const days = [
    { id: 0, label: 'Sun' },
    { id: 1, label: 'Mon' },
    { id: 2, label: 'Tue' },
    { id: 3, label: 'Wed' },
    { id: 4, label: 'Thu' },
    { id: 5, label: 'Fri' },
    { id: 6, label: 'Sat' }
  ];

  const alertConditions = [
    { id: 'FAIL_ONLY', label: 'Only on Failure' },
    { id: 'WARN_AND_FAIL', label: 'On Warning or Failure' },
    { id: 'ALWAYS', label: 'Always' }
  ];

  let windowDurationMinutes = $derived(() => {
    const [h1, m1] = formData.window_start.split(':').map(Number);
    const [h2, m2] = formData.window_end.split(':').map(Number);
    let start = h1 * 60 + m1;
    let end = h2 * 60 + m2;
    if (end <= start) end += 24 * 60;
    return end - start;
  });

  let isWindowTooSmall = $derived(windowDurationMinutes() < formData.dashboard_ids.length * 1); // Example: 1 min per dashboard

  async function handleSubmit(event) {
    event.preventDefault();
    isSubmitting = true;
    try {
      await onSave(formData);
    } finally {
      isSubmitting = false;
    }
  }

  function toggleDay(dayId) {
    if (formData.schedule_days.includes(dayId)) {
      formData.schedule_days = formData.schedule_days.filter(d => d !== dayId);
    } else {
      formData.schedule_days = [...formData.schedule_days, dayId];
    }
  }
</script>

<form onsubmit={handleSubmit} class="space-y-6 p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm">
  <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
    <!-- Basic Info -->
    <div class="space-y-4">
      <div>
        <label for="name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Policy Name</label>
        <input id="name" type="text" bind:value={formData.name} 
          class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded-md shadow-sm focus-visible:ring-primary-ring focus-visible:border-primary-ring sm:text-sm" 
          placeholder="e.g., Production Morning Check" required disabled={isSubmitting} />
      </div>

      <div>
        <label for="env" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Environment</label>
        <select id="env" bind:value={formData.environment_id} 
          class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded-md shadow-sm focus-visible:ring-primary-ring focus-visible:border-primary-ring sm:text-sm" 
          disabled={isSubmitting}>
          {#each getSafeEnvironments() as env}
            <option value={env.id}>{env.name || env.id}</option>
          {/each}
        </select>
      </div>

      <div>
        <span class="block text-sm font-medium text-gray-700 dark:text-gray-300">Schedule Days</span>
        <div class="mt-2 flex flex-wrap gap-2">
          {#each days as day}
            <button type="button" 
              onclick={() => toggleDay(day.id)}
              class="px-3 py-1 text-xs font-semibold rounded-full border transition-colors
                {formData.schedule_days.includes(day.id) 
                  ? 'bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-900 dark:text-blue-200' 
                  : 'bg-gray-50 text-gray-600 border-gray-200 dark:bg-gray-700 dark:text-gray-400 dark:border-gray-600'}"
              disabled={isSubmitting}>
              {day.label}
            </button>
          {/each}
        </div>
      </div>
    </div>

    <!-- Window & Alerts -->
    <div class="space-y-4">
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label for="start" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Window Start</label>
          <input id="start" type="time" bind:value={formData.window_start} 
            class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded-md shadow-sm focus-visible:ring-primary-ring focus-visible:border-primary-ring sm:text-sm" 
            disabled={isSubmitting} />
        </div>
        <div>
          <label for="end" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Window End</label>
          <input id="end" type="time" bind:value={formData.window_end} 
            class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded-md shadow-sm focus-visible:ring-primary-ring focus-visible:border-primary-ring sm:text-sm" 
            disabled={isSubmitting} />
        </div>
      </div>

      {#if formData.dashboard_ids.length > 0}
        <div class="p-3 bg-primary-light dark:bg-blue-900/30 rounded-md border border-blue-100 dark:border-blue-800">
          <p class="text-xs text-blue-700 dark:text-blue-300">
            💡 System will automatically distribute {formData.dashboard_ids.length} checks within this {Math.floor(windowDurationMinutes() / 60)}h {windowDurationMinutes() % 60}m window.
          </p>
          {#if isWindowTooSmall}
            <p class="mt-1 text-xs text-amber-600 dark:text-amber-400 font-medium">
              ⚠️ Window might be too narrow for {formData.dashboard_ids.length} dashboards.
            </p>
          {/if}
        </div>
      {/if}

      <div>
        <label for="alert" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Alert Condition</label>
        <select id="alert" bind:value={formData.alert_condition} 
          class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded-md shadow-sm focus-visible:ring-primary-ring focus-visible:border-primary-ring sm:text-sm" 
          disabled={isSubmitting}>
          {#each alertConditions as cond}
            <option value={cond.id}>{cond.label}</option>
          {/each}
        </select>
      </div>

      <div class="flex items-center">
        <input id="notify" type="checkbox" bind:checked={formData.notify_owners} 
          class="h-4 w-4 text-primary focus-visible:ring-primary-ring border-gray-300 rounded" 
          disabled={isSubmitting} />
        <label for="notify" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">
          Auto-notify Dashboard Owners
        </label>
      </div>
    </div>
  </div>

  <div class="pt-4 border-t border-gray-200 dark:border-gray-700 flex justify-end space-x-3">
    <button type="button" onclick={onCancel} 
      class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-ring dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600 dark:hover:bg-gray-600"
      disabled={isSubmitting}>
      Cancel
    </button>
    <button type="submit" 
      class="px-4 py-2 text-sm font-medium text-white bg-primary border border-transparent rounded-md shadow-sm hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-ring disabled:opacity-50"
      disabled={isSubmitting}>
      {isSubmitting ? 'Saving...' : 'Save Policy'}
    </button>
  </div>
</form>
<!-- #endregion PolicyForm -->
