<!-- #region PolicyForm [C:3] [TYPE Component] [SEMANTICS health, policy, form, validation, schedule] -->
<!-- @ingroup Components -->
<!-- @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.
@POST: Form submission forwards the current draft to onSave and cancel delegates dismissal to the parent callback.

@UX_STATE: Idle -> Displays the policy form with editable fields.
@UX_STATE: Submitting -> Disables inputs and shows a loading state.
@UX_FEEDBACK: Success -> Parent flow closes the form after a successful save.
@UX_FEEDBACK: Error -> Submit failures keep the draft visible for correction.
@UX_REACTIVITY: Uses $state for mutable form data and $derived for window health checks.
-->
<script lang="ts">
  import { Button, Input, Select } from '$lib/ui';
  import { t } from '$lib/i18n/index.svelte.js';

  /** @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],
      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'
    };
  }

  // eslint-disable-next-line svelte/prefer-writable-derived
  let formData = $state(buildFormData({}, []));
  let isSubmitting = $state(false);

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

  const days = $derived([
    { id: 0, label: t.settings?.day_sun || 'Sun' },
    { id: 1, label: t.settings?.day_mon || 'Mon' },
    { id: 2, label: t.settings?.day_tue || 'Tue' },
    { id: 3, label: t.settings?.day_wed || 'Wed' },
    { id: 4, label: t.settings?.day_thu || 'Thu' },
    { id: 5, label: t.settings?.day_fri || 'Fri' },
    { id: 6, label: t.settings?.day_sat || 'Sat' }
  ]);

  const alertConditionOptions = $derived([
    { value: 'FAIL_ONLY', label: t.settings?.alert_fail_only || 'Only on Failure' },
    { value: 'WARN_AND_FAIL', label: t.settings?.alert_warn_and_fail || 'On Warning or Failure' },
    { value: 'ALWAYS', label: t.settings?.alert_always || 'Always' }
  ]);

  const environmentOptions = $derived(
    getSafeEnvironments().map(e => ({ value: e.id, label: e.name || e.id }))
  );

  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);

  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 bg-surface-card border border-border rounded-lg p-6 shadow-sm">
  <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
    <!-- Left Column: Basic Info -->
    <div class="space-y-4">
      <Input
        label={$t.settings?.policy_name || 'Policy Name'}
        bind:value={formData.name}
        placeholder={$t.settings?.policy_name_placeholder || 'e.g., Production Morning Check'}
        disabled={isSubmitting}
      />

      <Select
        label={$t.settings?.environment || 'Environment'}
        bind:value={formData.environment_id}
        options={environmentOptions}
        disabled={isSubmitting}
      />

      <!-- Schedule Days -->
      <fieldset class="border-0 p-0 m-0">
        <legend class="text-sm font-medium text-text mb-2">{$t.settings?.schedule_days || 'Schedule Days'}</legend>
        <div class="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 cursor-pointer
                {formData.schedule_days.includes(day.id)
                  ? 'bg-primary-light text-primary border-primary-ring dark:bg-primary dark:text-primary'
                  : 'bg-surface-card text-text-muted border-border-strong hover:bg-surface-muted dark:bg-terminal-bg dark:text-text-subtle dark:border-border-strong'}"
              disabled={isSubmitting}
            >
              {day.label}
            </button>
          {/each}
        </div>
      </fieldset>
    </div>

    <!-- Right Column: Window & Alerts -->
    <div class="space-y-4">
      <div class="grid grid-cols-2 gap-4">
        <Input
          label={$t.settings?.window_start || 'Window Start'}
          type="time"
          bind:value={formData.window_start}
          disabled={isSubmitting}
        />
        <Input
          label={$t.settings?.window_end || 'Window End'}
          type="time"
          bind:value={formData.window_end}
          disabled={isSubmitting}
        />
      </div>

      {#if formData.dashboard_ids.length > 0}
        <div class="p-3 bg-primary-light dark:bg-primary/30 rounded-md border border-primary-ring">
          <p class="text-xs text-primary dark:text-primary">
            {($t.settings?.distribution_info || 'System will automatically distribute {count} checks within this {hours}h {minutes}m window.')
              .replace('{count}', formData.dashboard_ids.length)
              .replace('{hours}', Math.floor(windowDurationMinutes() / 60))
              .replace('{minutes}', windowDurationMinutes() % 60)}
          </p>
          {#if isWindowTooSmall}
            <p class="mt-1 text-xs text-warning font-medium">
              {($t.settings?.window_warning || 'Window might be too narrow for {count} dashboards.')
                .replace('{count}', formData.dashboard_ids.length)}
            </p>
          {/if}
        </div>
      {/if}

      <Select
        label={$t.settings?.alert_condition || 'Alert Condition'}
        bind:value={formData.alert_condition}
        options={alertConditionOptions}
        disabled={isSubmitting}
      />

      <!-- Notify Owners Checkbox -->
      <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-border-strong rounded"
          disabled={isSubmitting}
        />
        <label for="notify" class="ml-2 block text-sm text-text dark:text-text-subtle">
          {$t.settings?.notify_owners || 'Auto-notify Dashboard Owners'}
        </label>
      </div>
    </div>
  </div>

  <!-- Actions -->
  <div class="pt-4 border-t border-border flex justify-end space-x-3">
    <Button variant="secondary" onclick={onCancel} disabled={isSubmitting}>
      {$t.settings?.cancel || 'Cancel'}
    </Button>
    <Button type="submit" disabled={isSubmitting}>
      {isSubmitting ? ($t.settings?.saving_policy || 'Saving...') : ($t.settings?.save_policy || 'Save Policy')}
    </Button>
  </div>
</form>
<!-- #endregion PolicyForm -->
