<!-- #region StartMaintenanceForm [C:3] [TYPE Component] [SEMANTICS maintenance, start, form, template, presets] -->
<!-- @BRIEF Start maintenance form with template presets, table name input, and datetime pickers. -->
<!-- @LAYER Component -->
<!-- @RELATION DEPENDS_ON -> [MaintenanceApi] -->
<!-- @RELATION DEPENDS_ON -> [EXT:frontend:addToast] -->
<!-- @UX_STATE idle -> Form ready, fields editable. -->
<!-- @UX_STATE submitting -> Submit button shows spinner, fields disabled. -->
<!-- @UX_STATE success -> Toast shown, form resets. -->
<!-- @UX_STATE error -> Error toast with message. -->
<!-- @UX_FEEDBACK Toast on start/success/error. -->
<!-- @UX_RECOVERY Retry via re-submit. -->
<script lang="ts">
  import { startMaintenance } from "$lib/api/maintenance.js";
  import { addToast } from "$lib/toasts.svelte.js";
  import { t } from "$lib/i18n/index.svelte.js";
  import HelpTooltip from "$lib/ui/HelpTooltip.svelte";

  /** @type {{ onSuccess?: () => void }} */
  let { onSuccess = () => {} } = $props();

  // ── Templates ──────────────────────────────────────────────
  /**
   * Predefined maintenance templates.
   * Each template defines defaults for message and duration.
   */
  const TEMPLATES = {
    custom: {
      label: "template_none",
      message: "",
      durationHours: null,
    },
    daily_refresh: {
      label: "template_daily_refresh",
      description: "template_daily_refresh_desc",
      message: "Scheduled data mart refresh — daily ETL update in progress.",
      durationHours: 4,
    },
    schema_migration: {
      label: "template_schema_migration",
      description: "template_schema_migration_desc",
      message: "Schema migration in progress. Dashboard data may be temporarily incomplete.",
      durationHours: 2,
    },
    emergency: {
      label: "template_emergency",
      description: "template_emergency_desc",
      message: "Emergency maintenance — we are applying a critical fix. Data may be stale.",
      durationHours: 1,
    },
    extended: {
      label: "template_extended",
      description: "template_extended_desc",
      message: "Extended maintenance window — large-scale data refresh in progress.",
      durationHours: 8,
    },
  };

  // ── Form state ─────────────────────────────────────────────
  let tableName = $state("");
  let startTime = $state("");
  let endTime = $state("");
  let message = $state("");
  let selectedTemplate = $state("custom");
  let isSubmitting = $state(false);

  // Validation
  let tableError = $state("");

  // Initialize startTime to current datetime-local
  function initStartTime() {
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    startTime = now.toISOString().slice(0, 16);
  }
  initStartTime();

  // ── Template selection handler ─────────────────────────────
  function applyTemplate(templateId) {
    selectedTemplate = templateId;
    const tmpl = TEMPLATES[templateId];
    if (!tmpl || templateId === "custom") {
      // Don't overwrite user-entered values when going back to custom
      return;
    }
    message = tmpl.message;
    if (tmpl.durationHours && startTime) {
      const start = new Date(startTime);
      const end = new Date(start.getTime() + tmpl.durationHours * 60 * 60 * 1000);
      end.setMinutes(end.getMinutes() - end.getTimezoneOffset());
      endTime = end.toISOString().slice(0, 16);
    }
  }

  // ── Submit ─────────────────────────────────────────────────
  async function handleSubmit() {
    // Validate
    tableError = "";
    const trimmedTable = tableName.trim();
    if (!trimmedTable) {
      tableError = $t.maintenance?.table_required || "Table name is required";
      return;
    }

    isSubmitting = true;
    try {
      const params = {
        tables: [trimmedTable],
        start_time: startTime ? new Date(startTime).toISOString() : new Date().toISOString(),
      };
      if (endTime) {
        params.end_time = new Date(endTime).toISOString();
      }
      if (message.trim()) {
        params.message = message.trim();
      }

      const result = await startMaintenance(params);

      addToast(
        ($t.maintenance?.start_success || "Maintenance started. Task: {task_id}").replace("{task_id}", result.task_id),
        "success"
      );

      // Reset form
      tableName = "";
      endTime = "";
      message = "";
      selectedTemplate = "custom";
      initStartTime();
      onSuccess();
    } catch (e) {
      addToast(e?.message || $t.maintenance?.start_error || "Failed to start maintenance", "error");
    } finally {
      isSubmitting = false;
    }
  }
</script>

<div class="rounded-lg border border-gray-200 bg-white">
  <div class="px-4 py-3 border-b border-gray-200">
    <h3 class="text-base font-semibold text-gray-900">
      {$t.maintenance?.start_maintenance || "Start Maintenance"}
    </h3>
    <p class="mt-0.5 text-xs text-gray-500">
      {$t.maintenance?.start_maintenance_description || ""}
    </p>
  </div>

  <div class="px-4 py-4 space-y-4">
    <!-- Template Presets -->
    <div>
      <span class="flex items-center gap-1.5 mb-1.5">
        <span class="text-sm font-medium text-gray-700">
          {$t.maintenance?.template_label || "Quick Template"}
        </span>
      </span>
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2">
        {#each Object.entries(TEMPLATES) as [id, tmpl]}
          <button
            type="button"
            onclick={() => applyTemplate(id)}
            class="text-left px-3 py-2 rounded-lg border text-sm transition-colors
              {selectedTemplate === id
                ? 'border-blue-500 bg-blue-50 text-blue-800'
                : 'border-gray-200 bg-white text-gray-700 hover:border-gray-300 hover:bg-gray-50'}"
          >
            <div class="font-medium leading-tight">
              {$t.maintenance?.[tmpl.label] || tmpl.label}
            </div>
            {#if tmpl.description}
              <div class="text-xs text-gray-500 mt-0.5 leading-tight">
                {$t.maintenance?.[tmpl.description] || tmpl.description}
              </div>
            {/if}
          </button>
        {/each}
      </div>
    </div>

    <!-- Table Name -->
    <div>
      <span class="flex items-center gap-1.5 mb-1.5">
        <label for="mt-table" class="text-sm font-medium text-gray-700">
          {$t.maintenance?.table_name || "Table Name"}
        </label>
        <HelpTooltip text={$t.maintenance?.table_help || ""} />
      </span>
      <input
        id="mt-table"
        type="text"
        bind:value={tableName}
        placeholder={$t.maintenance?.table_name_placeholder || "e.g. raw.sales"}
        class="block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm
          focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500
          placeholder:text-gray-400
          {tableError ? 'border-red-400' : ''}"
      />
      {#if tableError}
        <p class="mt-1 text-xs text-red-600">{tableError}</p>
      {/if}
    </div>

    <!-- Start / End Time -->
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
      <div>
        <span class="flex items-center gap-1.5 mb-1.5">
          <label for="mt-start" class="text-sm font-medium text-gray-700">
            {$t.maintenance?.start_time_label || "Start Time"}
          </label>
          <HelpTooltip text={$t.maintenance?.start_time_help || ""} />
        </span>
        <input
          id="mt-start"
          type="datetime-local"
          bind:value={startTime}
          class="block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm
            focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
        />
      </div>

      <div>
        <span class="flex items-center gap-1.5 mb-1.5">
          <label for="mt-end" class="text-sm font-medium text-gray-700">
            {$t.maintenance?.end_time_label || "End Time (optional)"}
          </label>
          <HelpTooltip text={$t.maintenance?.end_time_help || ""} />
        </span>
        <input
          id="mt-end"
          type="datetime-local"
          bind:value={endTime}
          class="block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm
            focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
        />
      </div>
    </div>

    <!-- Message -->
    <div>
      <span class="flex items-center gap-1.5 mb-1.5">
        <label for="mt-msg" class="text-sm font-medium text-gray-700">
          {$t.maintenance?.message_label || "Message (optional)"}
        </label>
        <HelpTooltip text={$t.maintenance?.message_help || ""} />
      </span>
      <input
        id="mt-msg"
        type="text"
        bind:value={message}
        placeholder={$t.maintenance?.message_placeholder || "Scheduled data mart refresh"}
        class="block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm
          focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500
          placeholder:text-gray-400"
      />
    </div>

    <!-- Submit -->
    <div class="flex justify-end pt-1">
      <button
        type="button"
        onclick={handleSubmit}
        disabled={isSubmitting}
        class="inline-flex items-center justify-center rounded-lg bg-primary px-5 py-2 text-sm font-medium text-white
          transition-colors hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {#if isSubmitting}
          <svg class="w-4 h-4 mr-2 animate-spin" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
          {$t.maintenance?.starting || "Starting..."}
        {:else}
          {$t.maintenance?.start_now || "Start Maintenance"}
        {/if}
      </button>
    </div>
  </div>
</div>
<!-- #endregion StartMaintenanceForm -->
