<!-- #region EnvironmentsTab [C:3] [TYPE Component] [SEMANTICS sveltekit, environment, crud, connection, config] -->
<!-- @BRIEF Component component: routes/settings/EnvironmentsTab.svelte -->
<!-- @LAYER UI -->
<script lang="ts">
  /**
   * @PURPOSE: Environments configuration tab for managing Superset environments.
   * @LAYER UI
   * @RELATION DEPENDS_ON -> [EXT:frontend:SettingsUtils]
   * @PRE: Settings page has loaded environments data.
   * @POST: Exposes environment CRUD interface.
   * @SIDE_EFFECT: Calls API to add, update, delete, or test environments and triggers toasts.
   * @UX_STATE: Loading -> Form shows disabled controls during save.
   * @UX_STATE: Loaded -> List of environments.
   * @UX_FEEDBACK: Toast notifications on success/failure of CRUD or test operations.
   */
  import { t } from "$lib/i18n/index.svelte.js";
  import { api } from "$lib/api.js";
  import { addToast } from "$lib/toasts.svelte.js";
  import { resolveEnvStage, normalizeSupersetBaseUrl } from "./settings-utils.js";

  let { settings = $bindable(), onSave } = $props();

  let editingEnvId = $state(null);
  let isAddingEnv = $state(false);
  let newEnv = $state({
    id: "",
    name: "",
    url: "",
    username: "",
    password: "",
    stage: "DEV",
    is_production: false,
    is_default: false,
    backup_schedule: {
      enabled: false,
      cron_expression: "0 0 * * *",
    },
  });

  async function handleTestEnv(id) {
    console.log(`[EXT:frontend:EnvironmentsTab][Action] Test environment ${id}`);
    addToast($t.settings?.testing_connection, "info");
    try {
      const result = await api.testEnvironmentConnection(id);
      if (result.status === "success") {
        addToast($t.settings?.connection_success, "success");
      } else {
        addToast(
          ($t.settings?.connection_failed).replace(
            "{error}",
            result.message || $t.common?.unknown,
          ),
          "error",
        );
      }
    } catch (err) {
      console.error("[EXT:frontend:EnvironmentsTab][Coherence:Failed] Error testing connection:", err);
      addToast($t.settings?.connection_test_failed, "error");
    }
  }

  function editEnv(env) {
    console.log(`[EXT:frontend:EnvironmentsTab][Action] Edit environment ${env.id}`);
    newEnv = JSON.parse(JSON.stringify(env)); // Deep copy
    newEnv.url = normalizeSupersetBaseUrl(newEnv.url);
    if (!newEnv.backup_schedule) {
      newEnv.backup_schedule = { enabled: false, cron_expression: "0 0 * * *" };
    }
    const rawStage = String(newEnv.stage || "").toUpperCase();
    if (rawStage === "DEV" && newEnv.is_production === true) {
      newEnv.stage = "PROD";
    } else if (!rawStage) {
      newEnv.stage = newEnv.is_production ? "PROD" : "DEV";
    } else {
      newEnv.stage = rawStage;
    }
    editingEnvId = env.id;
    isAddingEnv = false;
  }

  function resetEnvForm() {
    newEnv = {
      id: "",
      name: "",
      url: "",
      username: "",
      password: "",
      stage: "DEV",
      is_production: false,
      is_default: false,
      backup_schedule: {
        enabled: false,
        cron_expression: "0 0 * * *",
      },
    };
    editingEnvId = null;
  }

  async function handleAddOrUpdateEnv() {
    try {
      console.log(`[EXT:frontend:EnvironmentsTab][Action] ${editingEnvId ? "Updating" : "Adding"} environment.`);
      if (!newEnv.id || !newEnv.name || !newEnv.url) {
        addToast($t.settings?.env_required_fields, "error");
        return;
      }

      const payload = {
        ...newEnv,
        url: normalizeSupersetBaseUrl(newEnv.url),
        stage: String(newEnv.stage || "DEV").toUpperCase(),
        is_production: String(newEnv.stage || "DEV").toUpperCase() === "PROD",
      };

      if (editingEnvId) {
        await api.updateEnvironment(editingEnvId, payload);
        addToast($t.settings?.env_updated, "success");
      } else {
        await api.addEnvironment(payload);
        addToast($t.settings?.env_added, "success");
      }

      resetEnvForm();
      editingEnvId = null;
      isAddingEnv = false;
      if (onSave) await onSave();
    } catch (error) {
      console.error("[EXT:frontend:EnvironmentsTab][Coherence:Failed] Failed to save environment:", error);
      addToast(error.message || $t.settings?.env_save_failed, "error");
    }
  }

  async function handleDeleteEnv(id) {
    if (confirm($t.settings?.env_delete_confirm)) {
      console.log(`[EXT:frontend:EnvironmentsTab][Action] Delete environment ${id}`);
      try {
        await api.deleteEnvironment(id);
        addToast($t.settings?.env_deleted, "success");
        if (onSave) await onSave();
      } catch (error) {
        console.error("[EXT:frontend:EnvironmentsTab][Coherence:Failed] Failed to delete environment:", error);
        addToast($t.settings?.env_delete_failed, "error");
      }
    }
  }
</script>

<div class="text-lg font-medium mb-4">
  <h2 class="text-xl font-bold mb-4">
    {$t.settings?.environments}
  </h2>
  <p class="text-gray-600 mb-6">
    {$t.settings?.env_description}
  </p>

  {#if !editingEnvId && !isAddingEnv}
    <div class="flex justify-end mb-6">
      <button
        class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary-hover"
        onclick={() => {
          isAddingEnv = true;
          resetEnvForm();
        }}
      >
        {$t.settings?.env_add}
      </button>
    </div>
  {/if}

  {#if editingEnvId || isAddingEnv}
    <div class="bg-gray-50 p-6 rounded-lg mb-6 border border-gray-200">
      <h3 class="text-lg font-medium mb-4">
        {editingEnvId ? $t.settings?.env_edit : $t.settings?.env_add}
      </h3>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label for="env_id" class="block text-sm font-medium text-gray-700">{$t.common?.id}</label>
          <input
            type="text"
            id="env_id"
            bind:value={newEnv.id}
            disabled={!!editingEnvId}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 disabled:bg-gray-100 disabled:text-gray-500"
          />
        </div>
        <div>
          <label for="env_name" class="block text-sm font-medium text-gray-700">{$t.connections?.name}</label>
          <input
            type="text"
            id="env_name"
            bind:value={newEnv.name}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
          />
        </div>
        <div>
          <label for="env_url" class="block text-sm font-medium text-gray-700">{$t.settings?.env_url}</label>
          <input
            type="text"
            id="env_url"
            bind:value={newEnv.url}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
          />
        </div>
        <div>
          <label for="env_user" class="block text-sm font-medium text-gray-700">{$t.connections?.user}</label>
          <input
            type="text"
            id="env_user"
            bind:value={newEnv.username}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
          />
        </div>
        <div>
          <label for="env_pass" class="block text-sm font-medium text-gray-700">{$t.connections?.pass}</label>
          <input
            type="password"
            id="env_pass"
            bind:value={newEnv.password}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
          />
        </div>
        <div class="flex items-center mt-6">
          <input
            type="checkbox"
            id="env_default"
            bind:checked={newEnv.is_default}
            class="h-4 w-4 text-primary border-gray-300 rounded"
          />
          <label for="env_default" class="ml-2 block text-sm text-gray-900">{$t.settings?.env_default}</label>
        </div>
        <div>
          <label for="env_stage" class="block text-sm font-medium text-gray-700">Stage</label>
          <select
            id="env_stage"
            bind:value={newEnv.stage}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
          >
            <option value="DEV">DEV</option>
            <option value="PREPROD">PREPROD</option>
            <option value="PROD">PROD</option>
          </select>
        </div>
      </div>

      <h3 class="text-lg font-medium mb-4 mt-6">
        {$t.tasks?.backup_schedule}
      </h3>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="flex items-center">
          <input
            type="checkbox"
            id="backup_enabled"
            bind:checked={newEnv.backup_schedule.enabled}
            class="h-4 w-4 text-primary border-gray-300 rounded"
          />
          <label for="backup_enabled" class="ml-2 block text-sm text-gray-900">{$t.settings?.enable_auto_backups}</label>
        </div>
        <div>
          <label for="cron_expression" class="block text-sm font-medium text-gray-700">{$t.tasks?.cron_label}</label>
          <input
            type="text"
            id="cron_expression"
            bind:value={newEnv.backup_schedule.cron_expression}
            placeholder={$t.settings?.cron_placeholder}
            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
          />
          <p class="text-xs text-gray-500 mt-1">
            {$t.tasks?.cron_hint}
          </p>
        </div>
      </div>

      <div class="mt-6 flex gap-2 justify-end">
        <button
          onclick={() => {
            isAddingEnv = false;
            editingEnvId = null;
            resetEnvForm();
          }}
          class="bg-gray-200 text-gray-700 px-4 py-2 rounded hover:bg-gray-300"
        >
          {$t.common?.cancel}
        </button>
        <button
          onclick={handleAddOrUpdateEnv}
          class="bg-primary text-white px-4 py-2 rounded hover:bg-primary-hover"
        >
          {editingEnvId ? $t.settings?.env_update : $t.settings?.env_add}
        </button>
      </div>
    </div>
  {/if}

  {#if settings.environments && settings.environments.length > 0}
    <div class="mt-6 overflow-x-auto border border-gray-200 rounded-lg">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.connections?.name}</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.settings?.env_url}</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.connections?.user}</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.settings?.default}</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stage</th>
            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.settings?.env_actions}</th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          {#each settings.environments as env}
            <tr>
              <td class="px-6 py-4 whitespace-nowrap">{env.name}</td>
              <td class="px-6 py-4 whitespace-nowrap">{env.url}</td>
              <td class="px-6 py-4 whitespace-nowrap">{env.username}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                {#if env.is_default}
                  <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                    {$t.common?.yes}
                  </span>
                {:else}
                  <span class="text-gray-500">{$t.common?.no}</span>
                {/if}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {resolveEnvStage(env) === 'PROD' ? 'bg-red-100 text-red-800' : resolveEnvStage(env) === 'PREPROD' ? 'bg-amber-100 text-amber-800' : 'bg-blue-100 text-blue-800'}">
                  {resolveEnvStage(env)}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button class="text-green-600 hover:text-green-900 mr-4" onclick={() => handleTestEnv(env.id)}>
                  {$t.settings?.env_test}
                </button>
                <button class="text-indigo-600 hover:text-indigo-900 mr-4" onclick={() => editEnv(env)}>
                  {$t.common.edit}
                </button>
                <button class="text-red-600 hover:text-red-900" onclick={() => handleDeleteEnv(env.id)}>
                  {$t.settings?.env_delete}
                </button>
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  {:else if !isAddingEnv}
    <div class="mb-4 p-4 bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700">
      <p class="font-bold">{$t.settings?.warning}</p>
      <p>
        No Superset environments configured. You must add at least one environment to perform backups or migrations.
      </p>
    </div>
  {/if}
</div>
<!-- #endregion EnvironmentsTab -->