'use client'

import { useEffect, useState, useContext } from 'react'
import { useRecoilValue } from 'recoil'
import { floorPlanObjectState } from '@/store/floorPlanObjectAtom'
import { SessionContext } from '@/app/SessionProvider'
import { useMessage } from '@/hooks/useMessage'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'
import SingleDatePicker from '../common/datepicker/SingleDatePicker'
import EstimateFileUploader from './EstimateFileUploader'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import { isNotEmptyArray, isObjectNotEmpty } from '@/util/common-utils'
import dayjs from 'dayjs'
import { useCommonCode } from '@/hooks/common/useCommonCode'
import Select from 'react-select'
import { useEstimateController } from '@/hooks/floorPlan/estimate/useEstimateController'

export default function Estimate({ params }) {
  const [objectNo, setObjectNo] = useState('') //물건번호
  const [planNo, setPlanNo] = useState('') //플랜번호
  const [files, setFiles] = useState([]) // 보내는 첨부파일

  const [showContentCode, setShowContentCode] = useState('ATTR001')

  //견적특이사항 접고 펼치기
  const [hidden, setHidden] = useState(false)

  //공통코드
  const { findCommonCode } = useCommonCode()
  const [honorificCodeList, setHonorificCodeList] = useState([]) //경칭 공통코드

  const [startDate, setStartDate] = useState(new Date())
  const singleDatePickerProps = {
    startDate,
    setStartDate,
  }

  const { session } = useContext(SessionContext)
  const objectRecoil = useRecoilValue(floorPlanObjectState)

  //견적서 상세데이터
  const { state, setState } = useEstimateController(params.pid)

  //견적특이사항 상세 데이터 LIST

  //견적특이사항 List
  const [specialNoteList, setSpecialNoteList] = useState([])

  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const { get, post } = useAxios(globalLocaleState)

  const { getMessage } = useMessage()

  const { setMenuNumber } = useCanvasMenu()

  const fileUploadProps = {
    // objectNo: '',
    // planNo: params.pid,
    // category: '10',
    uploadFiles: files,
    setUploadFiles: setFiles,
  }

  useEffect(() => {
    setMenuNumber(5)
    setObjectNo(objectRecoil.floorPlanObjectNo)
    setPlanNo(params.pid)

    // 공통코드
    const code1 = findCommonCode(200800)
    if (code1 != null) {
      setHonorificCodeList(code1)
    }
  }, [])

  useEffect(() => {
    //견적특이사항 API호출
    //여러개 선택하면 구분자로 (、)
    let url = `/api/estimate/special-note-list`
    get({ url: url }).then((res) => {
      if (isNotEmptyArray(res)) {
        if (state?.estimateOption) {
          res.map((row) => {
            let estimateOption = state?.estimateOption?.split('、')
            row.text = false
            estimateOption.map((row2) => {
              if (row2 === row.code) {
                row.text = true
              }
            })
          })
          setSpecialNoteList(res)
        }
      }
    })
  }, [state?.estimateOption])

  //견적일 set
  useEffect(() => {
    let estimateDate = dayjs(startDate).format('YYYY-MM-DD')
    setState({ estimateDate: estimateDate })
  }, [startDate])

  useEffect(() => {
    //선택된 견적특이사항 setState
    if (isNotEmptyArray(specialNoteList)) {
      const liveCheckedData = specialNoteList.filter((row) => row.text === true)

      const data = []
      for (let ele of liveCheckedData) {
        data.push(ele.code)
      }

      const newData = data.join('、')
      setState({ estimateOption: newData })
    }
  }, [specialNoteList])

  // 견적특이사항 remark 보여주기
  const settingShowContent = (code, event) => {
    setShowContentCode(code)
    event.stopPropagation()
  }

  // 첨부파일 state에 넣기
  useEffect(() => {
    // console.log(files)
    if (files.length > 0) {
      files.map((row) => {
        setState({ fileList: row.data })
      })
    } else {
      console.log('첨부파일 없음')
      setState({ fileList: [] })
    }
  }, [files])

  return (
    <div className="sub-content estimate">
      <div className="sub-content-inner">
        {/* 물건번호, 견적서번호, 등록일, 변경일시 시작 */}
        {/* <form onSubmit={handleSubmit(onValid)}> */}
        <div className="sub-content-box">
          <div className="sub-table-box">
            <div className="estimate-list-wrap one">
              <div className="estimate-box">
                <div className="estimate-tit">{getMessage('estimate.detail.objectNo')}</div>
                <div className="estimate-name">
                  {objectNo} (Plan No: {planNo})
                </div>
              </div>
              <div className="estimate-box">
                <div className="estimate-tit">{getMessage('estimate.detail.docNo')}</div>
                <div className="estimate-name">{state.docNo}</div>
              </div>
              <div className="estimate-box">
                <div className="estimate-tit">{getMessage('estimate.detail.drawingEstimateCreateDate')}</div>
                <div className="estimate-name">
                  {state?.drawingEstimateCreateDate ? `${dayjs(state.drawingEstimateCreateDate).format('YYYY.MM.DD')}` : ''}
                </div>
              </div>
              <div className="estimate-box">
                <div className="estimate-tit">{getMessage('estimate.detail.lastEditDatetime')}</div>
                <div className="estimate-name">{state?.lastEditDatetime ? `${dayjs(state.lastEditDatetime).format('YYYY.MM.DD HH:mm')}` : ''}</div>
              </div>
            </div>
          </div>
        </div>
        {/* 물건번호, 견적서번호, 등록일, 변경일시 끝 */}
        {/* 기본정보 시작 */}
        <div className="sub-content-box">
          <div className="sub-table-box">
            <div className="table-box-title-wrap">
              <div className="title-wrap">
                <h3>{getMessage('estimate.detail.header.title')}</h3>
              </div>
            </div>
            <div className="common-table bt-able">
              <table>
                <colgroup>
                  <col style={{ width: '160px' }} />
                  <col />
                  <col style={{ width: '160px' }} />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    {/* 1차 판매점명 */}
                    <th>{getMessage('estimate.detail.saleStoreId')}</th>
                    <td></td>
                    {/* 견적일 */}
                    <th>
                      {getMessage('estimate.detail.estimateDate')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="date-picker" style={{ width: '350px' }}>
                        <SingleDatePicker {...singleDatePickerProps} />
                      </div>
                    </td>
                  </tr>
                  <tr>
                    {/* 2차 판매점명 */}
                    <th>{getMessage('estimate.detail.otherSaleStoreId')}</th>
                    <td></td>
                    {/* 담당자 */}
                    <th>
                      {getMessage('estimate.detail.receiveUser')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="input-wrap" style={{ width: '350px' }}>
                        <input
                          type="text"
                          className="input-light"
                          defaultValue={state?.charger}
                          onChange={(e) => {
                            //담당자 charger
                            setState({ charger: e.target.value })
                          }}
                        />
                      </div>
                    </td>
                  </tr>
                  <tr>
                    {/* 안건명 */}
                    <th>
                      {getMessage('estimate.detail.objectName')} <span className="important">*</span>
                    </th>
                    <td colSpan={3}>
                      <div className="form-flex-wrap">
                        <div className="input-wrap mr5" style={{ width: '610px' }}>
                          <input
                            type="text"
                            className="input-light"
                            defaultValue={state?.objectName}
                            onChange={(e) => {
                              //안건명 objectName
                              setState({ objectName: e.target.value })
                            }}
                          />
                        </div>
                        <div className="select-wrap" style={{ width: '200px' }}>
                          <Select
                            id="objectNameOmit"
                            instanceId="objectNameOmit"
                            className="react-select-custom"
                            classNamePrefix="custom"
                            placeholder="Select"
                            options={honorificCodeList}
                            onChange={(e) => {
                              if (isObjectNotEmpty(e)) {
                                setState({ objectNameOmit: e.clCodeNm })
                              } else {
                                setState({ objectNameOmit: '' })
                              }
                            }}
                            getOptionLabel={(x) => x.clCodeNm}
                            getOptionValue={(x) => x.clCode}
                            isClearable={true}
                            isSearchable={false}
                            value={honorificCodeList.filter(function (option) {
                              return option.clCodeNm === state.objectNameOmit
                            })}
                          />
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    {/* 물건정보에서 입력한 메모 */}
                    <th>{getMessage('estimate.detail.objectRemarks')}</th>
                    <td colSpan={3}>{state?.objectRemarks}</td>
                  </tr>
                  <tr>
                    {/* 주문분류 */}
                    <th>
                      {getMessage('estimate.detail.estimateType')} <span className="important">*</span>
                    </th>
                    <td colSpan={3}>
                      <div className="radio-wrap">
                        <div className="d-check-radio light mr10">
                          <input
                            type="radio"
                            name="estimateType"
                            id="YJSS"
                            value={'YJSS'}
                            checked={state?.estimateType === 'YJSS' ? true : false}
                            onChange={(e) => {
                              setState({ estimateType: e.target.value })
                            }}
                          />
                          <label htmlFor="YJSS">住宅PKG</label>
                        </div>
                        <div className="d-check-radio light">
                          <input
                            type="radio"
                            name="estimateType"
                            id="YJOD"
                            value={'YJOD'}
                            checked={state?.estimateType === 'YJOD' ? true : false}
                            onChange={(e) => {
                              setState({ estimateType: e.target.value })
                            }}
                          />
                          <label htmlFor="YJOD">積上げ( YJOD )</label>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    {/* 지붕재・사양시공 최대4개*/}
                    <th>{getMessage('estimate.detail.roofCns')}</th>
                    <td colSpan={3}>
                      {state?.roofMaterialIdMulti?.split('、').map((row, index) => {
                        //지붕재
                        let roofList = row
                        let roofListLength = state?.roofMaterialIdMulti?.split('、').length
                        let style = 'mb5'
                        if (roofListLength == index + 1) {
                          style = ''
                        }
                        //사양시공
                        let constructSpecificationMulti = state?.constructSpecificationMulti?.split('、')

                        return (
                          <>
                            <div className={`form-flex-wrap ${style}`}>
                              <div className="input-wrap mr5" style={{ width: '610px' }}>
                                <input type="text" className="input-light" defaultValue={roofList} readOnly />
                              </div>
                              <div className="input-wrap" style={{ width: '200px' }}>
                                <input type="text" className="input-light" defaultValue={constructSpecificationMulti[index]} readOnly />
                              </div>
                            </div>
                          </>
                        )
                      })}
                    </td>
                  </tr>
                  <tr>
                    {/* 비고 */}
                    <th>{getMessage('estimate.detail.remarks')}</th>
                    <td colSpan={3}>
                      <div className="input-wrap">
                        <input
                          type="text"
                          className="input-light"
                          defaultValue={state?.remarks}
                          onChange={(e) => {
                            //비고
                            setState({ remarks: e.target.value })
                          }}
                        />
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            {/* 파일첨부 시작 */}
            <div className="table-box-title-wrap">
              <div className="title-wrap">
                <h3>{getMessage('estimate.detail.header.fileList1')}</h3>
                <div className="d-check-box light mr5">
                  <input type="checkbox" id="next" />
                  <label htmlFor="next" style={{ color: '#101010' }}>
                    {getMessage('estimate.detail.nextSubmit')}
                  </label>
                </div>
              </div>
            </div>
            <div className="common-table mb10">
              <table>
                <colgroup>
                  <col style={{ width: '160px' }} />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    <th>{getMessage('estimate.detail.header.fileList1')}</th>
                    <td>
                      <EstimateFileUploader {...fileUploadProps} />
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            {/* 첨부파일 목록 시작 */}
            <div className="common-table bt-able">
              <table>
                <colgroup>
                  <col style={{ width: '160px' }} />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    <th>{getMessage('estimate.detail.header.fileList2')}</th>
                  </tr>
                </tbody>
              </table>
            </div>
            {/* 첨부파일 목록 끝 */}
            {/* 파일첨부 끝 */}
            {/* 견적특이사항 시작 */}
            <div className="table-box-title-wrap">
              <div className="title-wrap">
                <h3 className="product">{getMessage('estimate.detail.header.specialEstimate')}</h3>
                <div className="product_tit">{getMessage('estimate.detail.header.specialEstimateProductInfo')}</div>
              </div>
              <div className="left-unit-box">
                <button className={`estimate-arr-btn down mr5 ${hidden ? '' : 'on'}`} onClick={() => setHidden(false)}></button>
                <button className={`estimate-arr-btn up ${hidden ? 'on' : ''}`} onClick={() => setHidden(true)}></button>
              </div>
            </div>
            {/* 견적 특이사항 코드영역시작 */}
            <div className={`estimate-check-wrap ${hidden ? 'hide' : ''}`}>
              <div className="estimate-check-inner">
                <div className="special-note-check-wrap">
                  {/* SpecialNoteList반복문 */}
                  {specialNoteList.map((row) => {
                    return (
                      <div
                        className="special-note-check-item"
                        onClick={(event) => {
                          settingShowContent(row.code, event)
                        }}
                      >
                        <div className="d-check-box light">
                          <input
                            type="checkbox"
                            id={row.code}
                            checked={!!row.text}
                            disabled={row.code === 'ATTR001' ? true : false}
                            onChange={(event) => {
                              setSpecialNoteList((specialNote) =>
                                specialNote.map((temp) => (temp.code === row.code ? { ...temp, text: !temp.text } : temp)),
                              )
                              settingShowContent(row.code, event)
                            }}
                          />
                          <label htmlFor={row.code}>{row.codeNm}</label>
                        </div>
                      </div>
                    )
                  })}
                </div>
                {/* 견적특이사항 선택한 내용?영역시작 */}
                <div className="calculation-estimate">
                  {specialNoteList.map((row) => {
                    if (row.code === showContentCode) {
                      return (
                        <dl>
                          <dt>{row.codeNm}</dt>
                          <dd>{row.remarks}</dd>
                        </dl>
                      )
                    }
                  })}
                </div>
                {/* 견적특이사항 선택한 내용?영역끝 */}
              </div>
            </div>

            {/* 견적 특이사항 코드영역 끝 */}

            {/* 견적특이사항 영역끝 */}
            {/* 제품정보 시작 */}
            <div className="table-box-title-wrap">
              <div className="title-wrap">
                <h3>{getMessage('estimate.detail.header.specialEstimateProductInfo')}</h3>
              </div>
            </div>
            <div className="esimate-wrap">
              <div className="estimate-list-wrap one">
                <div className="estimate-box">
                  <div className="estimate-tit">{getMessage('estimate.detail.sepcialEstimateProductInfo.totPcs')}</div>
                  <div className="estimate-name blue">74</div>
                </div>
                <div className="estimate-box">
                  <div className="estimate-tit">{getMessage('estimate.detail.sepcialEstimateProductInfo.vol')}</div>
                  <div className="estimate-name blue">8300</div>
                </div>
                <div className="estimate-box">
                  <div className="estimate-tit">{getMessage('estimate.detail.sepcialEstimateProductInfo.netAmt')}</div>
                  <div className="estimate-name blue">6,798,900</div>
                </div>
                <div className="estimate-box">
                  <div className="estimate-tit">{getMessage('estimate.detail.sepcialEstimateProductInfo.vat')}</div>
                  <div className="estimate-name blue">679,890</div>
                </div>
                <div className="estimate-box">
                  <div className="estimate-tit">{getMessage('estimate.detail.sepcialEstimateProductInfo.totPrice')}</div>
                  <div className="estimate-name red">7,478,790</div>
                </div>
              </div>
            </div>
            {/* YJOD면 아래영역 숨김 */}
            <div className="common-table bt-able" style={{ display: state?.estimateType === 'YJSS' ? '' : 'none' }}>
              <table>
                <colgroup>
                  <col style={{ width: '160px' }} />
                  <col />
                  <col style={{ width: '160px' }} />
                  <col />
                  <col style={{ width: '160px' }} />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    <th>
                      {getMessage('estimate.detail.sepcialEstimateProductInfo.pkgUnitPrice')}
                      <span className="important">*</span>
                    </th>
                    <td>
                      <div className="input-wrap">
                        <input type="text" className="input-light" />
                      </div>
                    </td>
                    <th>{getMessage('estimate.detail.sepcialEstimateProductInfo.pkgWeight')}</th>
                    <td>{getMessage('estimate.detail.sepcialEstimateProductInfo.calcFormula1')}</td>
                    <th>{getMessage('estimate.detail.sepcialEstimateProductInfo.pkgPrice')}</th>
                    <td>{getMessage('estimate.detail.sepcialEstimateProductInfo.calcFormula2')}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            {/* 제품정보 끝 */}
            {/* 가격표시영역시작 */}
            <div className="estimate-product-option">
              <div className="product-price-wrap">
                <div className="product-price-tit">{getMessage('estimate.detail.header.showPrice')}</div>
                <div className="select-wrap">
                  <select className="select-light" name="" id="">
                    <option value="">111</option>
                    <option value="">222</option>
                  </select>
                </div>
                <button className="btn-origin grey ml5">{getMessage('estimate.detail.showPrice.btn1')}</button>
              </div>
              <div className="product-edit-wrap">
                <ul className="product-edit-explane">
                  <li className="explane-item item01">
                    <span className="ico"></span>
                    {getMessage('estimate.detail.showPrice.description1')}
                  </li>
                  <li className="explane-item item02">
                    <span className="ico"></span>
                    {getMessage('estimate.detail.showPrice.description2')}
                  </li>
                  <li className="explane-item item03">
                    <span className="ico"></span>
                    {getMessage('estimate.detail.showPrice.description3')}
                  </li>
                  <li className="explane-item item04">
                    <span className="ico"></span>
                    {getMessage('estimate.detail.showPrice.description4')}
                  </li>
                </ul>
                <div className="product-edit-btn">
                  <button className="btn-origin navy mr5" type="submit">
                    <span className="plus"></span>
                    {getMessage('estimate.detail.showPrice.btn2')}
                  </button>
                  <button className="btn-origin grey">
                    <span className="minus"></span>
                    {getMessage('estimate.detail.showPrice.btn3')}
                  </button>
                </div>
              </div>
            </div>
            {/* 가격표시영역끝 */}
            {/* html테이블시작 */}
            <div className="q-grid no-cols"></div>
            {/* html테이블끝 */}
          </div>
        </div>
        {/* 기본정보끝 */}
        {/* </form> */}
      </div>
    </div>
  )
}
