import TemplateService from "../templates/templateService.js";

class TestItems {
  constructor() {
    this._item = new rxjs.BehaviorSubject(null);
    this._items = new rxjs.BehaviorSubject([]);
  }

  set item(value) {
    this._item.next(value);
  }

  get item$() {
    return this._item.asObservable();
  }

  get items$() {
    return this._items.asObservable();
  }

  getItems(invoiceID) {
    const url = admin_url + 'invoice_product_items/get_invoice_items';
    const data = { invoiceID };

    return new rxjs.Observable((observer) => {
      $.ajax({
        url,
        method: 'POST',
        dataType: 'json',
        data,
        success: (response) => {
          this._items.next(response);
          observer.next(response);
          observer.complete();
        },
        error: (error) => {
          observer.error(error);
        }
      });
    });
  }

  deleteItem(itemIndex) {
    return new rxjs.Observable((observer) => {
      this._items.pipe(rxjs.take(1)).subscribe((items) => {
        const updatedItems = items.filter((item, index) => index !== itemIndex);
        this._items.next(updatedItems);
        observer.next(true);
        observer.complete();
      });
    });
  }

  setItem(itemIndex) {
    return new rxjs.Observable((observer) => {
      this._items.pipe(rxjs.take(1)).subscribe((items) => {
        if (Array.isArray(items) && items.length > itemIndex) {
          const selectedItem = items[itemIndex];
          this._item.next(selectedItem); // Update _item with the selected item
          observer.next(selectedItem);
          observer.complete();
        } else {
          observer.error('Item not found');
        }
      });
    });
  }

  updateItem(itemIndex, updatedFields) {
    return new rxjs.Observable((observer) => {
      this._items.pipe(rxjs.take(1)).subscribe((items) => {
        if (Array.isArray(items) && items.length > itemIndex) {
          const updatedItems = [...items];
          const currentItem = updatedItems[itemIndex];
          updatedItems[itemIndex] = {
            ...currentItem,
            ...updatedFields,
          };
          this._items.next(updatedItems);
          observer.next(updatedItems);
          observer.complete();
        } else {
          observer.error('Item not found');
        }
      });
    });
  }

  handleDeleteButtonClick(event, items) {
    const itemIndex = event.target.getAttribute('data-item-index');
    // Call deleteItem function or perform any desired action
    this.deleteItem(items[itemIndex]);
  }

  getItemTemplate() {
    return `
    <div class="flex flex-row sortable items-center py-2">
      <div class="flex-1 dragger-container max-w-xs">
        <div class="dragger dragger-spacer"></div>
      </div>
      <div class="w-full grid-columns gap-3 p-5 hover-bg-gray hover-bg-gray-50 items-center grid-cols-26 border-solid border-1 border-gray-200 shadow-sm">
        <!-- NO + drag-->
        <div class="col-span-1 p-2 max-w-ws flex border-r-1 justify-center border-gray-200 border-solid">
          <%= index + 1 %>
        </div>
    
        <!-- Denumire-->
        <div class="col-span-8 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span><%= item.description %></span>
        </div>
    
        <!-- Descriere -->
        <div class="col-span-7 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span><%= item.long_description %></span>
        </div>
    
        <!-- Cod produs -->
        <div class="col-span-3 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span><%= item.sku %></span>
        </div>
    
        <!-- UM -->
        <div class="col-span-1 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span><%= item.unit %></span>
        </div>
    
        <!-- Cantitate -->
        <div class="col-span-1 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span><%= item.qty %></span>
        </div>
    
        <!-- CotaTVA-->
        <div class="col-span-2 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer justify-center">
          <span><%= item.taxname %></span>
        </div>
    
        <!-- Currency -->
        <div class="col-span-1 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span>
            <% const selectedCurrency = item.currencies.find(currency => currency.id === item.currency); %>
            <%= selectedCurrency ? selectedCurrency.name : '' %>
          </span>
        </div>
    
        <!-- Price -->
        <div class="col-span-1 p-2 flex border-r-1 border-gray-200 border-solid cursor-pointer">
          <span><%= item.rate %></span>
        </div>
    
        <!-- Denumire -->
        <div class="col-span-1 p-2 flex border-r-1 justify-end">
          <div class="flex flex-row">
            <i class="fa-regular fa-pen text-indigo-200 mr-6 cursor-pointer editInvoiceItem" data-item-index="<%= index %>"></i>
            <i class="fa-solid fa-xmark text-red-400 cursor-pointer deleteInvoiceItem" data-item-index="<%= index %>"></i>
          </div>
        </div>
      </div>
    </div>
    `;
  }

  getItemDeleteModalTemplate(itemIndex, reference) {
    return `
      <div class="modal fade" id="${reference}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <center><h4 class="modal-title" id="myModalLabel">Stergere produs</h4></center>
            </div>
            <div class="modal-body">
              <h4 class="text-center">Esti sigur ca vrei sa stergi acest produs?</h4>
              <h2 class="text-center"></h2>
            </div>
            <div class="flex justify-center pb-10">
              <button type="button" class="btn btn-default mr-3" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> RENUNTA</button>
              <button type="button" id="invoice_itamable_itemsModalEditDelete${itemIndex}" data-item-index="${itemIndex}" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> DA</button>
            </div>
          </div>
        </div>
      </div>
    `;
  }

  getItemFormModal(itemIndex, reference, item) {
    return `
      <div class="modal fade" id="${reference}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
        <div class="modal-dialog modal-lg" role="document">
          <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header bg-gray-600 h-16 text-white flex flex-0 items-center">
              <h5 class="modal-title" id="myModalLabel">Modificare produs</h5>
              <button type="button" class="close ml-auto" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
  
            <!-- Modal Body -->
            <div class="modal-body py-5 px-10">
              <!-- Form -->
              <form role="form">
                <div class="grid-columns grid-cols-4 gap-6 w-full">
                  <div class="form-group col-span-4">
                    <label for="item_description_${itemIndex}">Denumire</label>
                    <input type="text" name="item_description_${itemIndex}" id="item_description_${itemIndex}" class="form-control" value="${item.description}" required>
                  </div>
  
                  <div class="form-group col-span-4">
                    <label for="item_long_description_${itemIndex}">Descriere</label>
                    <input type="text" name="item_long_description_${itemIndex}" id="item_long_description_${itemIndex}" class="form-control" value="${item.long_description}" required>
                  </div>

                  <div class="form-group col-span-2">
                    <label for="item_um_${itemIndex}">UM</label>
                    <input type="text" name="item_um_${itemIndex}" id="item_um_${itemIndex}" value="${item.unit}" class="form-control">
                  </div>

                  <div class="form-group col-span-2">
                    <label for="item_qty_${itemIndex}">Cantitate</label>
                    <input type="number" name="item_qty_${itemIndex}" id="item_qty_${itemIndex}" class="form-control" value="${item.qty}">
                  </div>
  
                  <div class="form-group col-span-2">
                    <label for="item_cota_${itemIndex}">Cota TVA</label>
                    <select name="item_cota_${itemIndex}" id="item_cota_${itemIndex}" class="form-control" required>
                      ${item.taxes
                        .map((tax) => `<option value="${tax.name}" ${tax.name === item.taxname ? 'selected' : ''}>${tax.name}</option>`)
                        .join('')}
                    </select>
                  </div>

                  <div class="form-group col-span-2">
                    <label for="item_currency_${itemIndex}">Moneda</label>
                    <select name="item_currency_${itemIndex}" id="item_currency_${itemIndex}" class="form-control" required>
                      ${item.currencies
                        .map((currency) => `<option value="${currency.id}" ${currency.id === item.currency ? 'selected' : ''}>${currency.name}</option>`)
                        .join('')}
                    </select>
                  </div>
  
                  <div class="form-group col-span-2">
                    <label for="item_sku_${itemIndex}">Cod</label>
                    <input type="text" name="item_sku_${itemIndex}" id="item_sku_${itemIndex}" class="form-control" value="${item.sku}" required>
                  </div>

                  <div class="form-group col-span-2">
                    <label for="item_price_converted_${itemIndex}">Pret</label>
                    <input type="text" name="item_price_converted_${itemIndex}" id="item_price_converted_${itemIndex}" class="form-control" value="${item.rate}" required>
                  </div>
                </div>  
                <div class="flex justify-end">
                  <button type="submit" id="invoice_itemable_itemsModalEditSubmit_${itemIndex}" data-item-index="${itemIndex}" class="btn btn-primary mt-10">Submit</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    `;
  }
  
  
  
  
  // Function to render item using underscore template
  renderTemplate(template, data) {
    const compiledTemplate = _.template(template);
    return compiledTemplate(data);
  }
}

export default TestItems;