'use client'

import React, { useState, useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Input, RadioGroup, Radio, Button, Autocomplete, AutocompleteItem, Select, SelectItem, Checkbox, Textarea, button } from '@nextui-org/react'
import Link from 'next/link'
import { get } from '@/lib/Axios'
import { queryStringFormatter } from '@/util/common-utils'
import dayjs from 'dayjs'
import { useForm } from 'react-hook-form'
export default function StuffDetail() {
  const router = useRouter()
  const searchParams = useSearchParams()

  //form
  const formInitValue = {
    // 물건번호 T...(임시) R...(진짜)
    dispCompanyName: '', //담당자
    objectStatusId: '0', //물건구분(신축:0 기축 : 1)
    objectName: '', //물건명
    objectNameOmit: '', //경칭선택
    objectNameKana: '', //물건명 후리가나
    saleStoreId: '', //판매점ID
    saleStoreName: '', //판매점명
    zipNo: '', //우편번호
    prefId: '', //도도부현
    address: '', //주소
    powerSimArea: '', //발전량시뮬레이션지역
    windSpeed: '', //기준풍속
    snowCover: '', //수직적설량
    coldAreaChk: false, //한랭지대책시행
    surfaceType: '', //면조도구분(Ⅲ・Ⅳ / Ⅱ)
    saltAreaChk: false, //염해지역용아이템사용
    installHeight: '', //설치높이
    powerConTerms: '', //계약조건
    remark: '', //메모
    tempFlag: 'T', //임시저장(1) 저장(0)
  }
  const { register, setValue, getValues, handleSubmit, resetField, control, watch } = useForm({
    defaultValues: formInitValue,
  })

  const form = { register, setValue, getValues, handleSubmit, resetField, control, watch }

  const [receiveUser, setReceiveUser] = useState('') //담당자
  const [name2, setName2] = useState('') //물건명
  const [name3, setName3] = useState('') //물건명후리가나
  const [zipCode, setZipCode] = useState('') //우편번호
  const [name5, setName5] = useState('') //수직적설량
  const [gubun, setGubun] = useState('NEW') //신축 기축
  const [sel, setSel] = useState('') //경칭선택
  const [sel2, setSel2] = useState('') //발전량시뮬레이션지역
  const [sel3, setSel3] = useState('') //기준풍속
  const [sel4, setSel4] = useState('') //설치높이

  const [errors, setErrors] = useState({})
  const [isFormValid, setIsFormValid] = useState(false) //임시저장, 진짜저장 버튼 컨트롤
  const [testSelOption, setTestSelOption] = useState([]) // 테스트용
  const [autoSelectValue, setAutoSelectValue] = useState('') //판매점명 자동완성
  const [buttonValid, setButtonValid] = useState(false) //주소검색 활성화 컨트롤
  const [isSelected, setIsSelected] = useState(false) //한랭지대첵 체크박스
  const [isSelected2, setIsSelected2] = useState(false) //염해지역용아이템사용 체크박스
  const [gubun2, setGubun2] = useState('1') //면조도구분 라디오
  const [gubun3, setGubun3] = useState('A') //계약조건 라디오
  const [memo, setMemo] = useState('') //메모
  const objectNo = searchParams.get('objectNo') //url에서 물건번호 꺼내서 바로 set

  // const [address1, setAddress1] = useState('') //우편API리턴 도도부현명
  // const [address2, setAddress2] = useState('') //우편API리턴 시구정촌명
  // const [address3, setAddress3] = useState('') //우편API리턴 마을 지역명
  // const [prefCode, setPrefCode] = useState(1) //우편API prefcode

  const [editMode, setEditMode] = useState('NEW')
  const [detailData, setDetailData] = useState({})

  useEffect(() => {
    // console.log('상세화면진입:::::::::', searchParams.get('objectNo'))
    console.log('물건번호::::', objectNo)

    if (objectNo) {
      // console.log('상세::', objectNo)
      setEditMode('EDIT')
      if (objectNo.substring(0, 1) === 'R') {
        setIsFormValid(true)
      }
      //일단 플랜번호 무조건 1로
      //API 호출
      get({ url: `/api/object/v1.0/object/${objectNo}/1` }).then((res) => {
        if (res != null) {
          // console.log('res:::::::', res)
          setDetailData(res)
        }
      })
    }
  }, [objectNo])

  useEffect(() => {
    // validateForm()
  }, [receiveUser, name2, name3, gubun, sel, autoSelectValue, zipCode, sel2, sel3, name5, sel4])

  // 우편번호 숫자만 체크
  const _zipNo = watch('zipNo')
  useEffect(() => {
    console.log('실시간이니:::::', _zipNo)
    if (_zipNo !== '' && _zipNo.length === 7 && !_zipNo.match(/\D/g)) {
      console.log('벨리통과했군')
      setButtonValid(true)
    } else {
      setButtonValid(false)
    }
  }, [_zipNo])

  // 수직적설량 숫자만
  const textTypeHandler2 = (e) => {
    if (!e.target.value.match(/[^0-9]/g)) {
      setName5(e.target.value)
    }
  }
  const validateForm = () => {
    let errors = {}

    if (!receiveUser || receiveUser.trim().length === 0) {
      errors.receiveUser = '담당자 is required.'
    }

    if (!name2 || name2.trim().length === 0) {
      errors.name2 = '물건명 is required.'
    }

    if (!name3 || name3.trim().length === 0) {
      errors.name3 = '물건명후리가나 is required.'
    }

    if (!sel) {
      errors.sel = '경칭선택 is required'
    }

    if (!sel2) {
      errors.sel2 = '발전량시뮬레이션지역 is required'
    }

    if (!sel3) {
      errors.sel3 = '기준풍속 is required'
    }

    if (!sel4) {
      errors.sel4 = '설치높이 is required'
    }

    if (!autoSelectValue) {
      errors.autoSelectValue = '판매점ID자동완성 is required'
    }

    if (!zipCode || zipCode.length != 7) {
      errors.zipCode = '우편번호 is required.'
      setButtonValid(true)
    } else {
      setButtonValid(false)
    }

    if (!name5) {
      errors.name5 = '수직적설량 is required.'
    }

    console.log('errors::', errors)
    setErrors(errors)
    setIsFormValid(Object.keys(errors).length === 0)
  }

  // 우편번호 API
  const onSearchPostNumber = () => {
    const params = {
      zipcode: _zipNo,
    }
    get({ url: `https://zipcloud.ibsnet.co.jp/api/search?${queryStringFormatter(params)}` }).then((res) => {
      console.log('우편API RES::::::::', res)
      //7830060
      if (res.status === 200) {
        if (res.results?.length > 0) {
          // setAddress1(res.results[0].address1)
          // setAddress2(res.results[0].address2)
          // setAddress3(res.results[0].address3)
          // setPrefCode(res.results[0].prefcode)
          //       prefId: '', //도도부현
          // address: '', //주소
          form.setValue('prefId', res.results[0].prefcode)
          form.setValue('address', res.results[0].address2 + res.results[0].address3)
        } else {
          alert('등록된 우편번호에서 주소를 찾을 수 없습니다. 다시 입력해주세요.')
        }
      } else {
        alert(res.message)
      }
    })
  }

  const onTempSave = () => {
    console.log('임시저장::', isFormValid)
  }

  const onSave = () => {
    console.log('진짜저장isFormValid:::', isFormValid)
  }

  const moveList = () => {
    router.push('/management/stuff')
  }

  const changeAddress2 = (e) => {
    console.log('e:::::::', e.target.value)
  }

  //필수값 다 입력했을때
  const onValid = (data) => {
    console.log('data::::::', data)
    const formData = form.getValues()
    //console.log('formData::::', formData)
    const _dispCompanyName = watch('dispCompanyName')
    const _objectStatusId = watch('objectStatusId')
    const _objectNameOmit = watch('objectNameOmit')
    const _zipno = watch('zipno')
    console.log(_dispCompanyName)
    console.log(_objectStatusId)
    console.log(_objectNameOmit)
    console.log(_zipno)
  }

  //필수값 안넣었을때
  const onInvalid = (errors) => {
    console.log('실패', errors)
  }

  return (
    <>
      {(editMode === 'NEW' && (
        <form onSubmit={handleSubmit(onValid, onInvalid)}>
          <div>
            <div>(*필수 입력항목)</div>
            <div className="form-input">
              <label>담당자*</label>
              <input type="text" className="input-origin" {...form.register('dispCompanyName', { required: true })} />
            </div>
            <div className="form-input">
              <label>물건구분/물건명*</label>
              <input type="radio" name="objectStatusId" value="0" id="objectStatus0" {...form.register('objectStatusId')} />
              <label htmlFor="objectStatus0">신축</label>
              <input type="radio" name="objectStatusId" value="1" id="objectStatus1" {...form.register('objectStatusId')} />
              <label htmlFor="objectStatus0">기축</label>
              <input type="text" className="input-origin" {...form.register('objectName', { required: true })} />
              <div className="flex w-full max-w-xs flex-col gap-2">
                <select name="objectNameOmit" {...register('objectNameOmit', { required: true })}>
                  <option value="">경칭선택</option>
                  <option value="11">111</option>
                  <option value="22">222</option>
                  <option value="33">333</option>
                </select>
              </div>
            </div>
            <div className="form-input">
              <label>물건명 후리가나</label>
              <input type="text" className="input-origin" {...form.register('objectNameKana', { required: true })} />
            </div>
            <div className="form-input">
              <label>1차 판매점명 / ID</label>
            </div>
            <div className="form-input">
              <label>2차 판매점명 / ID</label>
            </div>
            <div className="form-input">
              <label>우편번호</label>
              <input
                type="text"
                className="input-origin"
                maxLength={7}
                {...form.register('zipNo', {
                  required: true,
                  minLength: { value: 7, message: '7자리만가능' },
                  pattern: { value: /^[0-9]*$/g, message: '숫자만 입력' },
                })}
              />
              <Button isDisabled={!buttonValid} onClick={onSearchPostNumber}>
                주소검색
              </Button>
              *우편번호 7자리를 입력한 후, 주소검색 버튼을 클릭해 주십시오
            </div>
            <div className="form-input">
              <label>도도부현 / 주소</label>

              <input type="text" className="input-origin" value={form.watch('address')} {...form.register('address')} />
            </div>
          </div>
          <button type="submit">저장!!!!!!!!!</button>
        </form>
      )) || <div>상세:::::::::::</div>}

      {/* <div className="flex w-full flex-wrap md:flex-nowrap gap-4">
        <div>
          <span>물건번호</span>
          <span>{objectNo}</span>
        </div>
        <div>
          <span>사양확정일</span>
          <span>{detailData?.specDate ? dayjs(detailData.specDate).format('YYYY.MM.DD') : null}</span>
        </div>
        <div>
          <span>갱신일시</span>
          <span>
            {detailData?.lastEditDatetime
              ? dayjs(detailData.lastEditDatetime).format('YYYY.MM.DD HH:mm:ss')
              : detailData?.createDatetime
                ? dayjs(detailData.createDatetime).format('YYYY.MM.DD HH:mm:ss')
                : null}
          </span>
        </div>
        <div>
          <span>등록일</span>
          <span></span>
        </div>
      </div> */}
      {/* <div>(*필수 입력항목)</div>
      
        <div>
          <input type="text" placeholder="물건명" value={name2} onChange={(e) => setName2(e.target.value)} />
        </div>
        <div className="flex w-full max-w-xs flex-col gap-2">
          <Select label="경칭선택" className="max-w-xs" onChange={(e) => setSel(e.target.value)}>
            <SelectItem key="1">111</SelectItem>
            <SelectItem key="2">222</SelectItem>
            <SelectItem key="3">333</SelectItem>
          </Select>
        </div>
        <div>
          <span>물건명 후리가나</span>
          <input type="text" placeholder="물건명 후리가나" value={name3} onChange={(e) => setName3(e.target.value)} />
        </div>
      </div> */}
      {/* <div>
        <span>판매점명 /ID *</span>
        <div className="flex w-full max-w-xs flex-col gap-2">
          <Autocomplete
            className="max-w-xs"
            defaultItems={testSelOption}
            label="판매점ID자동완성으로 바꾸기"
            selectedKey={autoSelectValue}
            onSelectionChange={setAutoSelectValue}
          >
            {(option) => <AutocompleteItem key={option.id}>{option.name}</AutocompleteItem>}
          </Autocomplete>
        </div>
      </div> */}
      {/* <div>
        <span>우편번호*</span>
        <input type="text" placeholder="숫자7자리 입력여부 체크" value={zipCode} maxLength="7" onChange={textTypeHandler} />
        <Button onClick={onSearchPostNumber} isDisabled={buttonValid}>
          주소검색
        </Button>
        *우편번호 7자리를 입력한 후, 주소검색 버튼을 클릭해 주십시오
      </div> */}
      {/* <div>
        <span>도도부현 / 주소*</span>
        <input type="text" placeholder="주소검색 결과 주소 셋팅 칸" value={address2 + address3} onChange={changeAddress2} />
      </div> */}
      {/* <div>
        <span>발전량시뮬레이션지역*</span>
        <Select label="발전량시뮬레이션지역" className="max-w-xs" onChange={(e) => setSel2(e.target.value)}>
          <SelectItem key="1">111</SelectItem>
          <SelectItem key="2">222</SelectItem>
          <SelectItem key="3">333</SelectItem>
        </Select>
      </div>
      <div>
        <span>기준풍속*</span>
        <Select label="기준풍속" className="max-w-xs" onChange={(e) => setSel3(e.target.value)}>
          <SelectItem key="1">111</SelectItem>
          <SelectItem key="2">222</SelectItem>
          <SelectItem key="3">333</SelectItem>
        </Select>
        m/s이하
      </div>
      <div>
        <span>수직적설량*</span>
        <input type="text" placeholder="수직적설량" value={name5} maxLength="3" onChange={textTypeHandler2} /> cm
        <Checkbox isSelected={isSelected} onValueChange={setIsSelected}>
          한랭지대책시행
        </Checkbox>
      </div> */}
      {/* <div>
        <span>면조도구분*</span>
        <input
          type="radio"
          name="radio_gubun2"
          id="radio_1"
          value={'1'}
          checked={gubun2 === '1' ? true : false}
          onChange={(e) => {
            setGubun2(e.target.value)
          }}
        />
        <label htmlFor="radio_1">III·IV</label>
        <input
          type="radio"
          name="radio_gubun2"
          id="radio_2"
          value={'2'}
          checked={gubun2 === '2' ? true : false}
          onChange={(e) => {
            setGubun2(e.target.value)
          }}
        />
        <label htmlFor="radio_2">II</label>
        <Checkbox isSelected={isSelected2} onValueChange={setIsSelected2}>
          염해지역용아이템사용
        </Checkbox>
      </div>
      <div>
        <span>설치높이*</span>
        <Select label="설치높이" className="max-w-xs" onChange={(e) => setSel4(e.target.value)}>
          <SelectItem key="1">111</SelectItem>
          <SelectItem key="2">222</SelectItem>
          <SelectItem key="3">333</SelectItem>
        </Select>
        m
      </div>
      <div>
        <span>계약조건</span>
        <input
          type="radio"
          name="radio_gubun3"
          id="radio_a"
          value={'A'}
          checked={gubun3 === 'A' ? true : false}
          onChange={(e) => {
            setGubun3(e.target.value)
          }}
        />
        <label htmlFor="radio_a">잉여</label>
        <input
          type="radio"
          name="radio_gubun3"
          id="radio_b"
          value={'B'}
          checked={gubun3 === 'B' ? true : false}
          onChange={(e) => {
            setGubun3(e.target.value)
          }}
        />
        <label htmlFor="radio_2">전량</label>
      </div>
      <div>
        <span>메모</span>
        <Textarea
          value={memo}
          onValueChange={setMemo}
          disableAutosize
          classNames={{
            base: 'max-w-xs',
            input: 'resize-y min-h-[40px]',
          }}
        />
      </div>
      {!isFormValid ? (
        <>
          <Button onClick={onTempSave}>임시저장</Button>
        </>
      ) : (
        <>
          <Button onClick={onSave}>진짜저장</Button>
        </>
      )}
      <Link href="/management/stuff">
        <button type="button">물건목록</button>
      </Link> */}
    </>
  )
}
