<script>
    import { onMount } from 'svelte';
    import { updateGlobalSettings, addEnvironment, updateEnvironment, deleteEnvironment, testEnvironmentConnection, updateStorageSettings } from '../../lib/api';
    import { addToast } from '../../lib/toasts';
    import { t } from '$lib/i18n';
    import { Button, Input, Card, PageHeader } from '$lib/ui';

    /** @type {import('./$types').PageData} */
    export let data;

    let settings = data.settings || {
        environments: [],
        settings: {
            storage: {
                root_path: '',
                backup_structure_pattern: '',
                repo_structure_pattern: '',
                filename_pattern: ''
            }
        }
    };

    $: if (data.settings) {
        settings = { ...data.settings };
        if (settings.settings && !settings.settings.storage) {
            settings.settings.storage = {
                root_path: '',
                backup_structure_pattern: '',
                repo_structure_pattern: '',
                filename_pattern: ''
            };
        }
    }

    let newEnv = {
        id: '',
        name: '',
        url: '',
        username: '',
        password: '',
        is_default: false
    };

    let editingEnvId = null;

    // [DEF:handleSaveGlobal:Function]
    /* @PURPOSE: Saves global application settings.
       @PRE: settings.settings must contain valid configuration.
       @POST: Global settings are updated via API.
    */
    async function handleSaveGlobal() {
        try {
            console.log("[Settings.handleSaveGlobal][Action] Saving global settings.");
            await updateGlobalSettings(settings.settings);
            addToast('Global settings saved', 'success');
            console.log("[Settings.handleSaveGlobal][Coherence:OK] Global settings saved.");
        } catch (error) {
            console.error("[Settings.handleSaveGlobal][Coherence:Failed] Failed to save global settings:", error);
            addToast('Failed to save global settings', 'error');
        }
    }
    // [/DEF:handleSaveGlobal:Function]

    // [DEF:handleSaveStorage:Function]
    /* @PURPOSE: Saves storage-specific settings.
       @PRE: settings.settings.storage must contain valid configuration.
       @POST: Storage settings are updated via API.
    */
    async function handleSaveStorage() {
        try {
            console.log("[Settings.handleSaveStorage][Action] Saving storage settings.");
            await updateStorageSettings(settings.settings.storage);
            addToast('Storage settings saved', 'success');
            console.log("[Settings.handleSaveStorage][Coherence:OK] Storage settings saved.");
        } catch (error) {
            console.error("[Settings.handleSaveStorage][Coherence:Failed] Failed to save storage settings:", error);
            addToast(error.message || 'Failed to save storage settings', 'error');
        }
    }
    // [/DEF:handleSaveStorage:Function]

    // [DEF:handleAddOrUpdateEnv:Function]
    /* @PURPOSE: Adds a new environment or updates an existing one.
       @PRE: newEnv must contain valid environment details.
       @POST: Environment is saved and page is reloaded to reflect changes.
    */
    async function handleAddOrUpdateEnv() {
        try {
            console.log(`[Settings.handleAddOrUpdateEnv][Action] ${editingEnvId ? 'Updating' : 'Adding'} environment.`);
            if (editingEnvId) {
                await updateEnvironment(editingEnvId, newEnv);
                addToast('Environment updated', 'success');
            } else {
                await addEnvironment(newEnv);
                addToast('Environment added', 'success');
            }
            resetEnvForm();
            // In a real app, we might want to invalidate the load function here
            // For now, we'll just manually update the local state or re-fetch
            // But since we are using SvelteKit, we should ideally use invalidateAll()
            location.reload(); // Simple way to refresh data for now
            console.log("[Settings.handleAddOrUpdateEnv][Coherence:OK] Environment saved.");
        } catch (error) {
            console.error("[Settings.handleAddOrUpdateEnv][Coherence:Failed] Failed to save environment:", error);
            addToast('Failed to save environment', 'error');
        }
    }
    // [/DEF:handleAddOrUpdateEnv:Function]

    // [DEF:handleDeleteEnv:Function]
    /* @PURPOSE: Deletes a Superset environment.
       @PRE: id must be a valid environment ID.
       @POST: Environment is removed and page is reloaded.
    */
    async function handleDeleteEnv(id) {
        if (confirm('Are you sure you want to delete this environment?')) {
            try {
                console.log(`[Settings.handleDeleteEnv][Action] Deleting environment: ${id}`);
                await deleteEnvironment(id);
                addToast('Environment deleted', 'success');
                location.reload();
                console.log("[Settings.handleDeleteEnv][Coherence:OK] Environment deleted.");
            } catch (error) {
                console.error("[Settings.handleDeleteEnv][Coherence:Failed] Failed to delete environment:", error);
                addToast('Failed to delete environment', 'error');
            }
        }
    }
    // [/DEF:handleDeleteEnv:Function]

    // [DEF:handleTestEnv:Function]
    /* @PURPOSE: Tests the connection to a Superset environment.
       @PRE: id must be a valid environment ID.
       @POST: Displays success or error toast based on connection result.
    */
    async function handleTestEnv(id) {
        try {
            console.log(`[Settings.handleTestEnv][Action] Testing environment: ${id}`);
            const result = await testEnvironmentConnection(id);
            if (result.status === 'success') {
                addToast('Connection successful', 'success');
                console.log("[Settings.handleTestEnv][Coherence:OK] Connection successful.");
            } else {
                addToast(`Connection failed: ${result.message}`, 'error');
                console.log("[Settings.handleTestEnv][Coherence:Failed] Connection failed.");
            }
        } catch (error) {
            console.error("[Settings.handleTestEnv][Coherence:Failed] Error testing connection:", error);
            addToast('Failed to test connection', 'error');
        }
    }
    // [/DEF:handleTestEnv:Function]

    // [DEF:editEnv:Function]
    /* @PURPOSE: Populates the environment form for editing.
       @PRE: env object must be provided.
       @POST: newEnv and editingEnvId are updated.
    */
    function editEnv(env) {
        newEnv = { ...env };
        editingEnvId = env.id;
    }
    // [/DEF:editEnv:Function]

    // [DEF:resetEnvForm:Function]
    /* @PURPOSE: Resets the environment creation/edit form to default state.
       @PRE: None.
       @POST: newEnv is cleared and editingEnvId is set to null.
    */
    function resetEnvForm() {
        newEnv = {
            id: '',
            name: '',
            url: '',
            username: '',
            password: '',
            is_default: false
        };
        editingEnvId = null;
    }
    // [/DEF:resetEnvForm:Function]
</script>

<div class="container mx-auto p-4">
    <PageHeader title={$t.settings.title} />

    {#if data.error}
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            {data.error}
        </div>
    {/if}


    <div class="mb-8">
        <Card title={$t.settings?.storage_title || "File Storage Configuration"}>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="md:col-span-2">
                    <Input
                        label={$t.settings?.storage_root || "Storage Root Path"}
                        bind:value={settings.settings.storage.root_path}
                    />
                </div>
                <Input
                    label={$t.settings?.storage_backup_pattern || "Backup Directory Pattern"}
                    bind:value={settings.settings.storage.backup_structure_pattern}
                />
                <Input
                    label={$t.settings?.storage_repo_pattern || "Repository Directory Pattern"}
                    bind:value={settings.settings.storage.repo_structure_pattern}
                />
                <Input
                    label={$t.settings?.storage_filename_pattern || "Filename Pattern"}
                    bind:value={settings.settings.storage.filename_pattern}
                />
                <div class="bg-gray-50 p-4 rounded border border-gray-200">
                    <span class="block text-xs font-semibold text-gray-500 uppercase mb-2">{$t.settings?.storage_preview || "Path Preview"}</span>
                    <code class="text-sm text-indigo-600">
                        {settings.settings.storage.root_path}/backups/sample_backup.zip
                    </code>
                </div>
            </div>
            <div class="mt-6">
                <Button on:click={handleSaveStorage}>
                    {$t.common.save}
                </Button>
            </div>
        </Card>
    </div>

    <section class="mb-8">
        <Card title={$t.settings?.env_title || "Superset Environments"}>

    {#if settings.environments.length === 0}
        <div class="mb-4 p-4 bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700">
            <p class="font-bold">Warning</p>
            <p>{$t.settings?.env_warning || "No Superset environments configured."}</p>
        </div>
    {/if}
        
        <div class="mb-6 overflow-x-auto">
            <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 || "Name"}</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">URL</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.connections?.user || "Username"}</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Default</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.git?.actions || "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">{env.is_default ? 'Yes' : 'No'}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <button on:click={() => handleTestEnv(env.id)} class="text-green-600 hover:text-green-900 mr-4">{$t.settings?.env_test || "Test"}</button>
                                <button on:click={() => editEnv(env)} class="text-indigo-600 hover:text-indigo-900 mr-4">{$t.common.edit}</button>
                                <button on:click={() => handleDeleteEnv(env.id)} class="text-red-600 hover:text-red-900">{$t.settings?.env_delete || "Delete"}</button>
                            </td>
                        </tr>
                    {/each}
                </tbody>
            </table>
        </div>

        <div class="mt-8 bg-gray-50 p-6 rounded-lg border border-gray-100">
            <h3 class="text-lg font-medium mb-6">{editingEnvId ? ($t.settings?.env_edit || "Edit Environment") : ($t.settings?.env_add || "Add Environment")}</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Input label="ID" bind:value={newEnv.id} disabled={!!editingEnvId} />
                <Input label={$t.connections?.name || "Name"} bind:value={newEnv.name} />
                <Input label="URL" bind:value={newEnv.url} />
                <Input label={$t.connections?.user || "Username"} bind:value={newEnv.username} />
                <Input label={$t.connections?.pass || "Password"} type="password" bind:value={newEnv.password} />
                <div class="flex items-center gap-2 h-10 mt-auto">
                    <input type="checkbox" id="env_default" bind:checked={newEnv.is_default} class="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500" />
                    <label for="env_default" class="text-sm font-medium text-gray-700">{$t.settings?.env_default || "Default Environment"}</label>
                </div>
            </div>
            <div class="mt-8 flex gap-3">
                <Button on:click={handleAddOrUpdateEnv}>
                    {editingEnvId ? $t.common.save : ($t.settings?.env_add || "Add Environment")}
                </Button>
                {#if editingEnvId}
                    <Button variant="secondary" on:click={resetEnvForm}>
                        {$t.common.cancel}
                    </Button>
                {/if}
            </div>
        </div>
        </Card>
    </section>
</div>
