{% extends 'base.html' %}
{% load tailwind_filters %}
{% load legacy_filters %}

{% block title %}Report Dashboard{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8" x-data="COIReport">
  <h1 class="text-2xl font-bold text-gray-800">Export Center</h1>
  <div class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
    <form method='post'>
      {% csrf_token %}
      <div class="flex flex-col gap-3 sm:flex-row sm:items-center">
        <label for="lot-number" class="text-sm font-semibold text-gray-700 sm:min-w-20">Lot No.</label>
        <input id="lot-number" type="text" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-blue-500" placeholder="Enter Lot No." name='lot_no' required x-model="lot_no" value="{{ lot_no }}">
        <button class="shrink-0 rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600" type="submit" name="search_lot">
          Search
        </button>
      </div>
    </form>

    <div class="mt-4">
      <div class="mb-2 inline-flex rounded-md bg-blue-100 px-3 py-1 text-sm font-medium text-blue-700">
        Export Options
      </div>
      <div class="grid grid-cols-1 gap-x-4 gap-y-2 md:grid-cols-2 xl:grid-cols-4">
      {% for key,value in SHEET_NAMES.items %}
      <label class="flex items-center gap-2 text-sm text-gray-700">
        <input type="checkbox" class="rounded" name='exports' value='{{ key }}'
        x-model='exports' required>
        <span>{{ value }}</span>
      </label>
      {% endfor %}
      </div>
    </div>

    <div class="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-3">
      <div>
            <label for="qa1" class="block mb-2 text-sm font-medium text-gray-900">Select QA.1</label>
            <select id="qa1" name="qa1" class="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" x-model='qa1' required>
              <option value="" disabled selected>Choose a user</option>
              {% for user in users %}
              <option value="{{ user.id }}">{{ user.profile }}</option>
              {% endfor %}
            </select>
      </div>
      <div>
            <label for="qa2" class="block mb-2 text-sm font-medium text-gray-900">Select QA.2</label>
            <select id="qa2" name="qa2" class="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" x-model='qa2' required>
              <option value="" disabled selected>Choose a user</option>
              {% for user in users %}
              <option value="{{ user.id }}">{{ user.profile }}</option>
              {% endfor %}
            </select>
      </div>
      <div class="rounded-lg border border-gray-200 bg-gray-50 px-4 py-3">
        <div class="mb-2 text-sm font-medium text-gray-900">Accept Status</div>
        <div class="flex flex-wrap items-center gap-4">
          <label class="flex items-center gap-2 text-sm text-gray-700">
            <input type="radio" name="status" id="accepted" value="accepted" 
              class="rounded" x-model="acceptStatus" />
            <span>Accepted</span>
          </label>
          <label class="flex items-center gap-2 text-sm text-gray-700">
            <input type="radio" name="status" id="special_accepted" value="special_accepted" 
              class="rounded" x-model="acceptStatus" />
            <span>Special Accepted</span>
          </label>
        </div>
      </div>
    </div>

    <div class="mt-4 flex justify-end">
      <div class="w-full rounded-lg border border-blue-100 bg-blue-50 px-4 py-3 lg:w-auto lg:min-w-[28rem]">
        <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div class="flex flex-wrap items-center gap-4">
            <span class="text-sm font-medium text-gray-900">Export Template</span>
            <label class="flex items-center gap-2 text-sm text-gray-700">
              <input type="radio" name="export_template" value="japanese" class="rounded" x-model="exportTemplate" />
              <span>Japanese</span>
            </label>
            <label class="flex items-center gap-2 text-sm text-gray-700">
              <input type="radio" name="export_template" value="asean" class="rounded" x-model="exportTemplate" />
              <span>ASEAN</span>
            </label>
          </div>
          <div class="flex flex-wrap items-center justify-center gap-3 lg:justify-end">
            <button  type='button' class="rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600" 
                                     @click="exportCOI">
              Export Excel
            </button>
            <div class="text-center" x-show="downloadUrl">
              <a :href="downloadUrl"  class="block rounded-md bg-green-600 px-4 py-2 text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2" download x-text="downText">
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <div class="bg-white shadow-md rounded-md p-4">

                <table class="w-full text-left border-collapse border border-gray-300">
                    <tbody>
                        <tr class="bg-blue-100">
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Product Code :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ code }}</td>
                        </tr>
                        <tr>
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Lot No. :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ result.PRO2 }}</td>
                        </tr>
                        <tr class="bg-blue-100">
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Customer :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ result.Japanese_CustomerName}} {{ result.PRO1C }}</td>
                        </tr>
                        <tr>
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Pcs. :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ pcs }}</td>
                        </tr>
                        <tr class="bg-blue-100">
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Shape | Size :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ size_str }}</td>
                        </tr>
                        <tr class="bg-blue-100">
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Tool :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ result.PRO_TOOL }}</td>
                        </tr>
                        <tr>
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Specification :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">{{ spec }}</td>
                        </tr>
                        <tr class="bg-blue-100">
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Inspection Date :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700">-</td>
                        </tr>
                        <tr>
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Inspection Indicate1 :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700"></td>
                        </tr>
                        <tr class="bg-blue-100">
                            <td class="border border-gray-300 px-4 py-2 font-medium text-gray-700">Inspection Indicate2 :</td>
                            <td class="border border-gray-300 px-4 py-2 text-gray-700"></td>
                        </tr>
                    </tbody>
                </table>
                    </div>
</div>
{% for model_name, objs in results.items %}
  {% if objs %}
    {% include "report/_tbl.html" with objs=objs fields=fields|get_item:model_name header=model_name %}
  {% endif %}
{% endfor %}

{% endblock %}
{% block footer_script %}
<style>
/* Remove fixed layout and allow columns to grow dynamically */
table {
    table-layout: auto; /* Default is auto, can be explicitly set */
    width: 100%; /* Ensures table spans available space */
}

th, td {
    white-space: nowrap; /* Prevents text wrapping */
    text-overflow: ellipsis; /* Adds ellipsis for overflowed content if combined with max-width */
    vertical-align: top; /* Aligns content to the top */
}
</style>

<script type="text/javascript">
  function COIReport() {
    return {
      lot_no: '{{ lot_no }}', // Bind this to the input value
      exports: {{ selected_templates|default:"[]"|safe }},
      exportTemplate: '{{ export_template|default:"asean" }}',
      qa1: '{{ current_user_id }}',
      qa2: '{{ qa2_default_user_id }}',
      gen_report_url: '{% url "report:gen_report" %}',
      acceptStatus: 'accepted',
      downloadUrl: null, // Stores the download link after export success
      downText: "Download Excel",
      init() {},
      async exportCOI() {
              if (!this.lot_no) {
                  alert("Please enter a Lot No.");
                  return;
              }
              if (!this.qa1) {
                  alert("Select QA.1");
                  return;
              }
              if (!this.qa2) {
                  alert("Select QA.2");
                  return;
              }
              if (this.exports.length == 0) {
                  alert("Select Export Template");
                  return;
              }

              try {
                  // Make POST request using Axios
                  const response = await axios.post(this.gen_report_url, {
                      lot_no: this.lot_no,
                      exports: this.exports,
                      export_template: this.exportTemplate,
                      qa1: this.qa1,
                      qa2: this.qa2,
                      acceptStatus: this.acceptStatus
                  });
                  this.downText = "Processing ..."
                  if (response.status === 200) {
                      const result = response.data;
                      //alert(`Report generated successfully: ${result.file_url}`);
                      setTimeout(() => {
                        this.downText = "Download Excel"
                      }, 2000);
                      console.log('File URL:', result.file_url);
                      this.downloadUrl = result.file_url; // Set the download URL
                  }else {
                      this.downText = "Error ..."
                  }
              } catch (error) {
                  this.downText = "Error ..."
                  if (error.response) {
                      // Server responded with a status other than 2xx
                      alert(`Error: ${error.response.data.message || 'Failed to generate report'}`);
                      console.error('Error response:', error.response);
                  } else if (error.request) {
                      // Request was made but no response received
                      alert('No response from server.');
                      console.error('Request error:', error.request);
                  } else {
                      // Something else caused the error
                      alert('An unexpected error occurred.');
                      console.error('Unexpected error:', error.message);
                  }
              }
          },
    };
  }
</script>
{% endblock %}
