{% extends 'generic/object.html' %}
{% load form_helpers %}

{% block title %}Import Devices from Catalyst Center{% endblock %}

{% block header %}
<h1 class="ps-3 pt-2"><i class="mdi mdi-lan-connect"></i> Import Devices from Catalyst Center</h1>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-9">
        <!-- Search Section -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-magnify"></i> Search Catalyst Center Inventory
                </h5>
            </div>
            <div class="card-body">
                <p class="text-muted">
                    Search for devices in Catalyst Center by hostname, IP address, or MAC address.
                    Use <code>*</code> as a wildcard (e.g., <code>switch*</code> matches devices starting with "switch").
                </p>

                <!-- Search Form -->
                <div class="row g-2 mb-3">
                    <div class="col-md-3">
                        <label class="form-label">Search By</label>
                        <select class="form-select" id="search-type">
                            <option value="hostname">Hostname</option>
                            <option value="ip">IP Address</option>
                            <option value="mac">MAC Address</option>
                        </select>
                    </div>
                    <div class="col-md-7">
                        <label class="form-label">Search Term</label>
                        <input type="text" class="form-control" id="search-value"
                               placeholder="Enter search term (e.g., switch* or 192.168.*)">
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="button" class="btn btn-primary w-100" id="search-btn">
                            <i class="mdi mdi-magnify"></i> Search
                        </button>
                    </div>
                </div>

                <!-- Loading indicator -->
                <div id="search-loading" style="display: none;" class="text-center py-5">
                    <i class="mdi mdi-loading mdi-spin mdi-48px text-primary"></i>
                    <p class="mt-2 text-muted">Searching Catalyst Center inventory...</p>
                </div>

                <!-- Empty state -->
                <div id="empty-state" class="text-center py-5 text-muted">
                    <i class="mdi mdi-server-network mdi-48px"></i>
                    <p class="mt-2">Enter a search term above to find devices in Catalyst Center</p>
                    <p class="small">Examples: <code>switch*</code>, <code>192.168.1.*</code>, <code>*router*</code></p>
                </div>

                <!-- Search Results -->
                <div id="search-results" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <span id="result-count" class="badge bg-info me-2"></span>
                            <span id="result-info" class="text-muted small"></span>
                        </div>
                        <div>
                            <button type="button" class="btn btn-sm btn-outline-secondary" id="select-all-btn">
                                <i class="mdi mdi-checkbox-multiple-marked"></i> Select All New
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" id="deselect-all-btn">
                                <i class="mdi mdi-checkbox-multiple-blank-outline"></i> Deselect All
                            </button>
                        </div>
                    </div>

                    <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                        <table class="table table-sm table-hover" id="results-table">
                            <thead class="sticky-top bg-body">
                                <tr>
                                    <th style="width: 40px;"><input type="checkbox" id="select-all-checkbox" class="form-check-input"></th>
                                    <th>Hostname</th>
                                    <th>Management IP</th>
                                    <th>Platform / Family</th>
                                    <th>Serial Number</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody id="results-body">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Import Options (only shown when results exist) -->
        <div id="import-section" class="card mt-3" style="display: none;">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-cog"></i> Import Options
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Default Site <span class="text-danger">*</span></label>
                        <select class="form-select" id="import-site" required>
                            <option value="">Select a site...</option>
                            {% for site in sites %}
                            <option value="{{ site.pk }}">{{ site.name }}</option>
                            {% endfor %}
                        </select>
                        <div class="form-text">All imported devices will be assigned to this site.</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Device Role</label>
                        <select class="form-select" id="import-role">
                            <option value="">Auto-detect from Catalyst Center</option>
                            {% for role in roles %}
                            <option value="{{ role.pk }}">{{ role.name }}</option>
                            {% endfor %}
                        </select>
                        <div class="form-text">Leave empty to auto-detect from Catalyst Center device family/role.</div>
                    </div>
                </div>

                <div class="row g-3 mt-2">
                    <div class="col-12">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="import-interfaces" checked>
                            <label class="form-check-label" for="import-interfaces">
                                <strong>Sync Interfaces</strong>
                                <br><small class="text-muted">Import all interfaces from Catalyst Center including IPs, speeds, descriptions, LAG membership, and POE settings</small>
                            </label>
                        </div>
                    </div>
                </div>

                <hr class="my-4">

                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <span id="selected-count" class="text-muted">0 devices selected for import</span>
                    </div>
                    <button type="button" class="btn btn-success btn-lg" id="import-btn" disabled>
                        <i class="mdi mdi-import"></i> Import Selected Devices
                    </button>
                </div>
            </div>
        </div>

        <!-- Import Results -->
        <div id="import-results" class="mt-3" style="display: none;"></div>
    </div>

    <!-- Sidebar -->
    <div class="col-md-3">
        <!-- Connection Status -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-lan-connect"></i> Connection Status
                </h5>
            </div>
            <div class="card-body">
                <div id="connection-status">
                    <div class="d-flex align-items-center">
                        <span class="text-muted">Checking connection...</span>
                    </div>
                </div>
                <div class="mt-2">
                    <small class="text-muted">
                        <strong>URL:</strong>
                        {% if config.catalyst_center_url %}
                        <code>{{ config.catalyst_center_url }}</code>
                        {% else %}
                        <span class="text-danger">Not configured</span>
                        {% endif %}
                    </small>
                </div>
            </div>
        </div>

        <!-- Help -->
        <div class="card mt-3">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-help-circle"></i> Search Tips
                </h5>
            </div>
            <div class="card-body">
                <h6>Wildcard Patterns</h6>
                <ul class="small mb-3">
                    <li><code>switch*</code> - Starts with "switch"</li>
                    <li><code>*router*</code> - Contains "router"</li>
                    <li><code>192.168.*</code> - IP in 192.168.x.x range</li>
                </ul>

                <h6>What Gets Imported</h6>
                <ul class="small mb-0">
                    <li>Hostname (domain stripped)</li>
                    <li>Serial number</li>
                    <li>Management IP</li>
                    <li>Device type (from platform)</li>
                    <li>Device role (auto-detected)</li>
                    <li>Platform (software type/version)</li>
                    <li>SNMP location (in comments)</li>
                    <li>Custom fields (CC ID, series, role)</li>
                </ul>
                <h6 class="mt-2">With "Sync Interfaces"</h6>
                <ul class="small mb-0">
                    <li>All network interfaces</li>
                    <li>IP addresses on interfaces</li>
                    <li>LAG/Port-channel membership</li>
                    <li>Speed, MTU, duplex settings</li>
                    <li>POE mode and type</li>
                </ul>
            </div>
        </div>

        <!-- Import Only Warning -->
        <div class="card mt-3 border-info">
            <div class="card-body">
                <h6 class="card-title text-info">
                    <i class="mdi mdi-information"></i> One-Way Import
                </h6>
                <p class="card-text small mb-2">
                    This is a <strong>one-way import only</strong>. Devices are created in NetBox
                    but changes made in NetBox are not synced back to Catalyst Center.
                    Maximum <strong>25 devices</strong> can be imported at a time.
                </p>
                <p class="card-text small mb-0">
                    <i class="mdi mdi-sync"></i> After import, use the <strong>Catalyst Center</strong> tab on each device
                    to sync additional fields like serial number, platform, and interfaces.
                </p>
            </div>
        </div>

        <!-- Existing Devices Note -->
        <div class="card mt-3 border-warning">
            <div class="card-body">
                <h6 class="card-title text-warning">
                    <i class="mdi mdi-alert"></i> Note
                </h6>
                <p class="card-text small mb-0">
                    Devices already in NetBox (matched by hostname or serial) are shown
                    with a green "In NetBox" badge and cannot be selected for import.
                </p>
            </div>
        </div>
    </div>
</div>

<script>
// Check connection on page load
document.addEventListener('DOMContentLoaded', function() {
    checkConnection();
});

function checkConnection() {
    var statusDiv = document.getElementById('connection-status');

    fetch('{% url "plugins:netbox_catalyst_center:test_connection" %}', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            statusDiv.innerHTML = '<div class="d-flex align-items-center">' +
                '<i class="mdi mdi-check-circle text-success me-2"></i>' +
                '<span class="text-success">Connected</span></div>' +
                '<small class="text-muted mt-1">' + data.message + '</small>';
        } else {
            statusDiv.innerHTML = '<div class="d-flex align-items-center">' +
                '<i class="mdi mdi-alert-circle text-danger me-2"></i>' +
                '<span class="text-danger">Connection Failed</span></div>' +
                '<small class="text-danger mt-1">' + data.error + '</small>';
        }
    })
    .catch(error => {
        statusDiv.innerHTML = '<div class="d-flex align-items-center">' +
            '<i class="mdi mdi-alert-circle text-danger me-2"></i>' +
            '<span class="text-danger">Error</span></div>' +
            '<small class="text-danger mt-1">' + error + '</small>';
    });
}

// Device Search
var searchResults = [];

document.getElementById('search-btn').addEventListener('click', function() {
    var searchType = document.getElementById('search-type').value;
    var searchValue = document.getElementById('search-value').value.trim();

    if (!searchValue) {
        alert('Please enter a search term');
        return;
    }

    // Show loading, hide others
    document.getElementById('search-loading').style.display = 'block';
    document.getElementById('search-results').style.display = 'none';
    document.getElementById('import-section').style.display = 'none';
    document.getElementById('empty-state').style.display = 'none';

    var url = '{% url "plugins:netbox_catalyst_center:search_devices" %}?search_type=' +
        encodeURIComponent(searchType) + '&search_value=' + encodeURIComponent(searchValue);

    fetch(url, {
        method: 'GET',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('search-loading').style.display = 'none';

        if (data.error) {
            alert('Search error: ' + data.error);
            document.getElementById('empty-state').style.display = 'block';
            return;
        }

        searchResults = data.devices || [];

        if (searchResults.length === 0) {
            document.getElementById('empty-state').innerHTML =
                '<i class="mdi mdi-magnify-close mdi-48px"></i>' +
                '<p class="mt-2">No devices found matching your search</p>' +
                '<p class="small">Try a different search term or pattern</p>';
            document.getElementById('empty-state').style.display = 'block';
            return;
        }

        renderSearchResults(searchResults, data.total_in_dnac);
        document.getElementById('search-results').style.display = 'block';
        document.getElementById('import-section').style.display = 'block';
    })
    .catch(error => {
        document.getElementById('search-loading').style.display = 'none';
        document.getElementById('empty-state').style.display = 'block';
        alert('Search failed: ' + error);
    });
});

// Allow Enter key in search box
document.getElementById('search-value').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        document.getElementById('search-btn').click();
    }
});

function renderSearchResults(devices, totalInDnac) {
    var tbody = document.getElementById('results-body');
    tbody.innerHTML = '';

    // Count new vs existing
    var newCount = devices.filter(d => !d.exists_in_netbox).length;
    var existingCount = devices.filter(d => d.exists_in_netbox).length;

    document.getElementById('result-count').textContent = devices.length + ' device' + (devices.length !== 1 ? 's' : '') + ' found';
    document.getElementById('result-count').className = 'badge bg-primary me-2';
    document.getElementById('result-info').textContent =
        '(' + newCount + ' new, ' + existingCount + ' already in NetBox, ' + totalInDnac + ' total in inventory)';

    devices.forEach(function(device, index) {
        var row = document.createElement('tr');
        if (device.exists_in_netbox) {
            row.classList.add('table-secondary');
        }

        var checkbox = device.exists_in_netbox
            ? '<input type="checkbox" class="form-check-input" disabled title="Already exists in NetBox">'
            : '<input type="checkbox" class="form-check-input device-checkbox" data-index="' + index + '">';

        var statusBadge = device.exists_in_netbox
            ? '<a href="' + device.netbox_device_url + '" class="badge bg-success text-white text-decoration-none"><i class="mdi mdi-check"></i> In NetBox</a>'
            : '<span class="badge bg-warning text-dark">New</span>';

        var reachability = device.reachability_status === 'Reachable'
            ? '<i class="mdi mdi-check-circle text-success" title="Reachable"></i>'
            : '<i class="mdi mdi-alert-circle text-warning" title="' + (device.reachability_status || 'Unknown') + '"></i>';

        var roleDisplay = device.role || device.device_family || '-';

        var stackBadge = device.is_stack
            ? ' <span class="badge bg-info text-white" title="' + device.stack_count + '-member stack"><i class="mdi mdi-layers-triple"></i> Stack (' + device.stack_count + ')</span>'
            : '';

        row.innerHTML =
            '<td>' + checkbox + '</td>' +
            '<td><strong>' + (device.hostname || 'N/A') + '</strong> ' + reachability + stackBadge + '</td>' +
            '<td><code>' + (device.management_ip || 'N/A') + '</code></td>' +
            '<td><small>' + (device.platform || device.device_family || 'N/A') + '</small></td>' +
            '<td><small><code>' + (device.serial_number || 'N/A') + '</code></small></td>' +
            '<td><small>' + roleDisplay + '</small></td>' +
            '<td>' + statusBadge + '</td>';

        tbody.appendChild(row);
    });

    updateSelectedCount();
}

// Checkbox handlers
document.getElementById('results-body').addEventListener('change', function(e) {
    if (e.target.classList.contains('device-checkbox')) {
        updateSelectedCount();
    }
});

document.getElementById('select-all-checkbox').addEventListener('change', function() {
    var checked = this.checked;
    document.querySelectorAll('.device-checkbox').forEach(function(cb) {
        cb.checked = checked;
    });
    updateSelectedCount();
});

document.getElementById('select-all-btn').addEventListener('click', function() {
    document.querySelectorAll('.device-checkbox').forEach(function(cb) {
        cb.checked = true;
    });
    document.getElementById('select-all-checkbox').checked = true;
    updateSelectedCount();
});

document.getElementById('deselect-all-btn').addEventListener('click', function() {
    document.querySelectorAll('.device-checkbox').forEach(function(cb) {
        cb.checked = false;
    });
    document.getElementById('select-all-checkbox').checked = false;
    updateSelectedCount();
});

var MAX_IMPORT_LIMIT = 25;

function updateSelectedCount() {
    var count = document.querySelectorAll('.device-checkbox:checked').length;
    var total = document.querySelectorAll('.device-checkbox').length;
    var countText = count + ' of ' + total + ' devices selected for import';

    if (count > MAX_IMPORT_LIMIT) {
        countText += ' (max ' + MAX_IMPORT_LIMIT + ')';
        document.getElementById('selected-count').innerHTML = '<span class="text-danger">' + countText + '</span>';
        document.getElementById('import-btn').disabled = true;
    } else {
        document.getElementById('selected-count').textContent = countText;
        document.getElementById('import-btn').disabled = count === 0;
    }
}

// Import button
document.getElementById('import-btn').addEventListener('click', function() {
    var siteId = document.getElementById('import-site').value;
    if (!siteId) {
        alert('Please select a default site');
        document.getElementById('import-site').focus();
        return;
    }

    var selectedDevices = [];
    document.querySelectorAll('.device-checkbox:checked').forEach(function(cb) {
        var index = parseInt(cb.getAttribute('data-index'));
        selectedDevices.push(searchResults[index]);
    });

    if (selectedDevices.length === 0) {
        alert('Please select at least one device');
        return;
    }

    if (selectedDevices.length > MAX_IMPORT_LIMIT) {
        alert('Maximum ' + MAX_IMPORT_LIMIT + ' devices can be imported at a time. Please deselect some devices.');
        return;
    }

    var syncInterfaces = document.getElementById('import-interfaces').checked;
    var confirmMsg = 'Import ' + selectedDevices.length + ' device(s) to NetBox?\n\n';
    if (syncInterfaces) {
        confirmMsg += 'This will create device records with all interfaces, IPs, and LAG membership from Catalyst Center.';
    } else {
        confirmMsg += 'This will create device records with a basic management interface.';
    }
    if (!confirm(confirmMsg)) {
        return;
    }

    var btn = this;
    btn.disabled = true;
    btn.innerHTML = '<i class="mdi mdi-loading mdi-spin"></i> Importing...';

    var roleId = document.getElementById('import-role').value;

    fetch('{% url "plugins:netbox_catalyst_center:import_devices" %}', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            devices: selectedDevices,
            default_site_id: parseInt(siteId),
            default_role_id: roleId ? parseInt(roleId) : null,
            sync_interfaces: document.getElementById('import-interfaces').checked
        })
    })
    .then(response => response.json())
    .then(data => {
        var resultsDiv = document.getElementById('import-results');
        resultsDiv.style.display = 'block';

        if (data.error) {
            resultsDiv.innerHTML = '<div class="alert alert-danger">' +
                '<i class="mdi mdi-alert-circle"></i> <strong>Import Failed:</strong> ' + data.error + '</div>';
        } else {
            var html = '<div class="alert ' + (data.error_count > 0 ? 'alert-warning' : 'alert-success') + '">' +
                '<h5><i class="mdi mdi-check-circle"></i> Import Complete</h5>' +
                '<p class="mb-0">Created: <strong>' + data.created_count + '</strong> | ' +
                'Skipped: <strong>' + data.skipped_count + '</strong> | ' +
                'Errors: <strong>' + data.error_count + '</strong></p>' +
                '</div>';

            if (data.results.created.length > 0) {
                html += '<div class="card mb-2"><div class="card-header bg-success text-white">Created Devices</div>' +
                    '<ul class="list-group list-group-flush">';
                data.results.created.forEach(function(d) {
                    var stats = [];
                    if (d.interface_count) {
                        stats.push('<i class="mdi mdi-ethernet text-primary"></i> <strong>' + d.interface_count + '</strong> interfaces');
                    }
                    if (d.poe_count) {
                        stats.push('<i class="mdi mdi-flash text-warning"></i> <strong>' + d.poe_count + '</strong> POE ports');
                    }
                    var statsHtml = stats.length > 0 ? '<br><small>' + stats.join(' &nbsp;|&nbsp; ') + '</small>' : '';

                    // Check if this is a virtual chassis import
                    var vcBadge = d.virtual_chassis
                        ? ' <span class="badge bg-info text-white"><i class="mdi mdi-layers-triple"></i> Virtual Chassis (' + d.member_count + ' members)</span>'
                        : '';

                    // Show appropriate view button(s)
                    var viewButtons = '';
                    if (d.virtual_chassis && d.virtual_chassis_id) {
                        viewButtons = '<a href="/dcim/virtual-chassis/' + d.virtual_chassis_id + '/" class="btn btn-sm btn-outline-info me-1"><i class="mdi mdi-layers-triple"></i> View VC</a>' +
                            '<a href="/dcim/devices/' + d.netbox_id + '/" class="btn btn-sm btn-outline-primary">View Master</a>';
                    } else {
                        viewButtons = '<a href="/dcim/devices/' + d.netbox_id + '/" class="btn btn-sm btn-outline-primary">View</a>';
                    }

                    html += '<li class="list-group-item d-flex justify-content-between align-items-center">' +
                        '<div><i class="mdi mdi-check text-success me-2"></i><strong>' + d.hostname + '</strong> <span class="text-muted">(' + d.device_type + ')</span>' + vcBadge + statsHtml + '</div>' +
                        '<div>' + viewButtons + '</div></li>';
                });
                html += '</ul></div>';
            }

            if (data.results.skipped.length > 0) {
                html += '<div class="card mb-2"><div class="card-header bg-warning">Skipped Devices</div>' +
                    '<ul class="list-group list-group-flush">';
                data.results.skipped.forEach(function(d) {
                    html += '<li class="list-group-item">' +
                        '<i class="mdi mdi-skip-next text-warning me-2"></i>' + d.hostname + ' - ' + d.reason + '</li>';
                });
                html += '</ul></div>';
            }

            if (data.results.errors.length > 0) {
                html += '<div class="card mb-2"><div class="card-header bg-danger text-white">Errors</div>' +
                    '<ul class="list-group list-group-flush">';
                data.results.errors.forEach(function(d) {
                    html += '<li class="list-group-item list-group-item-danger">' +
                        '<i class="mdi mdi-alert text-danger me-2"></i>' + d.hostname + ' - ' + d.error + '</li>';
                });
                html += '</ul></div>';
            }

            resultsDiv.innerHTML = html;

            // Refresh search to update "exists" status
            if (data.created_count > 0) {
                setTimeout(function() {
                    document.getElementById('search-btn').click();
                }, 1000);
            }
        }
    })
    .catch(error => {
        document.getElementById('import-results').innerHTML =
            '<div class="alert alert-danger"><i class="mdi mdi-alert-circle"></i> Import failed: ' + error + '</div>';
        document.getElementById('import-results').style.display = 'block';
    })
    .finally(function() {
        btn.disabled = false;
        btn.innerHTML = '<i class="mdi mdi-import"></i> Import Selected Devices';
        updateSelectedCount();
    });
});
</script>
{% endblock %}
