<% title = trans.cruds.MODULE.ORDER + ' ' + trans.global.view + ' - ' + companyInfo.NAME %>

<style>
.chat-container {
    max-height: 500px;
    overflow-y: auto;
    padding: 20px;
    scrollbar-width: thin;
    scrollbar-color: #adb5bd #f8f9fa;
}

.chat-container::-webkit-scrollbar {
    width: 6px;
}

.chat-container::-webkit-scrollbar-track {
    background: #f8f9fa;
}

.chat-container::-webkit-scrollbar-thumb {
    background-color: #adb5bd;
    border-radius: 20px;
}

.message-bubble {
    max-width: 500px;
    position: relative;
    padding-bottom: 25px !important;
}

.file-preview-item {
    transition: all 0.3s;
}

.file-preview-item:hover {
    transform: scale(1.05);
}

.btn-close {
    font-size: 0.7rem;
    padding: 0.25rem !important;
}

/* Filter buttons styling */
.btn-group .btn-outline-primary {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}

.btn-check:checked + .btn-outline-primary {
    background-color: var(--bs-primary);
    color: white;
}

.card {
    margin-bottom: 0;
}

.card .table {
    margin-bottom: 0;
}
</style>

<div class="container-fluid">
    <!-- Page Title and Breadcrumb -->
    <div class="page-title mb-4">
        <div class="row align-items-center">
            <div class="col-sm-6 col-12">
                <h2><%= trans.cruds.ORDER?.title %> Dispute</h2>
            </div>
            <div class="col-sm-6 col-12">
                <ol class="breadcrumb float-sm-end">
                    <li class="breadcrumb-item"><a href="/admin/dashboard"><i class="iconly-Home icli svg-color"></i> <%= trans.global.home %></a></li>
                    <li class="breadcrumb-item"><a href="/admin/orders"><%= trans.cruds.ORDER?.title_singular || trans.global.view %></a></li>
                    <li class="breadcrumb-item active">Dispute - <%= dispute.orderId._id %></li>
                </ol>
            </div>
        </div>
    </div>

    <!-- Order Summary -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h3 class="card-title mb-0">Order Dispute Details</h3>
            <div>
                <span class="badge bg-<%= dispute.status === 'resolved' ? 'success' : dispute.status === 'discussion' ? 'warning' : 'danger' %>">
                    <%= dispute.status.toUpperCase() %>
                </span>
            </div>
        </div>
        <div class="card-body disput-wrapper">
            <!-- Basic Information -->
            <div class="row mb-4 disput-row-info">
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-header bg-primary text-white">
                            <h6 class="mb-0">Order Information</h6>
                        </div>
                        <div class="card-body">
                            <table class="table table-sm mb-0">
                                <tr>
                                    <th width="40%">Order ID:</th>
                                    <td><%= dispute.orderId._id %></td>
                                </tr>
                                <tr>
                                    <th>Order Date:</th>
                                    <td><%= new Date(dispute.orderId.createdAt).toLocaleDateString() %></td>
                                </tr>
                                <tr>
                                    <th>Total Amount:</th>
                                    <td class="fw-bold">$<%= dispute.orderId.totalAmount %></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-header bg-info text-white">
                            <h6 class="mb-0">Dispute Information</h6>
                        </div>
                        <div class="card-body">
                            <table class="table table-sm mb-0">
                                <tr>
                                    <th width="40%">Dispute Created:</th>
                                    <td><%= new Date(dispute.createdAt).toLocaleString() %></td>
                                </tr>
                                <tr>
                                    <th>Initiator:</th>
                                    <td class="fw-bold">Buyer</td>
                                </tr>
                                <tr>
                                    <th>Status:</th>
                                    <td>
                                        <span class="badge bg-<%= dispute.status === 'resolved' ? 'success' : dispute.status === 'discussion' ? 'warning' : 'danger' %>">
                                            <%= dispute.status.toUpperCase() %>
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>

                <% if (dispute?.orderId?.products && dispute?.orderId?.products?.productSnapshot) { %>
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-header bg-success text-white">
                            <h6 class="mb-0">Product Information</h6>
                        </div>
                        <div class="card-body">
                            <% const product = dispute.orderId.products.productSnapshot; %>
                            <div class="d-flex align-items-center mb-3">
                                <% if (product['upload-feature-image'] && product['upload-feature-image'].content) { %>
                                    <img src="<%= isFileExists('storage/post' + product['upload-feature-image'].content) && product['upload-feature-image'].content.meta.files[0].location ? product['upload-feature-image'].meta.files[0].location : '/backend/images/dummy-image.jpg' %>" 
                                        class="img-fluid rounded me-3" 
                                        style="width: 60px; height: 60px; object-fit: cover;"
                                        alt="<%= product.title ? product.title.content : 'Product' %>">
                                <% } %>
                                <div>
                                    <h6 class="mb-1 fw-bold"><%= product.title ? product.title.content : 'Product' %></h6>
                                    <small class="text-muted">
                                        <%= product['short-description'] ? (product['short-description'].content.length > 50 ? product['short-description'].content.substring(0, 50) + '...' : product['short-description'].content) : '' %>
                                    </small>
                                </div>
                            </div>
                            <table class="table table-sm mb-0">
                                <tr>
                                    <th width="50%">Original Price:</th>
                                    <td>$<%= product.price ? product.price.content : 'N/A' %></td>
                                </tr>
                                <tr>
                                    <th>Negotiated Price:</th>
                                    <td class="fw-bold">$<%= dispute.orderId.products.negotiatePrice %></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                <% } %>
            </div>

            <!-- Users Information -->
            <div class="row mb-4 disput-row-info">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h6 class="mb-0">Buyer (Initiator)</h6>
                        </div>
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <% if (initiator.profile_image) { %>
                                    <img src="<%= initiator.profile_image %>" class="rounded-circle me-3" width="60" height="60" alt="Profile">
                                <% } else { %>
                                    <div class="rounded-circle bg-secondary d-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px;">
                                        <span class="text-white fs-4"><%= initiator.first_name.charAt(0) %></span>
                                    </div>
                                <% } %>
                                <div>
                                    <h5 class="mb-1"><%= initiator.first_name %> <%= initiator.last_name %></h5>
                                    <p class="text-muted mb-1"><%= initiator.email %></p>
                                    <span class="badge bg-primary">Buyer</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header bg-warning text-dark">
                            <h6 class="mb-0">Seller (Opponent)</h6>
                        </div>
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <% if (opponent.profile_image) { %>
                                    <img src="<%= opponent.profile_image %>" class="rounded-circle me-3" width="60" height="60" alt="Profile">
                                <% } else { %>
                                    <div class="rounded-circle bg-secondary d-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px;">
                                        <span class="text-white fs-4"><%= opponent.first_name.charAt(0) %></span>
                                    </div>
                                <% } %>
                                <div>
                                    <h5 class="mb-1"><%= opponent.first_name %> <%= opponent.last_name %></h5>
                                    <p class="text-muted mb-1"><%= opponent.email %></p>
                                    <span class="badge bg-warning">Seller</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Dispute Conversation -->
            <div class="card">
                <div class="mt-4 mb-3 d-flex justify-content-between align-items-center">
                    <div class="d-flex gap-1">
                        <h5 class="mb-0">Conversation</h5>
                        <div class="message-count" id="messageCount">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-mail"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline></svg>
                            <span class="counter-number"><%= dispute.disputeHistory ? dispute.disputeHistory.length : 0 %></span>
                        </div>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                      <!-- Message Filter -->
                      <div class="btn-group message-filter-wrap" role="group" aria-label="Message Filter">
                          <input type="radio" class="btn-check" name="messageFilter" id="filterAll" value="all" checked>
                          <label class="btn btn-outline-primary btn-sm" for="filterAll">
                              All
                          </label>
                          
                          <input type="radio" class="btn-check" name="messageFilter" id="filterBuyerSeller" value="buyer_seller">
                          <label class="btn btn-outline-primary btn-sm" for="filterBuyerSeller">
                              Buyer & Seller
                          </label>
                          
                          <!-- <input type="radio" class="btn-check" name="messageFilter" id="filterBuyerOnly" value="buyer_only">
                          <label class="btn btn-outline-primary btn-sm" for="filterBuyerOnly">
                              Buyer Only
                          </label>
                          
                          <input type="radio" class="btn-check" name="messageFilter" id="filterSellerOnly" value="seller_only">
                          <label class="btn btn-outline-primary btn-sm" for="filterSellerOnly">
                              Seller Only
                          </label> -->
                          
                          <!-- <input type="radio" class="btn-check" name="messageFilter" id="filterAdminBuyer" value="admin_buyer">
                          <label class="btn btn-outline-primary btn-sm" for="filterAdminBuyer">
                              Admin-Buyer
                          </label>
                          
                          <input type="radio" class="btn-check" name="messageFilter" id="filterAdminSeller" value="admin_seller">
                          <label class="btn btn-outline-primary btn-sm" for="filterAdminSeller">
                              Admin-Seller
                          </label> -->
                      </div>
                    
                  </div>
                </div>
                <div class="card-body p-0">
                    <div class="chat-container border border-primary">
                        <% if (dispute.disputeHistory && dispute.disputeHistory.length > 0) { 
                            dispute.disputeHistory.forEach((history, index) => { 
                            const isBuyer = history.action === 'buyer_message';
                            const isSeller = history.action === 'seller_message';
                            const isAdmin = history.action === 'admin_message';
                            const isInitiator = (isBuyer && dispute.userType === 'buyer') || (isSeller && dispute.userType === 'seller');
                            
                            let user;
                            if (isBuyer) user = dispute.userType === 'buyer' ? initiator : orderBuyer;
                            if (isSeller) user = dispute.userType === 'seller' ? initiator : orderSeller;
                            
                            // Generate data attributes for filtering
                            let filterClasses = '';
                            if (isBuyer) filterClasses += ' buyer-message';
                            if (isSeller) filterClasses += ' seller-message';
                            if (isAdmin) filterClasses += ' admin-message';
                            
                            // Determine recipients for filtering
                            const recipients = history.recipients || [];
                            const hasBuyer = recipients.includes('buyer');
                            const hasSeller = recipients.includes('seller');
                            const hasAdmin = recipients.includes('admin');
                            
                            if (isAdmin) {
                                if (hasBuyer && hasSeller) {
                                    filterClasses += ' admin-both';
                                } else if (hasBuyer) {
                                    filterClasses += ' admin-buyer';
                                } else if (hasSeller) {
                                    filterClasses += ' admin-seller';
                                }
                            }
                        %>
                            <div class="message mb-4<%= filterClasses %> <%= isInitiator ? 'text-end' : '' %>" data-filter="<%= filterClasses.trim() %>">
                                <div class="d-flex <%= history.action === 'admin_message' ? 'justify-content-end align-items-end' : 'align-items-end'  %>">
                                    

                                    <% if (isInitiator && user) { %>
                                        <div class="me-2 mb-4">
                                            <% if (user.profile_image) { %>
                                                <img src="<%= user.profile_image %>" class="rounded-circle" width="40" height="40" alt="Profile">
                                            <% } else { %>
                                                <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                    <span class="text-white"><%= user.first_name ? user.first_name.charAt(0) : 'U' %></span>
                                                </div>
                                            <% } %>
                                        </div>
                                    <% } else { %>
                                        <div class="me-2 mb-4">
                                            <% if (user && user.profile_image) { %>
                                                <img src="<%= user.profile_image %>" class="rounded-circle" width="40" height="40" alt="Profile">
                                            <% } else if (user) { %>
                                                <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                    <span class="text-white"><%= user.first_name ? user.first_name.charAt(0) : 'U' %></span>
                                                </div>
                                            <% } %>
                                        </div>
                                    <% } %>
                                    
                                    <div>
                                        <div class="message-bubble <%= isInitiator ? 'bg-primary text-white' : isAdmin ? 'bg-danger text-white' : 'bg-primary' %> p-3 rounded-3">
                                            <div class="message-header d-flex justify-content-between mb-2">
                                                <small class="fw-bold">
                                                    <%= isAdmin ? 'System Administrator' : (user ? user.first_name + ' ' + user.last_name : 'User') %>
                                                    <% if (isBuyer) { %>
                                                        <span class="badge bg-info ms-1">Buyer</span>
                                                    <% } else if (isSeller) { %>
                                                        <span class="badge bg-warning ms-1">Seller</span>
                                                    <% } else if (isAdmin) { %>
                                                        <span class="badge bg-danger ms-1">System Administrator</span>
                                                    <% } %>
                                                </small>
                                            </div>
                                            
                                            <% if (history.message) { %>
                                            <p class="mb-0"><%= history.message %></p>
                                            <% } %>

                                            <% if (history.evidence && history.evidence.length > 0) { %>
                                                <div class="evidence mt-3">
                                                    <div class="d-flex flex-column gap-2 g-2">
                                                        <% history.evidence.forEach((file, idx) => { 
                                                            const isImage = file && file.mimetype && file.mimetype.startsWith('image/');
                                                            const isVideo = file && file.mimetype && file.mimetype.startsWith('video/');
                                                            const isPDF = file && file.mimetype && file.mimetype === 'application/pdf';
                                                            const isWordDoc = file && file.mimetype && (file.mimetype.includes('word') || file.mimetype.includes('document'));
                                                            const isText = file && file.mimetype && file.mimetype.includes('text/');

                                                            let fileIcon = 'fa-file';
                                                            let iconColor = 'text-muted';

                                                            if (isImage) {
                                                                fileIcon = 'fa-image';
                                                                iconColor = 'text-success';
                                                            } else if (isVideo) {
                                                                fileIcon = 'fa-video';
                                                                iconColor = 'text-danger';
                                                            } else if (isPDF) {
                                                                fileIcon = 'fa-file-pdf';
                                                                iconColor = 'text-danger';
                                                            } else if (isWordDoc) {
                                                                fileIcon = 'fa-file-word';
                                                                iconColor = 'text-primary';
                                                            } else if (isText) {
                                                                fileIcon = 'fa-file-alt';
                                                                iconColor = 'text-info';
                                                            }
                                                        %>
                                                            <div class="col-12">
                                                                <div class="border rounded p-1 text-center file-preview mb-2">
                                                                    <% if (isImage && file.url) { %>
                                                                        <a href="<%= file.url %>" target="_blank" class="d-block">
                                                                            <img src="<%= file.url %>" class="img-thumbnail" 
                                                                                style="object-fit: cover;"
                                                                                alt="<%= file.originalName || 'Evidence' %>"
                                                                                title="<%= file.originalName || 'Evidence' %>">
                                                                        </a>

                                                                    <% } else if (isVideo && file.url) { %>
                                                                        <a href="<%= file.url %>" target="_blank" class="d-block">
                                                                            <video controls class="img-thumbnail">
                                                                                <source src="<%= file.url %>" type="<%= file.mimetype || 'video/mp4' %>">
                                                                            </video>
                                                                        </a>
                                                                    <% } else { %>
                                                                       <a href="<%= file.url %>" target="_blank" class="d-flex gap-2 text-decoration-none pdf-chat-wrapper">
                                                                            <i class="fas <%= fileIcon %> <%= iconColor %>"></i>
                                                                                <small><%= file.originalName %></small>
                                                                        </a>
                                                                    <% } %>

                                                                    <!-- File info -->
                                                                    <div class="download-chat-img">
                                                                        <% if (file.url) { %>
                                                                            <a href="<%= file.url %>" target="_blank" download="<%= file.originalName || 'evidence' %>" 
                                                                            class="btn btn-sm btn-outline-primary btn-block" title="Download <%= file.originalName || 'file' %>">
                                                                                <i class="fas fa-download me-1"></i>
                                                                            </a>
                                                                        <% } %>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        <% }) %>
                                                    </div>
                                                </div>
                                            <% } %>

                                            <small class="chat-time-date <%= isInitiator ? '' : 'text-muted' %>">
                                                <%= new Date(history.createdAt).toLocaleString() %>
                                            </small>
                                        </div>
                                            

                                        <div class="message-footer mt-1">
                                            <small class="text-muted">
                                                <span class="me-1">Sent to:</span>
                                                <% if (history.recipients && history.recipients.length > 0) { 
                                                    const recipients = history.recipients || [];

                                                    const recipientConfig = {
                                                        'buyer': { label: 'Buyer', class: 'bg-primary' },
                                                        'seller': { label: 'Seller', class: 'bg-warning text-dark' },
                                                        'admin': { label: 'Admin', class: 'bg-danger' }
                                                    };

                                                    recipients.forEach((recipient, idx) => { 
                                                        const config = recipientConfig[recipient] || { label: recipient, class: 'bg-secondary' };
                                                    %>
                                                        <span class="badge <%= config.class %>">
                                                            <%= config.label %>
                                                        </span>
                                                    <% });
                                                } else { %>
                                                    <span class="badge bg-light text-muted">None</span>
                                                <% } %>
                                            </small>
                                        </div>
                                        
                                    </div>
                                    
                                    <% if (!isInitiator) { %>
                                        <div class="ms-2">
                                            <% if (isAdmin) { %>
                                                <div class="rounded-circle bg-danger d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                    <i class="fas fa-user-shield text-white"></i>
                                                </div>
                                            <% } %>
                                        </div>
                                    <% } %>
                                    
                                </div>
                            </div>
                        <% });
                        } else { %>
                            <div class="text-center py-5">
                                <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No messages yet</p>
                            </div>
                        <% } %>
                    </div>
                    
                    <!-- Admin Actions -->
                    <% if (dispute.status !== 'resolved') { %>
                        <div class="p-3 bg-light position-relative">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="fw-bold text-dark mb-0">
                                    <i class="fas fa-shield-alt me-1 text-success"></i>
                                    Administration
                                </h6>
                                
                                <select id="sendMessageTo" name="sendMessageTo" class="form-select w-auto">
                                    <option value="both">Both</option>
                                    <option value="buyer">Buyer</option>
                                    <option value="seller">Seller</option>
                                </select>
                            </div>
                            
                            <!-- File Preview Container -->
                            <div id="filePreviewContainer" class="mb-3 d-flex flex-wrap gap-2" style="display: none !important;"></div>
                            
                            <form id="disputeReplyForm">
                                <div class="mb-3">
                                    <textarea class="form-control" 
                                            name="message" 
                                            rows="3" 
                                            placeholder="Enter your response as system..."
                                            required></textarea>
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <div class="position-relative">
                                        <label class="btn btn-outline-secondary btn-sm cursor-pointer mb-0">
                                            <i class="fas fa-paperclip me-1"></i>
                                            Attach Files
                                            <input type="file" id="fileAttachment" name="attachments" multiple hidden 
                                                accept="image/*,.pdf,.doc,.docx,.txt" />
                                        </label>
                                        <small class="text-muted ms-2">
                                            Max 5 files, 10MB each
                                        </small>
                                    </div>
                                    
                                    <div class="d-flex gap-2">
                                        <!-- Close Dispute Button -->
                                        <button type="button" 
                                                class="btn btn-danger"
                                                data-bs-toggle="modal"
                                                data-bs-target="#closeDisputeModal">
                                            <i class="fas fa-lock me-1"></i>
                                            Adjust Amount
                                        </button>

                                        <!-- Close Dispute Button -->
                                        <button type="button" 
                                                class="btn btn-danger"
                                                data-bs-toggle="modal"
                                                data-bs-target="#closeDisputeModal">
                                            <i class="fas fa-lock me-1"></i>
                                            Close Dispute
                                        </button>

                                        <!-- Send Response -->
                                        <button type="submit" class="btn btn-success sendResponse">
                                            <i class="fas fa-paper-plane me-1"></i>
                                            Send Response
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    <% } %>
                </div>
            </div>
        </div>
    </div>
</div>

<%- include("./dispute-modal") %>

<!-- script -->
<%- include("./dispute-script") %>