<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bot History</title>
  <script src="../utils/Utils.js"></script>
</head>

<body>

<button onclick="back()">Back</button>

<p>
  <label for="startDate">Start Date:</label>
  <input type="date" id="startDate" required>

  <br>

  <label for="endDate">End Date :</label>
  <input type="date" id="endDate" required>

  <br>

  <button onclick="fetchHistory()">Apply</button>
</p>

<h3 id="totalNetProfit"></h3>

<h1>Pool Table</h1>
<table id="resultsTable">
  <thead>
  <tr>
    <th>Date</th>
    <th>Sell sum</th>
    <th>Buy sum</th>
    <th>Net profit</th>
    <th>Avg total size</th>
    <th>Additional total size</th>
    <th>Grid</th>
  </tr>
  </thead>
  <tbody></tbody>
</table>
</body>

</html>

<style>
  table {
    width: 100%;
    border-collapse: collapse;
    background-color: #ffffff;
  }

  th,
  td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
  }

  tr:hover {
    background-color: #f1f1f1;
  }

  .details {
    display: none;
    background-color: #f2f2f2;
  }
</style>

<script>

  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString)
  const botId = urlParams.get('botId')

  const token = localStorage.getItem('t')

  const resultsTableBody = document.querySelector('#resultsTable tbody');

  function back() {
    history.back()
  }

  document.addEventListener('DOMContentLoaded', function () {
    initDateRange()
    fetchHistory()
  })

  function getDateRange() {
    const startDate = document.getElementById('startDate').value
    const endDate = document.getElementById('endDate').value
    return [startDate, endDate]
  }

  function initDateRange() {
    const startDate = document.getElementById('startDate')
    const endDate = document.getElementById('endDate')

    const today = new Date()
    endDate.value = today.toISOString().split('T')[0]

    const startOfWeek = new Date(today);
    startOfWeek.setDate(today.getDate() - today.getDay()); // Get Sunday
    const startOfWeekInput = document.getElementById('startOfWeek');
    startDate.value = startOfWeek.toISOString().split('T')[0];
  }

  async function fetchHistory() {
    dates = getDateRange()
    startDate = dates[0]
    endDate = dates[1]
    try {
      const payload = {
        method: 'GET',
        headers: {
          "Auth": token
        }
      }
      const response = await fetch(BACKEND_URL + '/api/getResults?' + "botId=" + botId + '&startDate=' + startDate + '&endDate=' + endDate, payload);

      checkIsValidResponse(response)

      if (!response.ok) {
        response.text().then(text => {
          alert(JSON.parse(text).msg)
        })
      }
      const json = await response.json();

      results = json.data.results
      console.log(results);

      document.getElementById("totalNetProfit").innerHTML = "Total net profit: " + json.data.total_net_profit.toFixed(3) + " USDT"

      displayResults(results)
    } catch (error) {
      console.error('Failed to fetch bots:', error);
    }
  }

  function displayResults(results) {
    resultsTableBody.innerHTML = ''
    results.forEach((result, index) => {
      displayResult(result, index)
    })
  }

  function displayResult(result, index) {
    // const timestamp = result.pool_id.split("_")[1]

    const row = document.createElement('tr');
    row.innerHTML = `
                <td>${formatTime(result.finish_timestamp) || "-"}</td>
                <td>${result.sell_sum}</td>
                <td>${result.buy_sum}</td>
                <td>${result.net_profit.toFixed(3)}</td>
                <td>${result.avg_total_size}</td>
                <td>${result.add_total_size}</td>
                <td>${result.executed_grid_count}/${result.total_grid_count}</td>
        `;

    row.addEventListener('click', () => toggleDetails(result.pool_id, index));
    resultsTableBody.appendChild(row);

    // Details row
    const detailsRow = document.createElement('tr');
    detailsRow.classList.add('details');
    resultsTableBody.appendChild(detailsRow);
    detailsRow.innerHTML = `<td id="${result.pool_id}" colspan="7"></td>`;
  }

  function toggleDetails(poolId, index) {
    const detailsRow = document.querySelectorAll('.details')[index];
    detailsRow.style.display = detailsRow.style.display === 'table-row' ? 'none' : 'table-row';
    loadDetails(poolId, detailsRow)
  }

  async function loadDetails(poolId, detailsRow) {
    document.getElementById(poolId).innerHTML = `Loading...`
    try {
      const payload = {
        method: 'GET',
        headers: {
          "Auth": token
        }
      }
      const response = await fetch(BACKEND_URL + '/api/getOrders?poolId=' + poolId, payload);
      if (!response.ok) {
        response.text().then(text => {
          alert(JSON.parse(text).msg)
        })
      }
      const json = await response.json();

      orders = json.data
      document.getElementById(poolId).innerHTML = ``
      createTitlesForOrders(poolId)
      orders.forEach(order => {
        displayOrder(detailsRow, order)
      });
    } catch (error) {
      console.error('Failed to fetch bots:', error);
    }
  }

  function createTitlesForOrders(poolId) {
    const orderRow = document.createElement('tr');
    orderRow.innerHTML = `
            <tr>
                <th>Order ID</th>
                <th>Order Size</th>
                <th>Instrument ID</th>
                <th>Order Type</th>
                <th>Create Time</th>
                <th>Fill Time</th>
                <th>Fill Price</th>
                <th>Order state</th>
                <th>Fee</th>
                <th>Fee Ccy</th>
                <th>Side</th>
                <th>Accomulated fill sise</th>
                <th>Avarage fill price</th>
                    <th>Details</th>
            </tr>
        `;
    document.getElementById(poolId).appendChild(orderRow);
  }

  function displayOrder(detailsRow, order) {
    console.log(order);
    const orderRow = document.createElement('tr');
    orderRow.innerHTML = `
        <tr>
            <td>${order.order_id || order.algo_client_id || "-"}</td>
            <td>${order.order_size || "-"}</td>
            <td>${order.inst_id || "-"}</td>
            <td>${order.order_type || "-"}</td>
            <td>${formatTime(order.create_time)}</td>
            <td>${formatTime(order.fill_time)}</td>
            <td>${order.fill_price || "-"}</td>
            <td>${order.state || "-"}</td>
            <td>${order.fee || "-"}</td>
            <td>${order.fee_ccy || "-"}</td>
            <td>${order.side || "-"}</td>
            <td>${order.accumulated_fill_size || "-"}</td>
            <td>${order.average_fill_price || "-"}</td>
            <td>${order.details || "-"}</td>
        </tr>
        `;

    document.getElementById(order.pool_id).appendChild(orderRow);
  }

</script>