{% extends "layouts/base.html" %}
{% load i18n static %}
{% load itens_extras %}

{% block title %}{% trans "Criar Leilão" %}{% endblock %}

{% block extrastyle %}
<link rel="stylesheet" href="{% static 'css/dashboard-custom.css' %}">
<style>
  .auction-create-container {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
    min-height: 100vh;
    padding: 2rem 0;
  }

  .auction-create-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    text-align: center;
  }

  .auction-create-header h1 {
    color: white;
    margin: 0;
    font-weight: 600;
  }

  .auction-create-header p {
    color: rgba(255, 255, 255, 0.8);
    margin: 0.5rem 0 0 0;
  }

  .auction-form-card {
    background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  .auction-form-card h2 {
    color: white;
    margin-bottom: 1.5rem;
    font-weight: 600;
  }

  .form-label {
    color: white;
    font-weight: 600;
    margin-bottom: 0.75rem;
    font-size: 1rem;
  }

  .form-control-custom {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 10px;
    color: white;
    padding: 1rem 1.5rem;
    font-size: 1rem;
    transition: all 0.3s ease;
    width: 100%;
  }

  .form-control-custom:focus {
    background: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    color: white;
    box-shadow: 0 0 0 0.2rem rgba(255, 255, 255, 0.1);
  }

  .form-control-custom::placeholder {
    color: rgba(255, 255, 255, 0.6);
  }

  .form-select-custom {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 10px;
    color: white;
    padding: 1rem 1.5rem;
    font-size: 1rem;
    transition: all 0.3s ease;
  }

  .form-select-custom:focus {
    background: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    color: white;
    box-shadow: 0 0 0 0.2rem rgba(255, 255, 255, 0.1);
  }

  .form-select-custom option {
    background: #2d3748;
    color: white;
  }

  .item-preview {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    padding: 1.5rem;
    margin: 1.5rem 0;
    border: 1px solid rgba(255, 255, 255, 0.1);
    display: none;
    align-items: center;
    gap: 1rem;
  }

  .item-preview.show {
    display: flex;
  }

  .item-image {
    width: 64px;
    height: 64px;
    border-radius: 8px;
    border: 2px solid rgba(255, 255, 255, 0.2);
    object-fit: cover;
  }

  .item-info h4 {
    color: white;
    margin: 0 0 0.5rem 0;
    font-weight: 600;
  }

  .item-info p {
    color: #a0aec0;
    margin: 0;
    font-size: 0.9rem;
  }

  .form-group {
    margin-bottom: 1.5rem;
  }

  .btn-create-auction {
    background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
    border: none;
    border-radius: 10px;
    padding: 1rem 2rem;
    color: white;
    font-weight: 600;
    font-size: 1.1rem;
    transition: all 0.3s ease;
    box-shadow: 0 8px 25px rgba(72, 187, 120, 0.3);
    width: 100%;
    margin-top: 1rem;
  }

  .btn-create-auction:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 35px rgba(72, 187, 120, 0.4);
    color: white;
  }

  .btn-cancel {
    background: linear-gradient(135deg, #718096 0%, #4a5568 100%);
    border: none;
    border-radius: 10px;
    padding: 0.75rem 1.5rem;
    color: white;
    font-weight: 500;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-block;
    margin-top: 1rem;
  }

  .btn-cancel:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(113, 128, 150, 0.3);
    color: white;
    text-decoration: none;
  }

  .info-alert {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    border: 1px solid rgba(102, 126, 234, 0.3);
  }

  .info-alert h5 {
    color: white;
    margin-bottom: 1rem;
    font-weight: 600;
  }

  .info-alert p {
    color: rgba(255, 255, 255, 0.9);
    margin: 0;
    line-height: 1.6;
  }

  .form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
  }

  @media (max-width: 768px) {
    .form-row {
      grid-template-columns: 1fr;
    }
    
    .item-preview {
      flex-direction: column;
      text-align: center;
    }
  }
</style>
{% endblock %}

{% block content %}
<div class="auction-create-container">
  <div class="container">
    <!-- Header -->
    <div class="auction-create-header">
      <h1>
        <i class="fas fa-gavel me-3"></i>{% trans "Criar Novo Leilão" %}
      </h1>
      <p>{% trans "Venda seus itens através do sistema de leilões" %}</p>
    </div>

    <!-- Breadcrumbs -->
    <nav aria-label="breadcrumb" class="mb-4">
      <ol class="breadcrumb">
        <li class="breadcrumb-item">
          <a href="{% url 'dashboard' %}" style="color: #a0aec0;">{% trans "Dashboard" %}</a>
        </li>
        <li class="breadcrumb-item">
          <a href="{% url 'auction:listar_leiloes' %}" style="color: #a0aec0;">{% trans "Leilões" %}</a>
        </li>
        <li class="breadcrumb-item active" aria-current="page" style="color: white;">{% trans "Criar Leilão" %}</li>
      </ol>
    </nav>

    <!-- Info Alert -->
    <div class="info-alert">
      <h5>
        <i class="fas fa-info-circle me-2"></i>{% trans "Como funciona?" %}
      </h5>
      <p>
        {% trans "Selecione um personagem, escolha o item que deseja leiloar, defina a quantidade, lance inicial e duração. O item será removido do seu inventário e colocado em leilão automaticamente." %}
      </p>
    </div>

    <!-- Auction Form Card -->
    <div class="auction-form-card">
      <h2>
        <i class="fas fa-edit me-2"></i>{% trans "Informações do Leilão" %}
      </h2>

      <form method="POST">
        {% csrf_token %}

        <div class="form-row">
          <div class="form-group">
            <label for="character_name" class="form-label">
              <i class="fas fa-user me-2"></i>{% trans "Personagem" %}
            </label>
            <select name="character_name" id="character_name" class="form-select-custom" required onchange="atualizarItens()">
              <option value="" disabled selected>{% trans "Selecione o personagem" %}</option>
              {% for inv in inventories %}
                <option value="{{ inv.character_name }}">{{ inv.character_name }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="form-group">
            <label for="item_id" class="form-label">
              <i class="fas fa-box me-2"></i>{% trans "Item" %}
            </label>
            <select name="item_id" id="item_id" class="form-select-custom" required onchange="mostrarPreview()">
              <option value="" disabled selected>{% trans "Selecione o item" %}</option>
            </select>
          </div>
        </div>

        <!-- Item Preview -->
        <div id="item_preview" class="item-preview">
          <img id="item_image" src="/static/assets/img/l2/icons/default.jpg" alt="" class="item-image">
          <div class="item-info">
            <h4 id="item_name"></h4>
            <p id="item_details"></p>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="quantity" class="form-label">
              <i class="fas fa-layer-group me-2"></i>{% trans "Quantidade" %}
            </label>
            <input type="number" name="quantity" id="quantity" class="form-control-custom" required min="1">
          </div>

          <div class="form-group">
            <label for="starting_bid" class="form-label">
              <i class="fas fa-dollar-sign me-2"></i>{% trans "Lance Inicial (R$)" %}
            </label>
            <input type="number" step="0.01" name="starting_bid" id="starting_bid" class="form-control-custom" required min="0.01">
          </div>

          <div class="form-group">
            <label for="duration_hours" class="form-label">
              <i class="fas fa-clock me-2"></i>{% trans "Duração (horas)" %}
            </label>
            <input type="number" name="duration_hours" id="duration_hours" class="form-control-custom" required min="1" max="168" value="24">
          </div>
        </div>

        <div class="text-center">
          <button type="submit" class="btn-create-auction">
            <i class="fas fa-plus-circle me-2"></i>{% trans "Criar Leilão" %}
          </button>
          
          <div class="mt-3">
            <a href="{% url 'auction:listar_leiloes' %}" class="btn-cancel">
              <i class="fas fa-arrow-left me-2"></i>{% trans "Cancelar" %}
            </a>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
  const inventories = {{ inventories_json|safe }};

  function atualizarItens() {
    const personagemSelecionado = document.getElementById('character_name').value;
    const selectItem = document.getElementById('item_id');

    // Limpa opções antigas
    selectItem.innerHTML = '<option value="" disabled selected>{% trans "Selecione o item" %}</option>';

    const inventario = inventories.find(inv => inv.character_name === personagemSelecionado);

    if (inventario) {
      inventario.items.forEach(item => {
        const option = document.createElement('option');
        option.value = item.item_id;
        option.textContent = `${item.item_name} (Qtd: ${item.quantity})`;
        option.dataset.quantity = item.quantity;
        option.dataset.itemName = item.item_name;
        selectItem.appendChild(option);
      });
    }

    // Esconde o preview
    document.getElementById('item_preview').classList.remove('show');
    
    // Atualiza quantidade máxima
    document.getElementById('quantity').max = '';
    document.getElementById('quantity').value = '';
  }

  function mostrarPreview() {
    const personagemSelecionado = document.getElementById('character_name').value;
    const itemSelecionado = document.getElementById('item_id');
    const selectedOption = itemSelecionado.options[itemSelecionado.selectedIndex];

    if (selectedOption && selectedOption.value) {
      const inventario = inventories.find(inv => inv.character_name === personagemSelecionado);
      const item = inventario.items.find(it => it.item_id == itemSelecionado.value);

      if (item) {
        // Busca a URL da imagem via API
        fetch(`/app/inventory/api/item-image/${item.item_id}/`)
          .then(response => response.json())
          .then(data => {
            document.getElementById('item_image').src = data.url;
          })
          .catch(error => {
            console.error('Erro ao buscar imagem:', error);
            document.getElementById('item_image').src = '/static/assets/img/l2/icons/default.jpg';
          });

        // Atualiza informações do item
        document.getElementById('item_name').textContent = item.item_name;
        document.getElementById('item_details').textContent = `Quantidade disponível: ${item.quantity}`;
        
        // Mostra preview
        document.getElementById('item_preview').classList.add('show');
        
        // Atualiza quantidade máxima
        document.getElementById('quantity').max = item.quantity;
        document.getElementById('quantity').value = Math.min(1, item.quantity);
      }
    } else {
      document.getElementById('item_preview').classList.remove('show');
    }
  }

  // Tratamento de erro para imagens
  document.addEventListener('DOMContentLoaded', function() {
    const itemImage = document.getElementById('item_image');
    itemImage.onerror = function() {
      this.src = '/static/assets/img/l2/icons/default.jpg';
    };
  });
</script>
{% endblock %}
