{% 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>
  <form method='post'>
    {% csrf_token %}
    <div class="flex items-center gap-2 mb-4">
      <label for="lot-number" class="text-gray-700 font-medium">Lot No. :</label>
      <input id="lot-number" type="text" class="border border-gray-300 rounded px-4 py-2 focus:outline-blue-500" placeholder="Enter Lot No." name='lot_no' required x-model="lot_no" value="{{ lot_no }}">
      <button class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600" type="submit" name="search_lot">
        🔍
      </button>
    </div>
  </form>
      <button class="bg-blue-100 text-blue-700 px-4 py-2 rounded hover:bg-blue-200">
        Option for Export :
      </button>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        {% for key,value in SHEET_NAMES.items %}
        <label class="flex items-center space-x-1">
          <input type="checkbox" class="rounded" name='exports' value='{{ key }}'
          x-model='exports' required>
          <span>{{ value }}</span>
        </label>
        {% endfor %}
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div class="my-4">
            <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 class="my-4">
            <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>
        <div class="flex justify-end my-3 space-x-4">
          <div class="flex items-center space-x-4 my-4">
            <!-- Radio button for 'Accepted' -->
            <label class="flex items-center space-x-2">
              <input type="radio" name="status" id="accepted" value="accepted" 
                class="rounded" x-model="acceptStatus" />
              <span>Accepted</span>
            </label>

            <!-- Radio button for 'Special Accepted' -->
            <label class="flex items-center space-x-2">
              <input type="radio" name="status" id="special_accepted" value="special_accepted" 
                class="rounded" x-model="acceptStatus" />
              <span>Special Accepted</span>
            </label>
          </div>
          <div>
            <button  type='button' class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600" 
                                   @click="exportCOI">
              Export Excel
            </button>
          </div>
          <!-- TODO: add download here -->
          <div class=" text-center" x-show="downloadUrl">
            <a :href="downloadUrl"  class="block px-4 py-2 bg-green-600 text-white  rounded-md 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 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 }},
      qa1: null,
      qa2: null,
      gen_report_url: '{% url "report:gen_report" %}', 
      acceptStatus: 'accepted', 
      downloadUrl: null, // Stores the download link after export success
      downText: "Download Excel",
      init() {
        //alert("COI Report");
        this.qa1 = '';
        this.qa2 = '';
      },
      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,
                      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 %}
