/**
 * PopupComponent
 * A specialized popup component for connection management
 */
Vue.component('popup-component', {
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        connections: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            newConnection: {
                Id: 0,
                Name: "",
                ConnectionString: "",
                PlatformType: "SharePoint",
                DefaultMediaHost: ""
            }
        };
    },
    methods: {
        blankConnectionForm() {
            return {
                Id: 0,
                Name: "",
                ConnectionString: "",
                PlatformType: "SharePoint",
                DefaultMediaHost: ""
            };
        },
        loadConnectionForEdit(cs) {
            this.newConnection = {
                Id: cs && cs.id != null ? cs.id : 0,
                Name: (cs && cs.name) || "",
                ConnectionString: (cs && cs.connectionString) || "",
                PlatformType:
                    (cs && (cs.platform != null ? cs.platform : cs.PlatformType)) || "SharePoint",
                DefaultMediaHost:
                    (cs && (cs.defaultMediaHost != null ? cs.defaultMediaHost : cs.DefaultMediaHost)) || ""
            };
        },
        cancelConnectionEdit() {
            this.newConnection = this.blankConnectionForm();
        },
        CloseModal() {
            this.$emit("CloseModal");
        },
        ConnectTo(connection) {
            this.$emit("ConnectTo", connection);
        },
        async SaveConnectionString() {
            try {
                var payload = {
                    Id: this.newConnection.Id,
                    Name: this.newConnection.Name,
                    ConnectionString: this.newConnection.ConnectionString,
                    PlatformType: this.newConnection.PlatformType,
                    DefaultMediaHost:
                        this.newConnection.DefaultMediaHost &&
                        String(this.newConnection.DefaultMediaHost).trim()
                            ? String(this.newConnection.DefaultMediaHost).trim()
                            : null
                };
                await fetch("/api/ContentTree/UpdateConnectionString", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });
                this.$emit('connection-saved');
                this.newConnection = this.blankConnectionForm();
                Helpers.showNotification('Connection saved successfully', 'success');
            } catch (error) {
                console.error('Error saving connection:', error);
                Helpers.showNotification('Error saving connection', 'error');
            }
        },
        async DeleteConnection(connection) {
            if (confirm("Are you sure you want to delete this connection?")) {
                try {
                    await fetch(`/api/ContentTree/DeleteConnectionString?id=${connection.id}`);
                    this.$emit('connection-deleted');
                    Helpers.showNotification('Connection deleted successfully', 'success');
                } catch (error) {
                    console.error('Error deleting connection:', error);
                    Helpers.showNotification('Error deleting connection', 'error');
                }
            }
        }
    },
    template: `
        <div class="modal fade" id="manage-connections" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ newConnection.Id > 0 ? 'Edit connection' : 'Manage Connections' }}</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close" @click="CloseModal">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <h4>Existing Connections ({{connections.length}}):</h4>
                        <table class="table table-striped table-hover table-bordered mb-3">
                            <thead class="table-dark">
                                <tr>
                                    <th scope="col">Id</th>
                                    <th scope="col">Name</th>
                                    <th scope="col">Platform</th>
                                    <th scope="col">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(cs, csIdx) in connections">
                                    <td>{{cs.id}}</td>
                                    <td>{{cs.name}}</td>
                                    <td>{{cs.platform}}</td>
                                    <td>
                                        <span style="cursor:pointer" @click="ConnectTo(cs)">Connect</span> |
                                        <span style="cursor:pointer" @click="loadConnectionForEdit(cs)">Edit</span> |
                                        <span class="text-danger" style="cursor:pointer" @click="DeleteConnection(cs)">Delete</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>

                        <h4 class="mt-5 mb-2">{{ newConnection.Id > 0 ? 'Edit selected connection:' : 'Add New Connection:' }}</h4>
                        <div class="form-group">
                            <label for="popupCsName">Name</label>
                            <input v-model="newConnection.Name" type="text" class="form-control" id="popupCsName" required>
                        </div>
                        <div class="form-group">
                            <label for="popupCsConn">Connection String:</label>
                            <input v-model="newConnection.ConnectionString" type="password" class="form-control" id="popupCsConn" required autocomplete="off">
                        </div>
                        <div class="form-group">
                            <label for="popupCsMedia">Media base URL (optional, Umbraco)</label>
                            <input v-model="newConnection.DefaultMediaHost" type="text" class="form-control" id="popupCsMedia" placeholder="https://..." autocomplete="off">
                        </div>
                        <button v-if="newConnection.Id > 0" type="button" class="btn btn-outline-secondary btn-sm mb-2" @click="cancelConnectionEdit">Cancel edit</button>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" @click="SaveConnectionString">Save</button>
                        <button type="button" class="btn btn-secondary" @click="CloseModal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `,
    watch: {
        visible: {
            immediate: true,
            handler(newVal) {
                try {
                    if (window.jQuery && window.jQuery.fn.modal) {
                        if (newVal) {
                            window.jQuery('#manage-connections').modal('show');
                        } else {
                            window.jQuery('#manage-connections').modal('hide');
                        }
                    } else {
                        console.error('jQuery or Bootstrap modal not available');
                    }
                } catch (e) {
                    console.error('Error toggling modal:', e);
                }
            }
        }
    }
}); 