{% extends "admin/base_site.html" %}
{% load i18n humanize admin_urls static palette %}


{% block extrastyle %}
  {{ block.super }}
  <style>
    /* Related Widget Wrapper */
    .related-widget-wrapper {
      display: flex;
      gap: 0.5rem;
      align-items: flex-start;
    }

    .related-widget-wrapper select {
      flex: 1;
    }

    .related-widget-wrapper-link {
      padding: 0.375rem 0.75rem;
      border-radius: 0.375rem;
      background-color: #0d6efd;
      color: white;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: 0.25rem;
      font-size: 0.85rem;
      white-space: nowrap;
      transition: all 0.2s ease;
      margin-top: 0.25rem;
    }

    .related-widget-wrapper-link:hover {
      background-color: #0b5ed7;
      box-shadow: 0 0.25rem 0.5rem rgba(13, 110, 253, 0.3);
    }

    body.dark-mode .related-widget-wrapper-link {
      background-color: #0d6efd;
    }

    body.dark-mode .related-widget-wrapper-link:hover {
      background-color: #0b5ed7;
    }

    .dj-palette-file-upload-zone {
      border: 2px dashed var(--card-border);
      border-radius: 0.375rem;
      padding: 2rem;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      background-color: var(--bs-bg-light);
    }

    .dj-palette-file-upload-zone:hover {
      border-color: #0d6efd;
      background-color: rgba(13, 110, 253, 0.05);
    }

    body.dark-mode .dj-palette-file-upload-zone:hover {
      background-color: rgba(13, 110, 253, 0.1);
    }

    .dj-palette-file-upload-zone.dragover {
      border-color: #0d6efd;
      background-color: rgba(13, 110, 253, 0.15);
      box-shadow: 0 0 10px rgba(13, 110, 253, 0.3);
    }

    .dj-palette-file-upload-content i {
      font-size: 2.5rem;
      color: #0d6efd;
      display: block;
      margin-bottom: 0.5rem;
    }

    .dj-palette-file-upload-content p {
      color: var(--text-muted);
      margin: 0;
      font-size: 0.95rem;
    }

    .dj-palette-file-input-hidden {
      display: none;
    }

    .file-preview {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 1rem;
    }

    .preview-item {
      position: relative;
      border-radius: 0.375rem;
      overflow: hidden;
      background-color: var(--bs-bg-light);
      padding: 0.5rem;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid var(--card-border);
    }

    .preview-item img {
      max-width: 100%;
      max-height: 150px;
      object-fit: cover;
    }

    .file-item {
      text-align: center;
      padding: 1rem;
    }

    .file-item i {
      font-size: 2rem;
      color: var(--text-muted);
      display: block;
      margin-bottom: 0.5rem;
    }

    .file-item p {
      color: var(--text-muted);
      font-size: 0.85rem;
      word-break: break-word;
      margin: 0;
    }

    .remove-file {
      position: absolute;
      top: 0.25rem;
      right: 0.25rem;
      background: rgba(220, 53, 69, 0.9);
      border: none;
      border-radius: 50%;
      width: 1.5rem;
      height: 1.5rem;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      cursor: pointer;
      opacity: 0;
      transition: opacity 0.2s ease;
    }

    .preview-item:hover .remove-file {
      opacity: 1;
    }

    .remove-file:hover {
      background: rgba(220, 53, 69, 1);
    }

    /* Bootstrap Switch Toggle Styles */
    .form-switch {
      padding-left: 0;
    }

    .form-switch .form-check-input {
      width: 2.5em;
      height: 1.25em;
      margin-left: 0;
      margin-top: 0.125em;
      background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280,0,0,.25%29'/%3e%3c/svg%3e");
      background-position: left center;
      background-repeat: no-repeat;
      background-size: 1.25em 1.25em;
      border-radius: 2em;
      transition: background-position 0.15s ease-in-out;
      cursor: pointer;
    }

    .form-switch .form-check-input:checked {
      background-position: right center;
      background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%28255,255,255,.25%29'/%3e%3c/svg%3e");
    }

    .form-switch .form-check-input:focus {
      border-color: #0d6efd;
      box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }

    .form-switch .form-check-label {
      margin-left: 0.5em;
      user-select: none;
    }
  </style>
{% endblock extrastyle %}


{% block content %}
  <div class="container-fluid">
    <div class="my-4">
      {% if change %}<h6 class="alert small alert-secondary">Editing: <u> "{{ original }}" </u> </h6>{% endif %}
      {% if add %}<h6 class="alert small alert-success">Create a new : {{ adminform.model_admin.opts.model_name|capfirst }}</h6>{% endif %}
    </div>

    <form method="post" enctype="multipart/form-data" novalidate>
      {% csrf_token %}

      {% if is_popup %}
        <input type="hidden" name="_popup" value="1">
        <script type="text/javascript">
          // Handle popup mode - notify parent window when item is created
          window.addEventListener('beforeunload', function() {
            if (window.opener && window.opener.dismissAddRelatedModal) {
              // Get the saved object ID and label from the form
              const objectId = document.querySelector('input[name="id"]')?.value || '{{ object.id }}';
              const objectLabel = '{{ original|escapejs }}' || 'New Item';
              if (objectId) {
                window.opener.dismissAddRelatedModal(objectId, objectLabel);
              }
            }
          });
        </script>
      {% endif %}

      {% if to_field %}
        <input type="hidden" name="_to_field" value="{{ to_field }}">
      {% endif %}

      <input type="hidden" name="_save" value="true" />

      {% if add %}
        <input type="hidden" name="_saveasnew" value="true">
      {% elif change %}
        <input type="hidden" name="id" value="{{ object.id }}">
      {% endif %}
      
      {% if save_and_continue %}
        <input type="hidden" name="_continue" value="{% url 'palette_admin:opts.app_label/opts.model_name' %}">
      {% endif %}


      <div class="row">
        <div class="col-lg-12">
          {% for fieldset in adminform %}
            <fieldset class="mb-4 border rounded p-3" style="background-color: var(--card-bg); border-color: var(--card-border);">
              {% if fieldset.name %}
                <legend class="h5 border-bottom pb-2 mb-3">{{ fieldset.label }}</legend>
              {% endif %}

              {% if fieldset.description %}
                <p>{{ fieldset.description|safe }}</p>
              {% endif %}

              <div class="mb-3 row">
              {% for line in fieldset %}
                {% for field in line %}
                    <div class="
                    {% if field|widget_type == 'relatedfieldwidgetwrapper' and field|is_multiple_select %}
                    col-12 
                    {% elif field|widget_type == 'admintextarea' %}
                    col-12 
                    {% else %} col-sm-6 col-md-6 {% endif %} mb-3">
                    
                      <label for="{{ field.id_for_label }}" class="fw-semibold">
                        {{ field.label_tag }}
                        {% if field.field.is_required %}<span class="text-danger">*</span>{% endif %}
                      </label>

                      {% comment %} {% if field|widget_type == 'relatedfieldwidgetwrapper' and not field|is_multiple_select %}
                          <select name="{{ field.html_name }}" id="{{ field.id_for_label }}" class="select2 form-control">
                            {% for option in field.field.field.choices %}
                              <option value="{{ option.0 }}" {% if option.0 in field.value %}selected{% endif %}>
                                {{ option.1 }}
                              </option>
                            {% endfor %}
                          </select>
                      {% elif field|widget_type == 'relatedfieldwidgetwrapper' and field|is_multiple_select %}
                        <div class="related-widget-wrapper" data-model-ref="{{ field.field.rel.model_name }}" data-field-id="{{ field.id_for_label }}">
                          <select multiple name="{{ field.html_name }}" id="{{ field.id_for_label }}" class="select2 multiple form-control">
                            {% for option in field.field.field.choices %}
                              <option value="{{ option.0 }}" {% if option.0 in field.value %}selected{% endif %}>
                                {{ option.1 }}
                              </option>
                            {% endfor %}
                          </select>
                          {% if field.field.rel %}
                            <button type="button" class="related-widget-wrapper-link add-related-modal" data-model="{{ field.field.rel.model_name }}" data-field-id="{{ field.id_for_label }}" title="Add another {{ field.field.rel.model_name|title }}">
                              <i class="bi bi-plus-circle"></i> Add
                            </button>
                          {% endif %}
                        </div> {% endcomment %}
                      {% if field|widget_type == "adminfile" %}
                        <div class="dj-palette-file-upload-zone" id="dj-palette-dropzone-{{ field.field.id_for_label }}">
                          <div class="dj-palette-file-upload-content">
                            <i class="bi bi-cloud-arrow-up"></i>
                            <p>Drag and drop files here or click to browse</p>
                            <input type="file" name="{{ field.field.html_name }}" id="{{ field.field.id_for_label }}" class="dj-palette-file-input-hidden" {% if field.field.widget.attrs.accept %}accept="{{ field.field.widget.attrs.accept }}"{% endif %}>
                          </div>
                          <div class="dj-palette-file-preview mt-3" id="preview-{{ field.id_for_label }}">
                            {% if field.field.value %}
                              <div class="preview-item">
                                {% with file_name=field.field.value.name|lower %}
                                  {% if file_name|slice:"-4:" in ".jpg,.png,.gif,.webp" or file_name|slice:"-5:" in ".jpeg" %}
                                    <img src="{{ MEDIA_URL}}{{ field.field.value.url }}" alt="Preview" class="img-thumbnail" style="max-width: 200px; max-height: 200px;">
                                  {% else %}
                                    <div class="file-item">
                                      <i class="bi bi-file-earmark"></i>
                                      <p>{{ field.field.value.name }}</p>
                                    </div>
                                  {% endif %}
                                {% endwith %}
                              </div>
                            {% endif %}
                          </div>
                        </div>
                      {% elif field|widget_type == "admintextarea" %}
                        <textarea name="{{ field.field.html_name }}" id="{{ field.field.id_for_label }}" class="form-control" rows="4">{{ field.field.value|default:'' }}</textarea>
                      {% elif field|widget_type == "checkbox" %}
                        <div class="form-check form-switch">
                          <input type="checkbox" name="{{ field.field.html_name }}" id="{{ field.field.id_for_label }}" class="form-check-input" value="on" {% if field.field.value %}checked{% endif %}>
                          <label class="form-check-label" for="{{ field.field.id_for_label }}">{{ field.label_tag }}</label>
                        </div>
                      {% elif field|widget_type == "adminemailinput" %}
                        <input type="email" name="{{ field.field.html_name }}" value="{{ field.field.value|default:'' }}" class="form-control" id="{{ field.field.id_for_label }}">
                      {% elif field|widget_type == "adminsplitdatetime" %}
                        {% if field.field.value %}
                          {% with datetime_val=field.field.value %}
                            <input type="datetime-local" name="{{ field.field.html_name }}" value="{{ datetime_val|date:'Y-m-d\\TH:i' }}" class="form-control" id="{{ field.field.id_for_label }}">
                          {% endwith %}
                        {% else %}
                          <input type="datetime-local" name="{{ field.field.html_name }}" class="form-control" id="{{ field.field.id_for_label }}">
                        {% endif %}
                      {% elif field|widget_type == "adminurlfield" %}
                        <input type="url" name="{{ field.field.html_name }}" value="{{ field.field.value|default:'' }}" class="form-control disabled password" id="{{ field.field.id_for_label }}">
                      {% elif field|widget_type == "admintextinput" and field.field.name == 'password' %}
                        <input type="password" name="{{ field.field.html_name }}" disabled="true" value="{{ field.field.value|default:''}}" class="form-control disabled password" id="{{ field.field.id_for_label }}">
                        <p class="small"> To change the password, use this "form" </p>
                      {% elif field|widget_type == "admintextinput" %}
                        <input name="{{ field.field.html_name }}" id="{{ field.field.id_for_label }}" class="form-control" rows="4" value="{{ field.field.value|default:'' }}" />
                      {% elif field|widget_type == "adminuuidinput" %}
                        <input name="{{ field.field.html_name }}" id="{{ field.field.id_for_label }}" class="form-control" rows="4" value="{{ field.field.value|default:'' }}" />
                      {% else %}
                        <div> {{ field.field  }} </div>
                      {% endif %}

                      {% if field.help_text %}
                        <small class="form-text">{{ field.help_text|safe }}</small>
                      {% endif %}
                      {% if field.errors %}
                        <div class="text-danger px-0 small">{{ errors|first }}</div>
                      {% endif %}
                    </div>
                {% endfor %}
              {% endfor %}
              </div>
              
            </fieldset>
          {% endfor %}

        </div>
      </div>

      {% block submit_buttons_bottom %}
      <div class="d-flex gap-3 flex-wrap position-sticky sticky-bottom border-top py-3 px-4 mt-5" style="background-color: var(--card-bg); border-color: var(--card-border);">
        <button type="submit" class="btn btn-primary">
          <i class="bi bi-download"></i> Save Changes
        </button>
        <button type="submit" class="btn btn-secondary">
          <i class="bi bi-plus-circle"></i> Save and add another
        </button>
        {% if change %}
          <a href="{{ delete_url }}" class="btn btn-danger">
            <i class="bi bi-trash"></i> Delete
          </a>
        {% endif %}
      </div>
      {% endblock %}
    </form>
  </div>

  <!-- Add Related Modal -->
  <div class="modal fade" id="addRelatedModal" tabindex="-1" aria-labelledby="addRelatedModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header border-bottom">
          <h5 class="modal-title" id="addRelatedModalLabel">Add New Item</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <iframe id="relatedItemFrame" style="width: 100%; height: 600px; border: none;"></iframe>
        </div>
        <div class="modal-footer border-top">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>
{% endblock %}


{% block extra_scripts %}
  <script type="text/javascript">
    $(document).ready(function(){
        // Initialize Select2 with current values
        $('.select2').select2({
          allowClear: true,
          width: '100%'
        });
        
        // Load current values for select2 fields
        $('.select2').each(function() {
          const currentValues = $(this).val();
          if (currentValues) {
            $(this).val(currentValues).trigger('change');
          }
        });
        
        // Get form and ensure values are synced before submission
        const form = document.querySelector('form');
        if (form) {
          // Use native form submit event with capture phase
          form.addEventListener('submit', function(e) {
            console.log('Form submitting, syncing Select2 fields...');
            
            // For each Select2 field, ensure the underlying select element
            // has the values that will be submitted
            document.querySelectorAll('.select2').forEach(selectElement => {
              const $select = $(selectElement);
              
              // Get the selected values from Select2
              const selectedValues = $select.val() || [];
              
              console.log(`Field ${selectElement.name}: ${selectedValues}`);
              
              // Make sure the native select element has these values selected
              Array.from(selectElement.options).forEach(option => {
                option.selected = selectedValues.includes(option.value);
              });
            });
            
            // Log entire form data for debugging
            const formData = new FormData(form);
            console.log('Form Data being submitted:');
            for (let [key, value] of formData.entries()) {
              console.log(`  ${key}: ${value}`);
            }
          }, true); // Use capture phase to run early
        }

        // File upload dropzone functionality
        const dropzones = document.querySelectorAll('.dj-palette-file-upload-zone');
        
        dropzones.forEach(zone => {
          const fileInput = zone.querySelector('.dj-palette-file-input-hidden');
          const previewContainer = zone.querySelector('.dj-palette-file-preview');

          // Make sure file input has proper name attribute
          if (fileInput && fileInput.name) {
            console.log(`File input found: ${fileInput.name}`);
          } else {
            console.warn('File input missing name attribute:', fileInput);
          }

          if (!fileInput) return;

          // Click to browse
          zone.addEventListener('click', () => fileInput.click());
          
          // Drag and drop
          zone.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.stopPropagation();
            zone.classList.add('dragover');
          });
          
          zone.addEventListener('dragleave', (e) => {
            e.preventDefault();
            e.stopPropagation();
            zone.classList.remove('dragover');
          });
          
          zone.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
            zone.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
              fileInput.files = files;
              updatePreview(fileInput, previewContainer);
            }
          });
          
          // File input change
          fileInput.addEventListener('change', () => {
            updatePreview(fileInput, previewContainer);
          });
        });
        
        function updatePreview(fileInput, previewContainer) {
          const files = fileInput.files;
          // Only clear existing previews if new files are being added
          if (files.length > 0) {
            previewContainer.innerHTML = '';
          }
          
          if (files.length === 0) return;
          
          Array.from(files).forEach((file, index) => {
            const previewItem = document.createElement('div');
            previewItem.className = 'preview-item';
            
            if (file.type.startsWith('image/')) {
              const reader = new FileReader();
              reader.onload = (e) => {
                previewItem.innerHTML = `
                  <img src="${e.target.result}" alt="Preview">
                  <button type="button" class="remove-file" data-index="${index}" title="Remove">
                    <i class="bi bi-x"></i>
                  </button>
                `;
              };
              reader.readAsDataURL(file);
            } else {
              previewItem.innerHTML = `
                <div class="file-item">
                  <i class="bi bi-file-earmark"></i>
                  <p>${file.name}</p>
                </div>
                <button type="button" class="remove-file" data-index="${index}" title="Remove">
                  <i class="bi bi-x"></i>
                </button>
              `;
            }
            
            previewContainer.appendChild(previewItem);
          });
        }
        
        // Handle Add Related Modal
        const addRelatedModal = document.getElementById('addRelatedModal');
        if (addRelatedModal) {
          const modal = new bootstrap.Modal(addRelatedModal);
          const modalFrame = document.getElementById('relatedItemFrame');
          const modalTitle = document.getElementById('addRelatedModalLabel');
          
          document.querySelectorAll('.add-related-modal').forEach(btn => {
            btn.addEventListener('click', function(e) {
              e.preventDefault();
              const modelName = this.dataset.model;
              const fieldId = this.dataset.fieldId;
              const addUrl = `/admin/core/${modelName}/add/?_to_field=id&_popup=1`;
              
              // Set iframe src and modal title
              modalTitle.textContent = `Add New ${modelName.charAt(0).toUpperCase() + modelName.slice(1)}`;
              modalFrame.src = addUrl;
              
              // Store field ID for later use
              modalFrame.dataset.fieldId = fieldId;
              
              // Show modal
              modal.show();
            });
          });
          
          // Handle popup responses from iframe
          window.dismissAddRelatedModal = function(newId, newLabel) {
            const fieldId = modalFrame.dataset.fieldId;
            const selectElement = document.getElementById(fieldId);
            
            // Add new option to select
            const newOption = document.createElement('option');
            newOption.value = newId;
            newOption.text = newLabel;
            newOption.selected = true;
            selectElement.appendChild(newOption);
            
            // Trigger select2 to refresh
            $(selectElement).val($(selectElement).val()).trigger('change');
            
            // Close modal
            modal.hide();
          };
        }
      }
    );
  </script>
{% endblock extra_scripts %}