{% extends "layout.html.twig" %}

{% block title %}Return Item - LocalLendables{% endblock %}

{% block content %}
<div class="container-fluid px-3 py-4">
  <div class="row">
    <div class="col-md-8 mx-auto">
      
      <!-- Header -->
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-undo me-2"></i>Return Item</h2>
        <a href="/dashboard/{{ currentUser.id }}" class="btn btn-outline-secondary">
          <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
        </a>
      </div>

      <!-- Item Details -->
      <div class="card mb-4">
        <div class="card-header bg-info text-white">
          <h5 class="mb-0"><i class="fas fa-box me-2"></i>Item Being Returned</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-4">
              {% if item.primaryLogo %}
                <img src="/lendable_items/{{ item.primaryLogo }}" 
                     alt="{{ item.name }}" 
                     class="img-fluid rounded shadow-sm">
              {% else %}
                <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height: 200px;">
                  <i class="fas fa-image text-muted fa-3x"></i>
                </div>
              {% endif %}
            </div>
            <div class="col-md-8">
              <h4>{{ item.name }}</h4>
              <p class="text-muted">{{ item.description }}</p>
              
              <div class="row mt-3">
                <div class="col-sm-6">
                  <strong>Item Owner:</strong><br>
                  <div class="d-flex align-items-center mt-1">
                    {% if owner.avatar %}
                      <img src="/lendables/{{ owner.avatar }}" 
                           alt="{{ owner.showName or owner.firstName }}" 
                           class="rounded-circle me-2" 
                           style="width: 32px; height: 32px;">
                    {% endif %}
                    <span>{{ owner.showName ? owner.showName : (owner.firstName ~ ' ' ~ owner.lastName) }}</span>
                  </div>
                </div>
                <div class="col-sm-6">
                  <strong>Returning User:</strong><br>
                  <div class="d-flex align-items-center mt-1">
                    {% if currentUser.avatar %}
                      <img src="/lendables/{{ currentUser.avatar }}" 
                           alt="{{ currentUser.showName or currentUser.firstName }}" 
                           class="rounded-circle me-2" 
                           style="width: 32px; height: 32px;">
                    {% endif %}
                    <span>{{ currentUser.showName ? currentUser.showName : (currentUser.firstName ~ ' ' ~ currentUser.lastName) }}</span>
                  </div>
                </div>
              </div>

              {% if loan.totalAmount %}
                <div class="mt-3">
                  <strong>Total Cost:</strong> <span class="text-success">${{ loan.totalAmount }}</span>
                </div>
              {% endif %}
            </div>
          </div>
        </div>
      </div>

      <!-- Return Process -->
      <div class="card mb-4">
        <div class="card-header bg-warning text-dark">
          <h5 class="mb-0"><i class="fas fa-clipboard-check me-2"></i>Return Process</h5>
        </div>
        <div class="card-body">
          
          {% if isOwner %}
            <!-- Owner can do return confirmation via QR code -->
            <div class="alert alert-success">
              <i class="fas fa-qrcode me-2"></i>
              <strong>Owner Return Confirmation:</strong> Use QR code to confirm return when item is physically returned.
            </div>

            <div class="text-center mb-3">
              <div id="qr-code-container" class="d-inline-block p-3 bg-white border rounded">
                <!-- QR Code will be generated here -->
              </div>
            </div>

            <div class="d-grid">
              <button type="button" class="btn btn-success btn-lg" onclick="confirmReturn()">
                <i class="fas fa-check-circle me-2"></i>Confirm Item Returned
              </button>
            </div>

          {% else %}
            <!-- Borrower can only send messages -->
            <div class="alert alert-info">
              <i class="fas fa-comments me-2"></i>
              <strong>Request Return Coordination:</strong> Send a message to coordinate return with the owner.
            </div>

            <form id="returnMessageForm">
              <div class="mb-3">
                <label for="returnMessage" class="form-label">Message to Owner</label>
                <textarea class="form-control" id="returnMessage" name="returnMessage" rows="3" 
                          placeholder="I'd like to return {{ item.name }} -- when's a good time?">I'd like to return {{ item.name }} -- when's a good time?</textarea>
              </div>

              <div class="d-grid">
                <button type="submit" class="btn btn-primary btn-lg">
                  <i class="fas fa-paper-plane me-2"></i>Send Message to Owner
                </button>
              </div>
            </form>

          {% endif %}

        </div>
      </div>

      <!-- Help Section -->
      <div class="card">
        <div class="card-header bg-info text-white">
          <h5 class="mb-0"><i class="fas fa-question-circle me-2"></i>Need Help?</h5>
        </div>
        <div class="card-body">
          <p class="mb-0">
            If you have questions about the return process, contact the 
            {% if isOwner %}borrower{% else %}owner{% endif %} using the contact information above 
            or through the LocalLendables messaging system.
          </p>
        </div>
      </div>

    </div>
  </div>
</div>

<!-- Success Modal for Return Process -->
<div class="modal fade" id="successModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">Return Initiated</h5>
      </div>
      <div class="modal-body text-center">
        <i class="fas fa-check-circle text-success fa-3x mb-3"></i>
        <h5>Return Request Sent!</h5>
        <p>The owner has been notified that you want to return this item. They will contact you to arrange pickup or dropoff.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="window.location.href='/dashboard/{{ currentUser.id }}'">
          Back to Dashboard
        </button>
        <button type="button" class="btn btn-outline-secondary" onclick="openChat()">
          Chat with Owner
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Message Sent Modal -->
<div class="modal fade" id="messageSentModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body text-center p-4">
        <i class="fas fa-check-circle text-success fa-4x mb-3"></i>
        <h4 class="text-success mb-2">Return Coordination Message Sent!</h4>
        <p class="mb-2">Your message has been sent to <strong>{{ owner.showName ? owner.showName : (owner.firstName ~ ' ' ~ owner.lastName) }}</strong></p>
        <div class="alert alert-info small mb-2">
          <strong>Community Tip:</strong> The owner will contact you to arrange the return. Check your messages for their response!
        </div>
        <small class="text-muted">Redirecting to dashboard in 4 seconds...</small>
      </div>
    </div>
  </div>
</div>

<script>
// Note: returnForm event listener removed - no form with that ID exists

// Handle message form submission for borrowers
document.getElementById('returnMessageForm')?.addEventListener('submit', async function(e) {
  e.preventDefault();
  
  const formData = new FormData(this);
  const submitBtn = this.querySelector('button[type="submit"]');
  const message = formData.get('returnMessage');
  
  if (!message || !message.trim()) {
    alert('Please enter a message');
    return;
  }
  
  try {
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Sending...';
    
    // Find conversation for this item or create one if needed
    let conversationId = null;
    
    try {
      // Try to find existing conversation for this item
      const conversationResponse = await fetch(`/api/chat/find-conversation?itemId={{ item.id }}&userId={{ currentUser.id }}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      if (conversationResponse.ok) {
        const conversationData = await conversationResponse.json();
        if (conversationData.conversationId) {
          conversationId = conversationData.conversationId;
        }
      }
      
      // If no conversation found, start a new one
      if (!conversationId) {
        const startResponse = await fetch('/api/chat/start', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            itemId: {{ item.id }},
            userId: {{ currentUser.id }}
          })
        });
        
        if (startResponse.ok) {
          const startData = await startResponse.json();
          conversationId = startData.conversationId;
        }
      }
      
      if (!conversationId) {
        throw new Error('Could not establish conversation');
      }
    } catch (error) {
      console.error('Error setting up conversation:', error);
      alert('Unable to set up messaging. Please contact the owner directly.');
      return;
    }
    
    // Send message using working direct message API
    const response = await fetch(`/api/chat/${conversationId}/message?user={{ currentUser.id }}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        content: message.trim()
      })
    });
    
    const result = await response.json();
    
    if (result.success) {
      // Show success modal with owner name
      const modal = new bootstrap.Modal(document.getElementById('messageSentModal'));
      modal.show();
      
      // Clear the form
      document.getElementById('returnMessage').value = '';
      
      // Redirect to dashboard after 4 seconds (increased for better visibility)
      setTimeout(() => {
        window.location.href = '/dashboard/{{ currentUser.id }}';
      }, 4000);
    } else {
      alert('Error sending message: ' + result.error);
    }
  } catch (error) {
    console.error('Error sending message:', error);
    alert('Failed to send message');
  } finally {
    submitBtn.disabled = false;
    submitBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Send Message to Owner';
  }
});

// Function for owner to confirm return
function confirmReturn() {
  if (confirm('Confirm that the item has been physically returned to you?')) {
    fetch('/api/loans/{{ currentLoan.id }}/complete-return', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        confirmed: true
      })
    })
    .then(response => response.json())
    .then(result => {
      if (result.success) {
        alert('Return confirmed! The item is now available for lending again.');
        window.location.href = '/dashboard/{{ currentUser.id }}';
      } else {
        alert('Error confirming return: ' + result.error);
      }
    })
    .catch(error => {
      console.error('Error confirming return:', error);
      alert('Failed to confirm return');
    });
  }
}

function openChat() {
  window.location.href = '/chat/{{ item.id }}/{{ owner.id }}/{{ currentUser.id }}';
}
</script>
{% endblock %}