{% extends "base.html" %}

{% block title %}{{ page_title }} - Kirin{% endblock %}

{% block breadcrumb %}
<span class="breadcrumb-separator">></span>
{% if catalog %}
<a href="/">Catalogs</a>
<span class="breadcrumb-separator">></span>
<span>Edit {{ catalog.name }}</span>
{% else %}
<span>Add Catalog</span>
{% endif %}
{% endblock %}

{% block header_title %}{{ page_title }}{% endblock %}
{% block header_description %}{{ page_description }}{% endblock %}

{% block content %}
<div class="max-w-2xl mx-auto">
    <!-- Error Alert -->
    {% if error %}
    <div class="alert alert-error mb-6">
        <strong>⚠️ {{ error }}</strong>
        {% if existing_catalog_id %}
        <div class="mt-2">
            <a href="/catalog/{{ existing_catalog_id }}" class="btn btn-primary btn-sm">
                Go to Existing Catalog →
            </a>
        </div>
        {% endif %}
    </div>
    {% endif %}

    <div class="panel">
        <div class="panel-header">
            <h2 class="panel-title">Catalog Configuration</h2>
        </div>
        <div class="panel-content">
            <form method="POST" action="{{ form_action }}" class="space-y-6">
                <!-- Catalog Name -->
                <div class="form-group">
                    <label for="name" class="form-label required">Catalog Name</label>
                    <input type="text" id="name" name="name" class="input" placeholder="My Data Catalog"
                           value="{{ catalog.name if catalog else (form_data.name if form_data else '') }}" required>
                    <p class="text-sm text-muted-foreground mt-1">A friendly name for this data catalog</p>
                </div>

                <!-- Root Directory -->
                <div class="form-group">
                    <label for="root_dir" class="form-label required">Root Directory</label>
                    <input type="text" id="root_dir" name="root_dir" class="input"
                           placeholder="/path/to/data or gs://bucket/prefix or s3://bucket/prefix"
                           value="{{ catalog.root_dir if catalog else (form_data.root_dir if form_data else '') }}" required>
                    <p class="text-sm text-muted-foreground mt-1">
                        Local path or cloud URL (gs://, s3://, az://).
                        <a href="#help" onclick="showHelp()" class="underline">See examples</a>
                    </p>
                </div>

                <!-- AWS Profile -->
                <div class="form-group">
                    <label for="aws_profile" class="form-label">AWS Profile</label>
                    <select id="aws_profile" name="aws_profile" class="input">
                        <option value="">Select AWS Profile (optional)</option>
                    </select>
                    <p class="text-sm text-muted-foreground mt-1">
                        AWS profile name for S3 authentication. Leave empty to use default profile or environment variables.
                    </p>
                </div>

                <!-- Authentication Command -->
                <div class="form-group">
                    <label for="auth_command" class="form-label">Authentication Command (Optional)</label>
                    <input type="text" id="auth_command" name="auth_command" class="input"
                           placeholder="aws sso login --profile my-profile or gcloud auth login"
                           value="{{ catalog.auth_command if catalog else (form_data.auth_command if form_data else '') }}">
                    <p class="text-sm text-muted-foreground mt-1">
                        CLI command to authenticate with this catalog's cloud provider (e.g.,
                        <code>aws sso login --profile my-profile</code> or
                        <code>gcloud auth login</code>)
                    </p>
                </div>

                <!-- Help Section -->
                <div id="help-section" class="hidden">
                    <div class="bg-muted p-4 rounded-lg">
                        <h4 class="font-semibold mb-2">Examples:</h4>
                        <ul class="text-sm space-y-1">
                            <li><strong>Local:</strong> <code>/home/user/data</code></li>
                            <li><strong>Google Cloud:</strong> <code>gs://my-bucket/kirin-data</code></li>
                            <li><strong>Amazon S3:</strong> <code>s3://my-bucket/kirin-data</code></li>
                            <li><strong>Azure:</strong> <code>az://my-container/kirin-data</code></li>
                        </ul>
                        <p class="text-sm mt-2 text-muted-foreground">
                            <strong>Note:</strong> Make sure you're authenticated with your cloud provider
                            (gcloud, aws, az CLI) before using cloud URLs.
                        </p>
                    </div>
                </div>

                <!-- Submit Button -->
                <div class="flex gap-3" style="align-items: center;">
                    <button type="submit" class="btn btn-primary" style="margin: 0; vertical-align: top;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path>
                        </svg>
                        {{ submit_button_text }}
                    </button>
                    <a href="/" class="btn btn-secondary" style="margin: 0; vertical-align: top;">
                        Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showHelp() {
    const helpSection = document.getElementById('help-section');
    helpSection.classList.toggle('hidden');
}

// Load AWS profiles and populate dropdown
async function loadAwsProfiles() {
    try {
        const response = await fetch('/api/aws-profiles');
        const data = await response.json();
        const select = document.getElementById('aws_profile');

        // Clear existing options except the first one
        select.innerHTML = '<option value="">Select AWS Profile (optional)</option>';

        // Add profile options
        data.profiles.forEach(profile => {
            const option = document.createElement('option');
            option.value = profile;
            option.textContent = profile;
            select.appendChild(option);
        });

        // Set current value if editing
        const currentValue = select.getAttribute('data-current-value');
        if (currentValue) {
            select.value = currentValue;
        }
    } catch (error) {
        console.error('Failed to load AWS profiles:', error);
    }
}

// Auto-detect storage type from URL
document.getElementById('root_dir').addEventListener('input', function(e) {
    const value = e.target.value;
    const awsProfileField = document.getElementById('aws_profile');

    if (value.startsWith('s3://')) {
        // Show AWS profile field for S3 URLs
        awsProfileField.closest('.form-group').style.display = 'block';
        // Load profiles when S3 URL is detected
        loadAwsProfiles();
    } else {
        // Hide AWS profile field for non-S3 URLs
        awsProfileField.closest('.form-group').style.display = 'none';
        awsProfileField.value = '';
    }
});

// Initialize visibility based on current root_dir value
document.addEventListener('DOMContentLoaded', function() {
    const rootDirField = document.getElementById('root_dir');
    const awsProfileField = document.getElementById('aws_profile');

    // Set current value for editing
    const currentValue = '{{ catalog.aws_profile if catalog else (form_data.aws_profile if form_data else "") }}';
    if (currentValue) {
        awsProfileField.setAttribute('data-current-value', currentValue);
    }

    if (rootDirField.value.startsWith('s3://')) {
        awsProfileField.closest('.form-group').style.display = 'block';
        // Load profiles for S3 URLs
        loadAwsProfiles();
    } else {
        awsProfileField.closest('.form-group').style.display = 'none';
    }
});
</script>
{% endblock %}
