{% extends "layouts/base.html" %}

{% block title %}Company Files{% endblock %}
{% block extra_css %}
<style>
    .files-section {
        padding: 20px;
    }

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .files-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 20px;
    }

    .file-card,
    .folder-card {
        background: white;
        border-radius: 8px;
        padding: 15px;
        display: flex;
        align-items: center;
        gap: 15px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        cursor: pointer;
    }

    .folder-card {
        background: #f8f9fa;
    }

    .file-icon,
    .folder-icon {
        font-size: 2em;
    }

    .file-icon {
        color: #dc3545;
    }

    .folder-icon {
        color: #0d6efd;
    }

    .file-info,
    .folder-info {
        flex-grow: 1;
        width: 130px;
    }

    .file-info h4,
    .folder-info h4 {
        margin: 0;
        font-size: 1em;
        color: #333;
    }

    .file-info p {
        margin: 5px 0 0;
        font-size: 0.8em;
        color: #666;
    }

    .file-actions,
    .folder-actions {
        display: flex;
        gap: 10px;
    }

    .no-files {
        grid-column: 1 / -1;
        text-align: center;
        padding: 40px;
        background: white;
        border-radius: 8px;
        color: #666;
    }

    .no-files i {
        font-size: 3em;
        margin-bottom: 10px;
    }

    .breadcrumb {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 20px;
        padding: 10px;
        background: white;
        border-radius: 8px;
    }

    .breadcrumb-item {
        display: flex;
        align-items: center;
        gap: 5px;
        color: #666;
        text-decoration: none;
    }

    .breadcrumb-item:hover {
        color: #0d6efd;
    }

    .breadcrumb-separator {
        color: #666;
    }

    .modal {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        width: 100%;
        height: max-content;
        transform: translate(-50%, -50%);
        box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
    }

    .modal-content {
        background: white;
        width: 500px;
        margin: 10px auto;
        padding: 20px;
        border-radius: 8px;
    }

    .modal-content input {
        width: 100%;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        margin: 10px 0;
    }

    .modal::-webkit-scrollbar {
        display: none;
    }

    /* Pagination Styles */
    .pagination-container {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 30px;
        gap: 10px;
    }

    .pagination {
        display: flex;
        list-style: none;
        margin: 0;
        padding: 0;
        gap: 5px;
    }

    .pagination li {
        display: inline-block;
    }

    .pagination a,
    .pagination span {
        display: block;
        padding: 8px 12px;
        text-decoration: none;
        color: #333;
        border: 1px solid #ddd;
        border-radius: 4px;
        transition: all 0.3s;
    }

    .pagination a:hover {
        background-color: #f5f5f5;
        border-color: #0d6efd;
    }

    .pagination .active span {
        background-color: #0d6efd;
        color: white;
        border-color: #0d6efd;
    }

    .pagination .disabled span {
        color: #ccc;
        cursor: not-allowed;
    }

    .pagination-info {
        color: #666;
        font-size: 0.9em;
    }

    /* File actions improvements */
    .file-actions .action-button,
    .folder-actions .action-button {
        padding: 5px 8px;
        font-size: 0.8em;
    }
    
    .folder-actions {
        display: flex;
        gap: 5px;
    }

    .limit-info {
        margin-bottom: 20px;
        padding: 12px 16px;
        background: white;
        border-radius: 8px;
        display: flex;
        align-items: center;
        gap: 12px;
        color: #0f172a;
        box-shadow: 0 1px 2px rgba(15, 23, 42, 0.05);
    }

    .limit-info i {
        font-size: 1.2em;
        color: #0d6efd;
    }

    .limit-info span {
        font-size: 0.95em;
    }
</style>
{% endblock %}

{% block content %}
<div class="files-section">
    <div class="section-header">
        <h2>Company Files</h2>
        <div class="header-actions">
            <button type="button" class="action-button primary" onclick="showCreateFolderModal()">
                <i class="fa-light fa-folder-plus"></i>
                <span>New Folder</span>
            </button>
            <button type="button" class="action-button primary"
                onclick="document.getElementById('upload-file').click()">
                <i class="fa-light fa-upload"></i>
                <span>Upload New File</span>
            </button>
            
            <!-- New refresh button -->
            <button type="button" class="action-button secondary" onclick="refreshVectorStore()">
                <i class="fa-light fa-refresh"></i>
                <span>Refresh AI Knowledge</span>
            </button>
            
            <input type="file" id="upload-file" style="display: none" accept=".pdf,.docx" multiple>
        </div>
    </div>

    <div id="fileLimitInfo" class="limit-info">
        <i class="fa-light fa-database"></i>
        {% if file_limit is none %}
            <span>You have unlimited file uploads{% if active_package_title %} ({{ active_package_title }}){% endif %}.</span>
        {% else %}
            <span>
                {% if active_package_title %}
                    Current package <strong>{{ active_package_title }}</strong> allows {{ file_limit }} file(s).
                {% else %}
                    Free tier allows {{ file_limit }} file(s).
                {% endif %}
                You have {{ remaining_files if remaining_files is not none else 0 }} upload(s) remaining{% if remaining_days is not none %} and {{ remaining_days }} day{% if remaining_days != 1 %}s{% endif %} left on the plan{% endif %}.
            </span>
        {% endif %}
    </div>

    <div class="breadcrumb">
        <a href="/company/files" class="breadcrumb-item">
            <i class="fa-light fa-home"></i>
            Root
        </a>
        {% for folder in breadcrumb %}
        <span class="breadcrumb-separator">/</span>
        <a href="/company/files?folder={{ folder.id }}" class="breadcrumb-item">
            <i class="fa-light fa-folder"></i>
            {{ folder.name }}
        </a>
        {% endfor %}
    </div>

    <div class="files-grid">
        {% for folder in folders %}
        <div class="folder-card" onclick="navigateToFolder('{{ folder[0] }}')">
            <div class="folder-icon">
                <i class="fa-light fa-folder"></i>
            </div>
            <div class="folder-info">
                <h4>{{ folder[1] }}</h4>
            </div>
            <div class="folder-actions">
                <button class="action-button secondary" onclick="editFolder('{{ folder[0] }}', '{{ folder[1] }}', event)" title="Edit">
                    <i class="fa-light fa-edit"></i>
                </button>
                <button class="action-button danger" onclick="deleteFolder('{{ folder[0] }}', event)" title="Delete">
                    <i class="fa-light fa-trash"></i>
                </button>
            </div>
        </div>
        {% endfor %}

        {% for doc in documents %}
        <div class="file-card">
            <div class="file-icon">
                {% if doc[1].endswith('.pdf') %}
                <i class="fa-light fa-file-pdf"></i>
                {% elif doc[1].endswith('.docx') or doc[1].endswith('.doc') %}
                <i class="fa-light fa-file-word"></i>
                {% else %}
                <i class="fa-light fa-file"></i>
                {% endif %}
            </div>
            <div class="file-info">
                <h4>{{ doc[1] }}</h4>
                <p>Uploaded: {{ doc[2].strftime('%Y-%m-%d %H:%M') }}</p>
            </div>
            <div class="file-actions">
                <button class="action-button danger" onclick="deleteFile('{{ doc[0] }}')" title="Delete">
                    <i class="fa-light fa-trash"></i>
                </button>
            </div>
        </div>
        {% endfor %}

        {% if not folders and not documents %}
        <div class="no-files">
            <i class="fa-light fa-folder-open"></i>
            <p>No files or folders in this location</p>
        </div>
        {% endif %}
    </div>

    <!-- Pagination -->
    {% if pagination %}
    <div class="pagination-container">
        <div class="pagination-info">
            Showing {{ pagination.start_item }} to {{ pagination.end_item }} of {{ pagination.total_items }} items
        </div>
        <ul class="pagination">
            {% if pagination.has_prev %}
            <li><a href="{{ url_for('company.files', folder=current_folder_id, page=pagination.prev_num) }}">&laquo; Previous</a></li>
            {% else %}
            <li class="disabled"><span>&laquo; Previous</span></li>
            {% endif %}

            {% for page_num in pagination.iter_pages() %}
                {% if page_num %}
                    {% if page_num != pagination.page %}
                    <li><a href="{{ url_for('company.files', folder=current_folder_id, page=page_num) }}">{{ page_num }}</a></li>
                    {% else %}
                    <li class="active"><span>{{ page_num }}</span></li>
                    {% endif %}
                {% else %}
                <li class="disabled"><span>...</span></li>
                {% endif %}
            {% endfor %}

            {% if pagination.has_next %}
            <li><a href="{{ url_for('company.files', folder=current_folder_id, page=pagination.next_num) }}">Next &raquo;</a></li>
            {% else %}
            <li class="disabled"><span>Next &raquo;</span></li>
            {% endif %}
        </ul>
    </div>
    {% endif %}
</div>

<!-- Create Folder Modal -->
<div id="createFolderModal" class="modal" style="display: none;">
    <div class="modal-backdrop"></div>
    <div class="modal-content">
        <h3>Create New Folder</h3>
        <input type="text" id="folderName" placeholder="Enter folder name">
        <div class="modal-actions">
            <button id="createFolderBtn" onclick="createFolder()" class="action-button primary">
                <span id="createFolderText">Create</span>
                <span id="createFolderLoader" style="display: none;">
                    <i class="fa-light fa-spinner fa-spin"></i>
                    Creating...
                </span>
            </button>
            <button onclick="closeCreateFolderModal()" class="action-button">Cancel</button>
        </div>
    </div>
</div>

<!-- Edit Folder Modal -->
<div id="editFolderModal" class="modal" style="display: none;">
    <div class="modal-backdrop"></div>
    <div class="modal-content">
        <h3>Edit Folder Name</h3>
        <input type="text" id="editFolderName" placeholder="Enter new folder name">
        <div class="modal-actions">
            <button id="editFolderBtn" onclick="updateFolder()" class="action-button primary">
                <span id="editFolderText">Update</span>
                <span id="editFolderLoader" style="display: none;">
                    <i class="fa-light fa-spinner fa-spin"></i>
                    Updating...
                </span>
            </button>
            <button onclick="closeEditFolderModal()" class="action-button">Cancel</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentFolderId = '{{ current_folder_id if current_folder_id else "null" }}';

    // Handle file upload
    document.getElementById('upload-file').addEventListener('change', async (e) => {
        const files = e.target.files;
        if (!files.length) return;

        const formData = new FormData();
        for (let file of files) {
            formData.append('documents[]', file);
        }
        formData.append('folder_id', currentFolderId);

        try {
            const response = await fetch('/company/upload-document', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();
            if (data.success) {
                showNotification('File Uploaded successfully', 'success');
                if (typeof data.remaining_files !== 'undefined' && data.remaining_files !== null) {
                    const info = document.getElementById('fileLimitInfo');
                    if (info) {
                        info.innerHTML = `<i class="fa-light fa-database"></i><span>You have ${data.remaining_files} upload(s) remaining on your plan.</span>`;
                    }
                }
                location.reload();
            } else {
                // alert('Error uploading files: ' + data.error);
                showNotification('Error uploading files: ' + data.error, 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            // alert('Error uploading files');
            showNotification('Error uploading files', 'error');
        }
    });

    // Handle file deletion
    async function deleteFile(fileId) {
        if (!confirm('Are you sure you want to delete this file?')) return;

        try {
            const response = await fetch(`/company/delete-document/${fileId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                showNotification('File Deleted successfully', 'success');
                location.reload();
            } else {
                showNotification('Error deleting file', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification('Error deleting file', 'error');
        }
    }

    // Folder functions
    function showCreateFolderModal() {
        console.log(currentFolderId);

        document.getElementById('createFolderModal').style.display = 'block';
    }

    function closeCreateFolderModal() {
        document.getElementById('createFolderModal').style.display = 'none';
    }

    async function createFolder() {
        const folderName = document.getElementById('folderName').value.trim();
        if (!folderName) {
            showNotification('Please enter a folder name', 'error');
            return;
        }

        // Get button elements
        const createBtn = document.getElementById('createFolderBtn');
        const createText = document.getElementById('createFolderText');
        const createLoader = document.getElementById('createFolderLoader');

        // Show loading state
        createBtn.disabled = true;
        createText.style.display = 'none';
        createLoader.style.display = 'inline';

        try {
            const response = await fetch('/company/create-folder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: folderName,
                    parent_id: currentFolderId || null
                })
            });

            const data = await response.json();
            if (data.success) {
                showNotification('Folder created successfully', 'success');
                location.reload();
            } else {
                showNotification('Error creating folder: ' + data.error, 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification('Error creating folder', 'error');
        } finally {
            // Reset button state
            createBtn.disabled = false;
            createText.style.display = 'inline';
            createLoader.style.display = 'none';
        }
    }

    async function deleteFolder(folderId, event) {
        event.stopPropagation();
        if (!confirm('Are you sure you want to delete this folder and all its contents?')) return;

        try {
            const response = await fetch(`/company/delete-folder/${folderId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                showNotification('Folder deleted successfully', 'success');
                location.reload();
            } else {
                showNotification('Error deleting folder', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification('Error deleting folder', 'error');
        }
    }

    function navigateToFolder(folderId) {
        window.location.href = `/company/files?folder=${folderId}`;
    }

    // Edit folder functions
    let editingFolderId = null;

    function editFolder(folderId, currentName, event) {
        event.stopPropagation();
        editingFolderId = folderId;
        document.getElementById('editFolderName').value = currentName;
        document.getElementById('editFolderModal').style.display = 'block';
    }

    function closeEditFolderModal() {
        document.getElementById('editFolderModal').style.display = 'none';
        editingFolderId = null;
        document.getElementById('editFolderName').value = '';
    }

    async function updateFolder() {
        const newName = document.getElementById('editFolderName').value.trim();
        if (!newName) {
            showNotification('Please enter a folder name', 'error');
            return;
        }

        if (!editingFolderId) {
            showNotification('No folder selected for editing', 'error');
            return;
        }

        // Get button elements
        const editBtn = document.getElementById('editFolderBtn');
        const editText = document.getElementById('editFolderText');
        const editLoader = document.getElementById('editFolderLoader');

        // Show loading state
        editBtn.disabled = true;
        editText.style.display = 'none';
        editLoader.style.display = 'inline';

        try {
            const response = await fetch(`/company/edit-folder/${editingFolderId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: newName
                })
            });

            const data = await response.json();
            if (data.success) {
                showNotification('Folder updated successfully', 'success');
                closeEditFolderModal();
                location.reload();
            } else {
                showNotification('Error updating folder: ' + data.error, 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification('Error updating folder', 'error');
        } finally {
            // Reset button state
            editBtn.disabled = false;
            editText.style.display = 'inline';
            editLoader.style.display = 'none';
        }
    }

    async function refreshVectorStore() {
        if (!confirm('This will refresh the AI knowledge base with all your documents. This may take a few moments. Continue?')) {
            return;
        }
        
        const button = event.target.closest('button');
        const originalText = button.innerHTML;
        
        try {
            // Show loading state
            button.innerHTML = '<i class="fa-light fa-spinner fa-spin"></i><span>Refreshing...</span>';
            button.disabled = true;
            
            const response = await fetch('/company/refresh-vector-store', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const data = await response.json();
            
            if (data.success) {
                showNotification(`AI Knowledge refreshed successfully! Processed ${data.details.documents_processed} documents.`, 'success');
            } else {
                showNotification(`Error: ${data.error}`, 'error');
            }
            
        } catch (error) {
            console.error('Error:', error);
            showNotification('Error refreshing AI knowledge', 'error');
        } finally {
            // Restore button state
            button.innerHTML = originalText;
            button.disabled = false;
        }
    }
</script>
{% endblock %}