'use client'

import React, { useEffect } from 'react'
import { useState } from 'react'
import { Input, RadioGroup, Radio, Button, Autocomplete, AutocompleteItem } from '@nextui-org/react'
import RangeDatePicker from '@/components/common/datepicker/RangeDatePicker'
import { useRecoilState, useResetRecoilState } from 'recoil'
import { stuffSearchState } from '@/store/stuffAtom'
import { isEmptyArray } from '@/util/common-utils'
import { get } from '@/lib/Axios'
import dayjs from 'dayjs'
import isLeapYear from 'dayjs/plugin/isLeapYear' // 윤년 판단 플러그인
dayjs.extend(isLeapYear)
import Link from 'next/link'
export default function StuffSearchCondition() {
  //달력 props 관련 날짜 셋팅
  const [dateRange, setDateRange] = useState([dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')])
  const [startRangeDate, endRangeDate] = dateRange

  const rangeDatePickerProps = {
    startRangeDate, //시작일
    endRangeDate, //종료일
    setDateRange,
  }

  //여기서 선택한 검색조건들을 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(endRangeDate).diff(startRangeDate, '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(startRangeDate).format('YYYY-MM-DD'),
      schToDt: dayjs(endRangeDate).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')
    setDateRange([dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'), 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 })
    }
  }

  //x로 날짜 비웠을때 기본값으로 셋팅
  useEffect(() => {
    if (!startRangeDate && !endRangeDate) {
      setDateRange([dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')])
    }
  }, [startRangeDate, endRangeDate])

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

  return (
    <>
      <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>
    </>
  )
}
