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'

export default function InitSettingsModal(props) {
  const [open, setOpen] = useRecoilState(modalState)
  const [canvasSetting, setCanvasSetting] = useRecoilState(canvasSettingState)
  const [roofMaterials, setRoofMaterials] = useState([])
  const [basicSetting, setBasicSettings] = useState({
    type: '1',
    inputType: '1',
    angleType: 'slope',
    roofs: [],
  })

  const { get, post } = useAxios()

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

      setRoofMaterials(res)
    })

    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 addRoofSetting = () => {
    if (basicSetting.roofs.length === 4) {
      alert('지붕재는 최대 4종까지 선택할 수 있습니다.')
      return
    }

    //기본값
    const newRoofSettings = {
      id: basicSetting.roofs.length + 1,
      roofId: '3',
      width: '200',
      height: '200',
      gap: '0',
      layout: 'parallel',
    }

    setBasicSettings((prevState) => ({
      ...prevState,
      roofs: [...prevState.roofs, newRoofSettings],
    }))
  }

  //배열 값 변경 함수
  const handleRoofSettings = (id, event) => {
    const roof = basicSetting.roofs.map((roof, i) => (id === roof.id ? { ...roof, [event.target.name]: event.target.value } : roof))
    setBasicSettings((prevState) => ({
      ...prevState,
      roofs: [...roof],
    }))
  }

  const submitCanvasConfig = () => {
    post({ url: '/api/canvas-config', data: basicSetting }).then((res) => {
      if (!res) {
        setCanvasSetting({ ...basicSetting })
      }
    })
  }

  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="type" orientation="horizontal" value={basicSetting.type} onChange={handleBasicSetting}>
              <Radio value="1">치수 입력에 의한 물건작성</Radio>
            </RadioGroup>
          </div>
        </div>

        <div className="mb-6">
          <div className="flex space-x-4">
            <RadioGroup label="치수 입력방법" name="inputType" orientation="horizontal" value={basicSetting.inputType} 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="angleType" orientation="horizontal" value={basicSetting.angleType} onChange={handleBasicSetting}>
              <Radio value="slope">경사</Radio>
              <Radio value="angle">각도</Radio>
            </RadioGroup>
          </div>
        </div>

        <div className="flex items-center mb-4">
          <button className="px-3 py-1 bg-blue-500 text-white rounded mr-3" onClick={addRoofSetting}>
            Add
          </button>
          <span className="text-sm text-gray-500">※ 지붕재는 최대 4종까지 선택할 수 있습니다.</span>
        </div>

        {basicSetting.roofs &&
          basicSetting.roofs.map((roof, index) => {
            return <RoofSelectBox roofMaterials={roofMaterials} roof={roof} key={index} onChange={handleRoofSettings} />
          })}

        <div className="flex gap-4 items-right">
          <Button size="sm" color="secondary" onClick={submitCanvasConfig}>
            저장
          </Button>
          <Button size="sm" onClick={() => setOpen(!open)}>
            취소
          </Button>
        </div>
      </div>
    </>
  )
}

const RoofSelectBox = (props) => {
  return (
    <div className="mb-4 flex flex-wrap items-center space-x-4" style={{ border: '1px solid black' }}>
      <Select
        aria-label="roofMaterial"
        className={'w-52'}
        name="roofId"
        onChange={(e) => props.onChange(props.roof.id, e)}
        items={props.roofMaterials}
        defaultSelectedKeys={props.roof.roofId ? props.roof.roofId : ''}
        selectedKeys={props.roof.roofId}
        value={props.roof.roofId}
      >
        {(roofMaterial) => (
          <SelectItem key={roofMaterial.id} value={roofMaterial.id}>
            {roofMaterial.name}
          </SelectItem>
        )}
      </Select>
      <Input
        type="text"
        name="width"
        placeholder="너비"
        value={props.roof.width}
        className="w-24"
        onChange={(e) => props.onChange(props.roof.id, e)}
      />
      <Input
        type="text"
        name="height"
        placeholder="높이"
        value={props.roof.height}
        className="w-24"
        onChange={(e) => props.onChange(props.roof.id, e)}
      />
      mm
      <Input type="text" name="gap" placeholder="간격" value={props.roof.gap} className="w-24" onChange={(e) => props.onChange(props.roof.id, e)} />
      mm
      <div className="flex space-x-4">
        <RadioGroup
          orientation="horizontal"
          name="layout"
          value={props.roof.layout}
          defaultValue="parallel"
          onChange={(e) => props.onChange(props.roof.id, e)}
        >
          <Radio value="parallel">병렬식</Radio>
          <Radio value="cascade">계단식</Radio>
        </RadioGroup>
      </div>
    </div>
  )
}
