'use client'

import React, { useEffect, useState } from 'react';
//import { useMutation } from "react-query";

import { Button } from '@nextui-org/react'

import { get, post } from '@/lib/Axios'

export default function Settings() {
  
  //초기 상태 설정
  //화면 표시1
  const [selectedIndices1, setSelectedIndices1] = useState(['N','N','N','N','N','N','N','N','N','N','N']);
  //화면 표시2
  const [selectedIndices2, setSelectedIndices2] = useState(['N','N','N']);
  //흡착 범위 설정 (default:극소)
  const [selectedIndices3, setSelectedIndices3] = useState(0);
  //그리드 설정
  const [selectedIndices4, setSelectedIndices4] = useState([]);

  const [gridItems1, setGridItems1] = useState([
    '할당 표시', 
    '도면 표시', 
    '그리드 표시',
    '문자 표시',
    '흐름방향 표시',
    '복도치수 표시',
    '실제치수 표시',
    '치수 표시 없음',
    '가대 표시',
    '좌표 표시',
    '도면전환 표시']);
  const [gridItems2, setGridItems2] = useState(['테두리만', '라인해치', 'All Painted']);
  const [gridItems3, setGridItems3] = useState(['극소', '소', '중', '대']);
  const [gridItems4, setGridItems4] = useState(['임의 그리드', '실선 그리드', '점 그리드', '그리드 색 설정', '흡착점 추가']);

  // 클릭 시 상태 변경 함수
  //화면 표시1
  const handleClick1 = (index) => {
    setSelectedIndices1((prevSelectedIndices) => {
      if (prevSelectedIndices.includes(index)) {
        // 이미 선택된 경우, 선택 해제 (리스트에서 제거)
        return prevSelectedIndices.filter((i) => i !== index);
      } else {
        // 선택되지 않은 경우, 리스트에 추가
        return [...prevSelectedIndices, index];
      }
    });
  };

  //화면 표시2
  const handleClick2 = (index) => {
    setSelectedIndices2((prevSelectedIndices) => {
      if (prevSelectedIndices.includes(index)) {
        // 이미 선택된 경우, 선택 해제 (리스트에서 제거)
        return prevSelectedIndices.filter((i) => i !== index);
      } else {
        // 선택되지 않은 경우, 리스트에 추가
        return [...prevSelectedIndices, index];
      }
    });
  };

  //흡착 범위 설정
  const handleClick3 = (index) => {
    setSelectedIndices3(index);
  };

  //그리드 설정
  const handleClick4 = (index) => {
    setSelectedIndices4((prevSelectedIndices) => {
      if (prevSelectedIndices.includes(index)) {
        // 이미 선택된 경우, 선택 해제 (리스트에서 제거)
        return prevSelectedIndices.filter((i) => i !== index);
      } else {
        // 선택되지 않은 경우, 리스트에 추가
        return [...prevSelectedIndices, index];
      }
    });
  };

  // 제출 post
  // const postMutation = useMutation(
  //   (formData) =>
  //     axios.post("http://서버주소", formData, {
  //       headers: {
  //         "Content-Type": "multipart/form-data",
  //       },
  //     }),
  //   {
  //     onSuccess: () => {
  //       alert("제출 완료 되었습니다.");
  //       setShowModal(false);
  //     },
  //     onError: (error) => {
  //       // 에러 처리
  //       console.error("Error:", error);
  //     },
  //   },
  // );


  const handleSubmit = async (e) => {
    e.preventDefault();

    let tempCnt1 = [0,1,2,3,4,5,6,7,8,9,10]
    let display1 = ['N','N','N','N','N','N','N','N','N','N','N']

    //화면 표시1 data
    for (let i = 0; i < tempCnt1.length; i++) {
      for (let j = 0; j < selectedIndices1.length; j++) {
        if (i == selectedIndices1[j]) {          
          display1[i] = "Y"
        }
      }
    }

    let tempCnt2 = [0,1,2]
    let display2 = ['N','N','N']
    
    //화면 표시2 data
    for (let i = 0; i < tempCnt2.length; i++) {
      for (let j = 0; j < selectedIndices2.length; j++) {
        if (i == selectedIndices2[j]) {          
          display2[i] = "Y"
        }
      }
    }

    //흡착 범위 설정
    let rangeSetting = selectedIndices3

    //견적서 번호 << objectNo 받아와야 함.
    let objectNo = 'test123240829010'

	  // 유저가 올린 데이터를 데이터로 만들어주는 부분
    const patternData = {
      objectNo : objectNo,
      assignDisplay : display1[0],
      drawDisplay : display1[1],
      gridDisplay : display1[2],
      charDisplay : display1[3],
      flowDisplay : display1[4],
      hallwayDimenDisplay : display1[5],
      actualDimenDisplay : display1[6],
      noDimenDisplay : display1[7],
      trestleDisplay : display1[8],
      coordiDisplay : display1[9],
      drawConverDisplay : display1[10],
      onlyBorder : display2[0],
      lineHatch : display2[1],
      allPainted : display2[2],
      adsorpRangeSetting : rangeSetting,
    }
    console.log("patternData : ", patternData)

    // Canvas Setting 등록
    await post({ url: '/api/canvas-management/canvas-settings', data : patternData })

  };

  // Canvas Setting 조회
  useEffect(() => {
    get({ url: '/api/canvas-management/canvas-settings/by-object/test123240829010' }).then((res) => {    
      const arrangeData = res.map((item) => {

        console.log("item : ", item)

        return {
          objectNo : item.objectNo,
          assignDisplay : item.assignDisplay,
          drawDisplay : item.drawDisplay,
          gridDisplay : item.gridDisplay,
          charDisplay : item.charDisplay,
          flowDisplay : item.flowDisplay,
          hallwayDimenDisplay : item.hallwayDimenDisplay,
          actualDimenDisplay : item.actualDimenDisplay,
          noDimenDisplay : item.noDimenDisplay,
          trestleDisplay : item.trestleDisplay,
          coordiDisplay : item.coordiDisplay,
          drawConverDisplay : item.drawConverDisplay,
          onlyBorder : item.onlyBorder,
          lineHatch : item.lineHatch,
          allPainted : item.allPainted,
          adsorpRangeSetting : item.adsorpRangeSetting,
        }
      })
      
      // 가공된 데이터를 상태에 저장
      //setArrangeData(arrangeData);

      let assignDisplay = ""
      let drawDisplay = ""
      let gridDisplay = ""
      let charDisplay = ""
      let flowDisplay = ""
      let hallwayDimenDisplay = ""
      let actualDimenDisplay = ""
      let noDimenDisplay = ""
      let trestleDisplay = ""
      let coordiDisplay = ""
      let drawConverDisplay = ""
      let display1 = []

      {arrangeData.map((gridYn1) => (
        assignDisplay = gridYn1.assignDisplay,
        drawDisplay = gridYn1.drawDisplay,
        gridDisplay = gridYn1.gridDisplay,
        charDisplay = gridYn1.charDisplay,
        flowDisplay = gridYn1.flowDisplay,
        hallwayDimenDisplay = gridYn1.hallwayDimenDisplay,
        actualDimenDisplay = gridYn1.actualDimenDisplay,
        noDimenDisplay = gridYn1.noDimenDisplay,
        trestleDisplay = gridYn1.trestleDisplay,
        coordiDisplay = gridYn1.coordiDisplay,
        drawConverDisplay = gridYn1.drawConverDisplay
      ))}
      
      display1 = [assignDisplay, drawDisplay, gridDisplay, charDisplay, flowDisplay, hallwayDimenDisplay, 
        actualDimenDisplay, noDimenDisplay, trestleDisplay, coordiDisplay, drawConverDisplay]

      //console.log("display1 : ", display1)
      //console.log("gridItems1 : ", gridItems1)

      //초기화
      //배열 전체 삭제
      selectedIndices1.splice(0,11)

      //화면 표시1 data
      for (let i = 0; i < 11; i++) {
        display1.forEach((data, i) => {

          if ('Y' == data) {
            selectedIndices1[i] = i
          }
        })
      }
      setSelectedIndices1(selectedIndices1)       
             
      let onlyBorder = ""
      let lineHatch = ""
      let allPainted = ""
      let display2 = []

      {arrangeData.map((gridYn2) => (
        onlyBorder = gridYn2.onlyBorder,
        lineHatch = gridYn2.lineHatch,
        allPainted = gridYn2.allPainted
      ))}
      
      display2 = [onlyBorder, lineHatch, allPainted]

      //console.log("display2 : ", display2)
      //console.log("gridItems2 : ", gridItems2)

      //초기화
      // 배열 전체 삭제
      selectedIndices2.splice(0,3)

      //화면 표시2 data
      for (let i = 0; i < 3; i++) {
        display2.forEach((data, i) => {
          if ('Y' == data) {
            selectedIndices2[i] = i
          }
        })
      }
      setSelectedIndices2(selectedIndices2)       
             
      let adsorpRangeSetting = 0
      {arrangeData.map((gridItems3) => (
        adsorpRangeSetting = gridItems3.adsorpRangeSetting        
      ))}

      setSelectedIndices3(Number(adsorpRangeSetting))

    })
  }, [])
  
  return (
    <>
      <div className="container mx-auto p-4 m-4 border">
        <div align="right">
          <Button onClick={handleSubmit}>저장</Button>
        </div>
        <div className="container mx-auto p-4 m-4 border">
        <h1>[디스플레이 설정]</h1>
          <h1>* 도면에 표시할 항목을 클릭하면 적용 됩니다.</h1>
          <div className="grid-container2">
            {gridItems1.map((item1, index) => (
              <div
                key={index}
                className={`grid-item ${
                  selectedIndices1.includes(index) ? 'selected' : 'unselected'
                }`}
                onClick={() => handleClick1(index)}
              >
                {selectedIndices1.includes(index) ? 'Y' : 'N'} {item1}
              </div>
            ))}
          </div>  
          <br/>
          <h1>* 화면 표시</h1>
          <div className="grid-container3">
          {gridItems2.map((item2, index) => (
              <div
                key={index}
                className={`grid-item ${
                  selectedIndices2.includes(index) ? 'selected' : 'unselected'
                }`}
                onClick={() => handleClick2(index)}
              >
                {selectedIndices2.includes(index) ? 'Y' : 'N'} {item2}
              </div>
            ))}
          </div>
        <h1>[글꼴/도면크기 설정]</h1>
        <h1>* 글꼴 및 크기 변경</h1>
          <div className="grid-container2">
            <div className="grid-item">문자 글꼴 변경</div>
            <div className="grid-item">흐름방향 글꼴 변경</div>
            <div className="grid-item">치수 글꼴 변경</div>
            <div className="grid-item">회로번호 글꼴 변경</div>
          </div>
          <h1>* 흡착 범위 설정</h1>
          <div className="grid-container4">
            {gridItems3.map((item3, index) => (
              <div
                key={index}
                className={`grid-item ${selectedIndices3 === index ? 'selected' : 'unselected'}`}
                onClick={() => handleClick3(index)}
              >
                {selectedIndices3 === index ? 'Y' : 'N'} {item3}
              </div>
            ))}            
          </div>
          <div className="grid-container3">
            <div className="grid-item">치수선 설정</div>
            <div className="grid-item">도면 크기 설정</div>
            <div className="grid-item">흡착점 ON</div>
          </div>

        <h1>[그리드 설정]</h1>
          <div className="grid-container2 border">
            {gridItems4.map((item4, index) => (
              <div
                key={index}
                className={`grid-item ${
                  selectedIndices4.includes(index) ? 'selected' : 'unselected'
                }`}
                onClick={() => handleClick4(index)}
              >
                {selectedIndices4.includes(index) ? 'Y' : 'N'} {item4}
              </div>
            ))}
          </div>  
        </div>
      </div>
    </>
  )
}
