'use client'

import React, { useEffect } from 'react'
import { useState } from 'react'
import { Autocomplete, AutocompleteItem } from '@nextui-org/react'
import { useAxios } from '@/hooks/useAxios'
import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil'
import { globalLocaleStore } from '@/store/localeAtom'

import RangeDatePicker from '@/components/common/datepicker/RangeDatePicker'
import { stuffSearchState } from '@/store/stuffAtom'
import { isEmptyArray } from '@/util/common-utils'
import dayjs from 'dayjs'
import isLeapYear from 'dayjs/plugin/isLeapYear' // 윤년 판단 플러그인
dayjs.extend(isLeapYear)
import Link from 'next/link'
import SingleDatePicker from '../common/datepicker/SingleDatePicker'
export default function StuffSearchCondition() {
  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const { get } = useAxios(globalLocaleState)

  //달력 props 관련 날짜 셋팅
  const [startDate, setStartDate] = useState(dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'))
  const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))

  const rangeDatePickerProps1 = {
    startDate, //시작일
    setStartDate,
  }

  const rangeDatePickerProps2 = {
    startDate: endDate, //종료일
    setStartDate: setEndDate,
  }

  //여기서 선택한 검색조건들을 recoil로 관리
  const resetStuffRecoil = useResetRecoilState(stuffSearchState)
  const [stuffSearch, setStuffSearch] = useRecoilState(stuffSearchState)
  const [objectNo, setObjectNo] = useState('') //물건번호
  const [saleStoreId, setSaleStoreId] = useState('') //판매대리점ID
  const [address, setAddress] = useState('') //물건주소
  const [objectName, setobjectName] = useState('') //물건명
  const [saleStoreName, setSaleStoreName] = useState('') //판매대리점명
  const [specDateYn, setSpecDateYn] = useState('') //사양 확인('', 'Y', 'N')
  const [receiveUser, setReceiveUser] = useState('') //담당자
  const [dispCompanyName, setDispCompanyName] = useState('') //견적처
  const [dateType, setDateType] = useState('U') //갱신일(U)/등록일(R)
  const [schSelSaleStoreId, setSchSelSaleStoreId] = useState('') //판매대리점 선택

  const [schSelSaleStoreList, setSchSelSaleStoreList] = useState([]) //판매대리점 자동완성 SELECT
  // 조회
  const onSubmit = () => {
    let diff = dayjs(endDate).diff(startDate, 'day')
    if (diff > 366) {
      return alert('최대1년 조회 가능합니다.')
    }

    setStuffSearch({
      schObjectNo: stuffSearch?.schObjectNo ? stuffSearch.schObjectNo : objectNo,
      schSaleStoreId: stuffSearch?.schSaleStoreId ? stuffSearch.schSaleStoreId : saleStoreId,
      schAddress: stuffSearch?.schAddress ? stuffSearch.schAddress : address,
      schObjectName: stuffSearch?.schObjectName ? stuffSearch.schObjectName : objectName,
      schSaleStoreName: stuffSearch?.schSaleStoreName ? stuffSearch.schSaleStoreName : saleStoreName,
      schSpecDateYn: stuffSearch?.schSpecDateYn ? stuffSearch.schSpecDateYn : specDateYn,
      schReceiveUser: stuffSearch?.schReceiveUser ? stuffSearch.schReceiveUser : receiveUser,
      schDispCompanyName: stuffSearch?.schDispCompanyName ? stuffSearch.schDispCompanyName : dispCompanyName,
      schDateType: stuffSearch?.schDateType ? stuffSearch.schDateType : dateType,
      schFromDt: dayjs(startDate).format('YYYY-MM-DD'),
      schToDt: dayjs(endDate).format('YYYY-MM-DD'),
      code: 'E',
      schSelSaleStoreId: stuffSearch?.schSelSaleStoreId ? stuffSearch.schSelSaleStoreId : schSelSaleStoreId,
      startRow: stuffSearch?.startRow ? stuffSearch.startRow : 1,
      endRow: stuffSearch?.endRow ? stuffSearch.endRow : 100,
      schSortType: stuffSearch?.schSortType ? stuffSearch.schSortType : 'R',
    })
  }

  //초기화
  const resetRecoil = () => {
    setObjectNo('')
    setSaleStoreId('')
    setAddress('')
    setobjectName('')
    setSaleStoreName('')
    setSpecDateYn('')
    setReceiveUser('')
    setDispCompanyName('')
    setDateType('U')
    setStartDate(dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'))
    setEndDate(dayjs(new Date()).format('YYYY-MM-DD'))
    setSchSelSaleStoreId('')
    resetStuffRecoil()
  }

  useEffect(() => {
    get({ url: `/api/object/saleStore/201TES01/list` }).then((res) => {
      if (!isEmptyArray(res)) {
        // console.log('판매점 결과:::::', res)
        setSchSelSaleStoreList(res)
      }
    })
  }, [])

  //판매대리점 자동완성 변경
  const onSelectionChange = (key) => {
    // console.log('자동완성값변경', key)
    if (key == null) {
      setSchSelSaleStoreId('')
      setStuffSearch({ ...stuffSearch, schSelSaleStoreId: '' })
    } else {
      setSchSelSaleStoreId(key)
      setStuffSearch({ ...stuffSearch, schSelSaleStoreId: key })
    }
  }

  useEffect(() => {
    setStartDate(stuffSearch?.schFromDt ? stuffSearch.schFromDt : dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'))
    setEndDate(stuffSearch?.schToDt ? stuffSearch.schToDt : dayjs(new Date()).format('YYYY-MM-DD'))
  }, [stuffSearch])

  return (
    <>
      {/* 퍼블적용시작 */}
      <div className="sub-table-box">
        <div className="table-box-title-wrap">
          <div className="title-wrap">
            <h3>물건현황</h3>
          </div>
          <div className="left-unit-box">
            <Link href="/management/stuff/tempdetail">
              <button type="button" className="btn-origin navy mr5">
                물건신규등록버튼
              </button>
            </Link>
            <button type="button" className="btn-origin navy mr5" onClick={onSubmit}>
              조회
            </button>
            <button type="button" className="btn-origin grey" onClick={resetRecoil}>
              초기화
            </button>
          </div>
        </div>
        <div className="common-table">
          <table>
            <colgroup>
              <col style={{ width: '160px' }} />
              <col />
              <col style={{ width: '160px' }} />
              <col />
              <col style={{ width: '160px' }} />
              <col />
            </colgroup>
            <tbody>
              <tr>
                <th>물건번호</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      placeholder="물건번호 입력"
                      value={stuffSearch?.code === 'E' ? stuffSearch.schObjectNo : objectNo}
                      onChange={(e) => {
                        setObjectNo(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schObjectNo: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>판매대리점명</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      placeholder="판매대리점ID 입력"
                      value={stuffSearch?.schSaleStoreId ? stuffSearch.schSaleStoreId : saleStoreId}
                      onChange={(e) => {
                        setSaleStoreId(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schSaleStoreId: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>물건주소</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      placeholder="물건주소 입력"
                      value={stuffSearch?.schAddress ? stuffSearch.schAddress : address}
                      onChange={(e) => {
                        setAddress(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schAddress: e.target.value })
                      }}
                    />
                  </div>
                </td>
              </tr>
              <tr>
                <th>물건명</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      placeholder="물건명 입력"
                      value={stuffSearch?.schObjectName ? stuffSearch.schObjectName : objectName}
                      onChange={(e) => {
                        setobjectName(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schObjectName: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>견적처</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      placeholder="견적처 입력"
                      value={stuffSearch?.schDispCompanyName ? stuffSearch.schDispCompanyName : dispCompanyName}
                      onChange={(e) => {
                        setDispCompanyName(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schDispCompanyName: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>판매대리점 선택</th>
                <td>
                  {/* <div className="select-wrap">
                    <select className="select-light" name="" id=""></select>
                  </div> */}
                  {schSelSaleStoreList?.length > 0 && (
                    <Autocomplete
                      className="max-w-xs"
                      label="판매대리점선택"
                      defaultItems={schSelSaleStoreList}
                      selectedKey={stuffSearch?.schSelSaleStoreId ? stuffSearch.schSelSaleStoreId : schSelSaleStoreId}
                      onSelectionChange={onSelectionChange}
                    >
                      {(option) => <AutocompleteItem key={option.saleStoreId}>{option.saleStoreName}</AutocompleteItem>}
                    </Autocomplete>
                  )}
                </td>
              </tr>
              <tr>
                <th>담당자</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      placeholder="담당자 입력"
                      value={stuffSearch?.schReceiveUser ? stuffSearch.schReceiveUser : receiveUser}
                      onChange={(e) => {
                        setReceiveUser(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schReceiveUser: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>기간검색</th>
                <td colSpan={3}>
                  <div className="form-flex-wrap">
                    <div className="radio-wrap mr10">
                      <div className="d-check-radio light mr10">
                        <input
                          type="radio"
                          name="radio_ptype"
                          id="radio_u"
                          checked={stuffSearch?.schDateType === 'U' ? true : false}
                          value={'U'}
                          onChange={(e) => {
                            setDateType(e.target.value)
                            setStuffSearch({ ...stuffSearch, code: 'S', schDateType: e.target.value })
                          }}
                        />
                        <label htmlFor="radio_u">갱신일</label>
                      </div>
                      <div className="d-check-radio light">
                        <input
                          type="radio"
                          name="radio_ptype"
                          id="radio_r"
                          checked={stuffSearch?.schDateType === 'R' ? true : false}
                          value={'R'}
                          onChange={(e) => {
                            setDateType(e.target.value)
                            setStuffSearch({ ...stuffSearch, code: 'S', schDateType: e.target.value })
                          }}
                        />
                        <label htmlFor="ra05">등록일</label>
                      </div>
                    </div>
                    <div className="date-picker-wrap">
                      <div className="date-picker" style={{ flex: 1 }}>
                        <SingleDatePicker {...rangeDatePickerProps1} />
                      </div>
                      <span> ~ </span>
                      <div className="date-picker" style={{ flex: 1 }}>
                        <SingleDatePicker {...rangeDatePickerProps2} />
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      {/* 퍼블적용끝 */}
      {/* <div align="right">
        <Link href="/management/stuff/tempdetail">
          <button type="button">물건신규등록</button>
        </Link>
        <Button size="sm" onClick={onSubmit}>
          조회
        </Button>
        <Button size="sm" onClick={resetRecoil}>
          초기화
        </Button>
      </div>
      <div className="w-full flex flex-col gap-4">
        {Array(4)
          .fill()
          .map((_, i) => {
            if (i === 0) {
              return (
                <div key={i} className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4">
                  <input
                    type="text"
                    placeholder="물건번호 입력"
                    value={stuffSearch?.code === 'E' ? stuffSearch.schObjectNo : objectNo}
                    onChange={(e) => {
                      setObjectNo(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schObjectNo: e.target.value })
                    }}
                  />
                  <input
                    type="text"
                    placeholder="판매대리점ID 입력"
                    value={stuffSearch?.schSaleStoreId ? stuffSearch.schSaleStoreId : saleStoreId}
                    onChange={(e) => {
                      setSaleStoreId(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schSaleStoreId: e.target.value })
                    }}
                  />
                  <input
                    type="text"
                    placeholder="물건주소 입력"
                    value={stuffSearch?.schAddress ? stuffSearch.schAddress : address}
                    onChange={(e) => {
                      setAddress(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schAddress: e.target.value })
                    }}
                  />
                </div>
              )
            } else if (i === 1) {
              return (
                <div key={i} className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4">
                  <input
                    type="text"
                    placeholder="물건명 입력"
                    value={stuffSearch?.schObjectName ? stuffSearch.schObjectName : objectName}
                    onChange={(e) => {
                      setobjectName(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schObjectName: e.target.value })
                    }}
                  />
                  <input
                    type="text"
                    placeholder="물건명 입력"
                    value={stuffSearch?.schSaleStoreName ? stuffSearch.schSaleStoreName : saleStoreName}
                    onChange={(e) => {
                      setSaleStoreName(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schSaleStoreName: e.target.value })
                    }}
                  />
                  <div>
                    <input
                      type="radio"
                      name="radio_sayang"
                      id="radio_all"
                      checked={stuffSearch?.schSpecDateYn === '' ? true : false}
                      value={''}
                      onChange={(e) => {
                        setSpecDateYn(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schSpecDateYn: e.target.value })
                      }}
                    />
                    <label htmlFor="radio_all">ALL</label>
                  </div>
                  <div>
                    <input
                      type="radio"
                      name="radio_sayang"
                      id="radio_y"
                      checked={stuffSearch?.schSpecDateYn === 'Y' ? true : false}
                      value={'Y'}
                      onChange={(e) => {
                        setSpecDateYn(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schSpecDateYn: e.target.value })
                      }}
                    />
                    <label htmlFor="radio_y">사양 확인</label>
                  </div>
                  <div>
                    <input
                      type="radio"
                      name="radio"
                      id="radio_n"
                      checked={stuffSearch?.schSpecDateYn === 'N' ? true : false}
                      value={'N'}
                      onChange={(e) => {
                        setSpecDateYn(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schSpecDateYn: e.target.value })
                      }}
                    />
                    <label htmlFor="radio_n">사양 미확인</label>
                  </div>
                </div>
              )
            } else if (i === 2) {
              return (
                <div key={i} className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4">
                  <input
                    type="text"
                    placeholder="담당자 입력"
                    value={stuffSearch?.schReceiveUser ? stuffSearch.schReceiveUser : receiveUser}
                    onChange={(e) => {
                      setReceiveUser(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schReceiveUser: e.target.value })
                    }}
                  />
                  <input
                    type="text"
                    placeholder="견적처 입력"
                    value={stuffSearch?.schDispCompanyName ? stuffSearch.schDispCompanyName : dispCompanyName}
                    onChange={(e) => {
                      setDispCompanyName(e.target.value)
                      setStuffSearch({ ...stuffSearch, code: 'S', schDispCompanyName: e.target.value })
                    }}
                  />
                  {schSelSaleStoreList?.length > 0 && (
                    <Autocomplete
                      className="max-w-xs"
                      label="판매대리점선택"
                      defaultItems={schSelSaleStoreList}
                      selectedKey={stuffSearch?.schSelSaleStoreId ? stuffSearch.schSelSaleStoreId : schSelSaleStoreId}
                      onSelectionChange={onSelectionChange}
                    >
                      {(option) => <AutocompleteItem key={option.saleStoreId}>{option.saleStoreName}</AutocompleteItem>}
                    </Autocomplete>
                  )}
                </div>
              )
            } else {
              return (
                <div key={i} className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4">
                  <div>
                    <input
                      type="radio"
                      name="radio_ptype"
                      id="radio_u"
                      checked={stuffSearch?.schDateType === 'U' ? true : false}
                      value={'U'}
                      onChange={(e) => {
                        setDateType(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schDateType: e.target.value })
                      }}
                    />
                    <label htmlFor="radio_u">갱신일</label>
                  </div>
                  <div>
                    <input
                      type="radio"
                      name="radio_ptype"
                      id="radio_r"
                      checked={stuffSearch?.schDateType === 'R' ? true : false}
                      value={'R'}
                      onChange={(e) => {
                        setDateType(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schDateType: e.target.value })
                      }}
                    />
                    <label htmlFor="radio_r">등록일</label>
                  </div>
                  <RangeDatePicker {...rangeDatePickerProps} />
                </div>
              )
            }
          })}
      </div> */}
    </>
  )
}
