document.addEventListener('DOMContentLoaded', function () {
  const terminateAction = document.getElementById('terminateAction');
  const finishAction = document.getElementById('finishAction');

  const gridItems = document.querySelectorAll('.gridItem');
  const runButton = document.getElementById('run');
  const stopButton = document.getElementById('stop');

  const exitAppButton = document.getElementById('exitAppButton');

  const stackerStartButton = document.getElementById('stackerStartButton');
  const stackerStopButton = document.getElementById('stackerStopButton');

  const upDownOnButton = document.getElementById('upDownOnButton');
  const upDownOffButton = document.getElementById('upDownOffButton');

  const leftRightOnButton = document.getElementById('leftRightOnButton');
  const leftRightOffButton = document.getElementById('leftRightOffButton');

  let selectedGridId = null; // 선택된 그리드 ID
  let intervalId = null; // setInterval ID
  let isRunning = false; // 한줄쌓기 실행 상태

  // 초기 상태 설정
  stopButton.disabled = true;
  runButton.disabled = true;

  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));
  }

  // JSON 파일에서 데이터 로드
  function fetchJsonData() {
    fetch('/static/json/oneLine.json')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((data) => {
        updateGridStatus(data);
      })
      .catch((error) => console.error('Error loading JSON:', error));
  }

  // 초기 데이터 로드
  fetchJsonData();

  // 그리드 상태 업데이트 함수
  function updateGridStatus(data) {
    const grids = ['grid1', 'grid2', 'grid3', 'grid4'];

    // 그리드 비활성화 초기화
    gridItems.forEach((item) => item.classList.remove('disabled'));

    grids.forEach((grid) => {
      if (data[grid].currentLayerHeight > 720) {
        document.getElementById(grid).classList.add('disabled');
      }
    });

    if (data.grid4.currentLayerHeight > data.grid2.currentLayerHeight) {
      document.getElementById('grid2').classList.add('disabled');
    }

    if (data.grid3.currentLayerHeight > data.grid1.currentLayerHeight) {
      document.getElementById('grid1').classList.add('disabled');
    }

    // 선택된 그리드의 currentLayerIndex 출력
    if (selectedGridId) {
      const selectedGridData = data[selectedGridId];
      document.getElementById(
        'currentLayerIndexDisplay'
      ).textContent = `현재 쌓고 있는 단 : ${
        selectedGridData.currentLayerIndex + 1
      }`;
    }

    // 한줄쌓기 실행 중인 경우 그리드 비활성화 유지
    if (isRunning) {
      toggleGridItems(true);
    }
  }

  // 그리드 아이템 클릭 핸들러
  function handleGridItemClick(event) {
    const item = event.currentTarget;
    if (item.classList.contains('disabled')) {
      return; // 클릭 이벤트 무시
    }
    gridItems.forEach((btn) => btn.classList.remove('selected'));
    item.classList.add('selected');
    selectedGridId = item.id;
    checkRunButtonState();
  }

  gridItems.forEach((item) => {
    item.addEventListener('click', handleGridItemClick);
  });

  // 한줄쌓기 실행 버튼 클릭 핸들러
  runButton.addEventListener('click', function () {
    runButton.disabled = true;
    stopButton.disabled = false;
    isRunning = true;
    toggleGridItems(true);

    intervalId = setInterval(fetchJsonData, 5000);

    fetch('/one_line_run', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: 'one_line_run',
        gridId: selectedGridId, // 선택된 그리드 아이템의 ID 전송
      }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('one_line_run failed.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : one_line_run api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) =>
        console.error('Error sending one_line_run action:', error)
      );
  });

  // 한줄쌓기 멈춤 버튼 클릭 핸들러
  stopButton.addEventListener('click', function () {
    runButton.disabled = false;
    stopButton.disabled = true;
    isRunning = false;
    toggleGridItems(false);
    clearGridSelection();

    // JSON 데이터 주기적으로 가져오기 중지
    clearInterval(intervalId);

    // 멈춤 버튼 클릭 시 JSON 데이터 다시 로드
    fetchJsonData();

    fetch('/one_line_stop', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message: 'one_line_stop' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('one_line_stop failed.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : one_line_stop api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) =>
        console.error('Error sending one_line_stop action:', error)
      );
  });

  // 한줄쌓기 실행 버튼 활성화 여부 확인 함수
  function checkRunButtonState() {
    const anyGridSelected = Array.from(gridItems).some((item) =>
      item.classList.contains('selected')
    );

    runButton.disabled = !anyGridSelected;
  }

  // 그리드 아이템 활성화/비활성화 함수
  function toggleGridItems(disable) {
    gridItems.forEach((item) => item.classList.toggle('disabled', disable));
  }

  // 그리드 아이템 선택 해제 함수
  function clearGridSelection() {
    gridItems.forEach((item) => item.classList.remove('selected'));
    checkRunButtonState(); // 선택 해제 후 버튼 상태 재확인
  }

  finishAction.addEventListener('click', function () {
    finishAction.disabled = true;
    fetch('/robot_immediately_take_book', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        immediately_take_book: 'robot_immediately_take_book',
      }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('immediately_take_book failed.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : robot_immediately_take_book api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) =>
        console.error('Error Sending robot finish action:', error)
      )
      .finally(() => {
        setTimeout(() => {
          finishAction.disabled = false;
        }, 10000);
      });
  });

  terminateAction.addEventListener('click', function () {
    fetch('/robot_finish_action', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'robot_finish_action' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send robot finish action.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : terminateAction api sent successfully - oneLineProgress.js'
        );

        window.location.href = '/';
      })
      .catch((error) =>
        console.error('Error sending robot finish action:', error)
      );
  });

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

  stackerStartButton.addEventListener('click', function () {
    fetch('/stacker_start', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'stacker_start' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send stacker start.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : stacker_start api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) => console.error('Error sending stacker start:', error));
  });

  stackerStopButton.addEventListener('click', function () {
    fetch('/stacker_stop', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'stacker_stop' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send stacker stop.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : stacker_stop api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) => console.error('Error sending stacker stop:', error));
  });

  upDownOnButton.addEventListener('click', function () {
    fetch('/updown_on', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'updown_on' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send updown on');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : updown_on api sent successfully - oneLineProgress.js');
      })
      .catch((error) => console.error('Error sending updown on:', error));
  });

  upDownOffButton.addEventListener('click', function () {
    fetch('/updown_off', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'updown_off' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send updown off');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : updown_off api sent successfully - oneLineProgress.js');
      })
      .catch((error) => console.error('Error sending updown off:', error));
  });

  leftRightOnButton.addEventListener('click', function () {
    fetch('/leftright_on', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'leftright_on' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send leftright on');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : leftright_on api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) => console.error('Error sending leftright on:', error));
  });

  leftRightOffButton.addEventListener('click', function () {
    fetch('/leftright_off', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'leftright_off' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send leftright off');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : leftright_off api sent successfully - oneLineProgress.js'
        );
      })
      .catch((error) => console.error('Error sending leftright off:', error));
  });
});
