const bookCenterPosition_Wheel = [
  { x: 450.5, y: 105 },
  { x: 450.5, y: 320 },
  { x: 148.5, y: 105 },
  { x: 148.5, y: 320 },
];
const bookCenterPosition_Flat = [
  { x: 750, y: 148.5 },
  { x: 535, y: 148.5 },
  { x: 320, y: 148.5 },
  { x: 105, y: 148.5 },
  { x: 750, y: 450.5 },
  { x: 535, y: 450.5 },
  { x: 320, y: 450.5 },
  { x: 105, y: 450.5 },
];

const woodenWheelPallet = {
  palletWidth: 620,
  palletLength: 442,
  palletHeight: 653,
  bookCenterPosition_Wheel,
};
const ironWheelPallet = {
  palletWidth: 620,
  palletLength: 442,
  palletHeight: 633,
  bookCenterPosition_Wheel,
};
const woodenFlatPallet = {
  palletWidth: 878,
  palletLength: 638,
  palletHeight: 148,
  bookCenterPosition_Flat,
};

const pallets = {
  woodenWheelPallet,
  ironWheelPallet,
  woodenFlatPallet,
};

document.addEventListener('DOMContentLoaded', function () {
  const sendPaletteInfoButton = document.getElementById('sendPaletteInfo');
  const startRobotMove = document.getElementById('startRobotButton');
  const resetButton = document.getElementById('resetButton');
  const exitAppButton = document.getElementById('exitAppButton');
  const palletHeightInput = document.getElementById('palletHeight');
  const palletHeightTitle = document.getElementById('palletHeightTitle');

  const stackingButtons = document.querySelectorAll('.leftbuttonBox button');
  let stackingSelected = false;

  const palletButtons = document.querySelectorAll('.buttonBox button');
  let selectedPalletId = null;

  const woodenFlatPalletButton = document.getElementById('woodenFlatPallet');

  let isStartclicked = false;

  function customAlert(msg) {
    const alert = document.getElementById('alert');
    const text = document.getElementById('alert_msg');
    if (msg) {
      alert.style.display = 'flex';
      text.innerText = msg;
    } else {
      alert.style.display = 'none';
      text.innerText = '';
    }
  }

  function logAction(message) {
    fetch('/writelog', {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain',
      },
      body: message,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to write log.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(`Log result: ${data}`);
      })
      .catch((error) => console.error('Error writing log:', error));
  }

  stackingButtons.forEach((button) => {
    button.addEventListener('click', () => {
      stackingButtons.forEach((btn) => btn.classList.remove('selected'));
      button.classList.add('selected');
      stackingSelected = true;
      stackingButtons.forEach((btn) => btn.classList.remove('disabled'));

      // pallet 버튼의 선택 상태를 해제
      palletButtons.forEach((btn) => {
        btn.classList.remove('selected');
        btn.disabled = false; // pallet 버튼을 활성화 상태로 되돌림
      });
      selectedPalletId = null;
      sendPaletteInfoButton.disabled = true;

      if (button.id === 'oneLineButton') {
        woodenFlatPalletButton.classList.add('disabled');
        woodenFlatPalletButton.disabled = true;
        palletHeightInput.style.display = 'none';
        palletHeightTitle.style.display = 'none';
      } else if (button.id === 'normalButton') {
        woodenFlatPalletButton.classList.remove('disabled');
        woodenFlatPalletButton.disabled = false;
      }

      logAction(`FE : Stacking button ${button.id} clicked - layer.js`);
    });
  });

  palletButtons.forEach((button) => {
    button.addEventListener('click', () => {
      if (!stackingSelected) {
        alert('⛔ 쌓기 버튼을 먼저 선택해주세요!');
        return;
      }
      palletButtons.forEach((btn) => btn.classList.remove('selected'));
      button.classList.add('selected');
      selectedPalletId = button.id;
      sendPaletteInfoButton.disabled = false;

      if (selectedPalletId === 'woodenFlatPallet') {
        palletHeightInput.style.display = 'block';
        palletHeightTitle.style.display = 'block';
      } else {
        palletHeightInput.style.display = 'none';
        palletHeightTitle.style.display = 'none';
      }

      logAction(`FE : Pallet button ${button.id} clicked - layer.js`);
    });
  });

  sendPaletteInfoButton.addEventListener('click', function () {
    let palletHeight = pallets[selectedPalletId].palletHeight; // 기본 높이를 사용
    if (selectedPalletId === 'woodenFlatPallet') {
      palletHeight = parseFloat(palletHeightInput.value);
      if (isNaN(palletHeight) || palletHeight <= 0) {
        alert('⛔ 유효한 팔레트 높이를 입력해주세요!');
        return;
      }
    }

    if (selectedPalletId) {
      const selectedPallet = pallets[selectedPalletId];
      selectedPallet.palletHeight = palletHeight; // update the pallet height

      fetch('/update_pallet', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(selectedPallet),
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error('Failed to send palette info.');
          }
          return response.text();
        })
        .then((data) => {
          if (data == 'Success') {
            startRobotMove.disabled = false;
            sendPaletteInfoButton.style.backgroundColor = '#34b800';
            isStartclicked = false;
            logAction('FE : update_pallet api sent successfully - layer.js');
          }
        })
        .catch((error) => console.error('Error sending palette info:', error));
    } else {
      alert('⛔ 팔레트를 선택해주세요!');
    }
  });

  startRobotMove.addEventListener('click', function () {
    logAction('FE : startRobotMove button clicked - layer.js');

    if (selectedPalletId) {
      let confirmResult = confirm('로봇 동작을 시작하시겠습니까?');
      if (confirmResult && isStartclicked == false) {
        isStartclicked = true;

        const selectedPallet = pallets[selectedPalletId];

        const selectedStackingButton = document.querySelector(
          '.leftbuttonBox .selected'
        );

        let btnId = '';

        if (selectedStackingButton.id === 'normalButton') {
          btnId = 'normalButton';
          window.location.href = '/progress';
        } else if (selectedStackingButton.id === 'oneLineButton') {
          btnId = 'oneLineButton';
          window.location.href = '/oneLineProgress';
        }

        const data = { selectedPallet, btnId, selectedPalletId };
        customAlert('로봇 동작을 시작합니다...');

        fetch('/robot_start', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
        })
          // 지금 현재 상황 (2024.10.10 문제점 : .then아래로 안내려옴 문제 해결 필요 시급)
          .then((response) => {
            if (!response.ok) {
              throw new Error('Failed to send palette info.');
            }
            return response.text();
          })
          .then((data) => {
            console.log(data);
            logAction(
              'FE : robot_start function(server) finish successfully - layer.js'
            );
          })
          .catch((error) =>
            console.error('Error sending palette info:', error)
          );
      }
    } else {
      alert('⛔ 팔레트를 선택해주세요!');
    }
  });

  resetButton.addEventListener('click', function () {
    fetch('/reset_data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message: 'Reset button clicked' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send reset data.');
        }
        return response.text();
      })
      .then((data) => {
        if (data == 'Success') {
          logAction('FE : reset_data api sent successfully - layer.js');
        }
      })
      .catch((error) => console.error('Error sending reset data:', error));
  });

  exitAppButton.addEventListener('click', function () {
    fetch('/shutdown', {
      method: 'POST',
    })
      .then((response) => response.text())
      .then((data) => {
        console.log(data);
        logAction('FE : shutdown api sent successfully - layer.js');
      })
      .catch((error) => console.error('Error shutting down:', error));
  });
});
