'use client'

import { useEffect, useState, memo, useCallback } from 'react'
import { Button, Checkbox, CheckboxGroup, RadioGroup, Radio, Input, Select, SelectItem } from '@nextui-org/react'
import { useRecoilState, useRecoilValue } from 'recoil'
import { modalContent, modalState } from '@/store/modalAtom'
import { canvasSettingState } from '@/store/canvasAtom'
import { useAxios } from '@/hooks/useAxios'
import { get, post } from '@/lib/Axios'

export default function InitSettingsModal(props) {
  const [objectNo, setObjectNo] = useState('test123240909003') // 후에 삭제 필요
  const [open, setOpen] = useRecoilState(modalState)
  const [canvasSetting, setCanvasSetting] = useRecoilState(canvasSettingState)
  const [roofMaterials, setRoofMaterials] = useState([])
  const [basicSetting, setBasicSettings] = useState({
    roofDrawingSet: '1',
    roofSizeSet: '1',
    roofAngleSet: 'slope',
    roofs: [{ roofSeq: '1', roofType: '3', roofWidth: '200', roofHeight: '200', roofGap: '0', roofLayout: 'parallel' }],
  })

  const modelProps = {
    open,
    setOpen,
  }

  //const { get, post } = useAxios()

  useEffect(() => {
    get({ url: '/api/roof-material/roof-material-infos' }).then((res) => {
      //TODO: error handling
      if (!res) return

      setRoofMaterials(res)
    })

    get({ url: `/api/canvas-management/canvas-basic-settings/by-object/${objectNo}` }).then((res) => {
      if (res.length == 0) return

      // 'roofs' 배열을 생성하여 각 항목을 추가
      const roofsRow = res.map((item) => {
        return {
          roofDrawingSet: String(item.roofDrawingSet),
          roofSizeSet: String(item.roofSizeSet),
          roofAngleSet: item.roofAngleSet,
        }
      })

      const roofsArray = res.some((item) => !item.roofSeq)
        ? //최초 지붕재 추가 정보의 경우 roofsArray를 초기화 설정
          [{ roofSeq: '1', roofType: '3', roofWidth: '200', roofHeight: '200', roofGap: '0', roofLayout: 'parallel' }]
        : res.map((item) => ({
            roofSeq: String(item.roofSeq),
            roofType: String(item.roofType),
            roofWidth: String(item.roofWidth),
            roofHeight: String(item.roofHeight),
            roofGap: String(item.roofGap),
            roofLayout: item.roofLayout,
          }))

      // 나머지 데이터와 함께 'roofs' 배열을 patternData에 넣음
      const patternData = {
        roofDrawingSet: roofsRow[0].roofDrawingSet, // 첫 번째 항목의 값을 사용
        roofSizeSet: roofsRow[0].roofSizeSet, // 첫 번째 항목의 값을 사용
        roofAngleSet: roofsRow[0].roofAngleSet, // 첫 번째 항목의 값을 사용
        roofs: roofsArray, // 만들어진 roofs 배열
      }

      // 데이터 설정
      setBasicSettings({ ...patternData })
    })

    if (!(Object.keys(canvasSetting).length === 0 && canvasSetting.constructor === Object)) {
      setBasicSettings({ ...canvasSetting })
    }
  }, [])

  //기본 설정값 변경 함수
  const handleBasicSetting = (event) => {
    const newBasicSetting = { ...basicSetting, [event.target.name]: event.target.value }
    setBasicSettings(newBasicSetting)
  }

  //배열 값 변경 함수
  const handleRoofSettings = (id, event) => {
    // 기본 세팅에서 roofs 배열을 복사
    const updatedRoofs = [...basicSetting.roofs]

    // roofSeq가 id와 일치하는 항목의 인덱스 찾기
    const index = updatedRoofs.findIndex((roof) => roof.roofSeq === id)

    if (index !== -1) {
      // 해당 인덱스의 항목을 수정
      updatedRoofs[index] = {
        ...updatedRoofs[index],
        [event.target.name]: event.target.value,
      }

      // 수정된 배열을 상태에 반영
      setBasicSettings((prevState) => ({
        ...prevState,
        roofs: updatedRoofs,
      }))
    }
  }

  //저장
  const submitCanvasConfig = async () => {
    if (!objectNo) {
      alert('object_no를 입력하세요.')
      return
    }

    const patternData = {
      objectNo,
      roofDrawingSet: basicSetting.roofDrawingSet,
      roofSizeSet: basicSetting.roofSizeSet,
      roofAngleSet: basicSetting.roofAngleSet,
      roofMaterialsAddList: basicSetting.roofs,
    }
    await post({ url: `/api/canvas-management/canvas-basic-settings`, data: patternData })

    //Recoil 설정
    setCanvasSetting({ ...basicSetting })

    // 저장 후 재조회
    //await handleSelect()
  }

  return (
    <>
      <div className="container mx-auto mt-10 p-6 bg-white shadow-lg rounded-lg">
        <div className="text-lg font-semibold mb-4">배치면 초기설정</div>

        <div className="mb-6">
          <div className="flex space-x-4">
            <RadioGroup
              label="도면 작성방법"
              name="roofDrawingSet"
              orientation="horizontal"
              value={basicSetting.roofDrawingSet}
              onChange={handleBasicSetting}
            >
              <Radio value="1">치수 입력에 의한 물건작성</Radio>
            </RadioGroup>
          </div>
        </div>

        <div className="mb-6">
          <div className="flex space-x-4">
            <RadioGroup
              label="치수 입력방법"
              name="roofSizeSet"
              orientation="horizontal"
              value={basicSetting.roofSizeSet}
              onChange={handleBasicSetting}
            >
              <Radio value="1">복사도 입력</Radio>
              <Radio value="2">실측값 입력</Radio>
              <Radio value="3">육지붕</Radio>
            </RadioGroup>
          </div>
        </div>

        <div className="mb-6">
          <div className="flex space-x-4">
            <RadioGroup
              label="지붕각도 설정"
              name="roofAngleSet"
              orientation="horizontal"
              value={basicSetting.roofAngleSet}
              onChange={handleBasicSetting}
            >
              <Radio value="slope">경사</Radio>
              <Radio value="angle">각도</Radio>
            </RadioGroup>
          </div>
        </div>
        <RadioGroup label="지붕재 추가(단위 : mm)" />
        {/* Roofs Array Rendering */}
        {basicSetting.roofs &&
          basicSetting.roofs.map((roof, index) => {
            return (
              <div key={index} className="mb-4 flex flex-wrap items-center space-x-4" style={{ border: '1px solid black' }}>
                <span> 타입 : </span>
                <Select
                  aria-label="roofMaterial"
                  className={'w-52'}
                  name="roofType"
                  onChange={(e) => handleRoofSettings(roof.roofSeq, e)}
                  items={roofMaterials}
                  defaultSelectedKeys={roof.roofType ? [roof.roofType] : []}
                  selectedKeys={roof.roofType}
                  value={roof.roofType}
                >
                  {(roofMaterial) => (
                    <SelectItem key={roofMaterial.id} value={roofMaterial.id}>
                      {roofMaterial.name}
                    </SelectItem>
                  )}
                </Select>
                <span> 너비 : </span>
                <Input
                  type="text"
                  name="roofWidth"
                  placeholder="너비"
                  value={roof.roofWidth}
                  className="w-24"
                  onChange={(e) => handleRoofSettings(roof.roofSeq, e)}
                />
                mm
                <span> 높이 : </span>
                <Input
                  type="text"
                  name="roofHeight"
                  placeholder="높이"
                  value={roof.roofHeight}
                  className="w-24"
                  onChange={(e) => handleRoofSettings(roof.roofSeq, e)}
                />
                mm
                <span> 서까래 간격 : </span>
                <Input
                  type="text"
                  name="roofGap"
                  placeholder="간격"
                  value={roof.roofGap}
                  className="w-24"
                  onChange={(e) => handleRoofSettings(roof.roofSeq, e)}
                />
                mm
                <div className="flex space-x-4">
                  <RadioGroup
                    orientation="horizontal"
                    name="roofLayout"
                    value={roof.roofLayout}
                    defaultValue="parallel"
                    onChange={(e) => handleRoofSettings(roof.roofSeq, e)}
                  >
                    <Radio value="parallel">병렬식</Radio>
                    <Radio value="cascade">계단식</Radio>
                  </RadioGroup>
                </div>
              </div>
            )
          })}

        <div className="flex gap-4 items-right">
          <Button size="sm" color="secondary" onClick={submitCanvasConfig}>
            저장
          </Button>
          <Button size="sm" onClick={() => setOpen(!open)}>
            취소
          </Button>
          <input type="text" placeholder="Object No 입력" value={objectNo} onChange={(e) => setObjectNo(e.target.value)} />
        </div>
      </div>
    </>
  )
}
