'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 { del, get, post } from '@/lib/Axios'
import { queryStringFormatter, isEmptyArray } from '@/util/common-utils'
import dayjs from 'dayjs'
import { useMessage } from '@/hooks/useMessage'
import { useForm } from 'react-hook-form'
export default function StuffDetail() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { getMessage } = useMessage()

  //form
  const formInitValue = {
    // 물건번호 T...(임시) R...(진짜)
    dispCompanyName: '', //담당자
    objectStatusId: '0', //물건구분(신축:0 기축 : 1)
    objectName: '', //물건명
    objectNameOmit: '', //경칭선택
    objectNameKana: '', //물건명 후리가나
    saleStoreId: '', //판매점ID
    saleStoreName: '', //판매점명
    otherSaleStoreId: '',
    otherSaleStoreName: '',
    zipNo: '', //우편번호
    prefId: '', //도도부현
    prefName: '',
    address: '', //주소
    powerSimArea: '', //발전량시뮬레이션지역
    windSpeed: '', //기준풍속
    snowCover: '', //수직적설량
    coldAreaChk: false, //한랭지대책시행
    surfaceType: 'Ⅲ・Ⅳ', //면조도구분(Ⅲ・Ⅳ / Ⅱ)
    saltAreaChk: false, //염해지역용아이템사용
    installHeight: '', //설치높이
    powerConTerms: '0', //계약조건(잉여 / 전량)
    remarks: '', //메모
    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 [prefCodeList, setPrefCodeList] = useState([]) //도도부현 코트 리스트
  const [prefValue, setPrefValue] = useState('')
  const [saleStoreList, setSaleStoreList] = useState([]) // 판매점 리스트
  const [otherSaleStoreList, setOtherSaleStoreList] = useState([])

  const [powerSimAreaList, setPowerSimAreaList] = useState([]) //발전시뮬레이션 리스트

  const [isFormValid, setIsFormValid] = useState(false) //임시저장, 진짜저장 버튼 컨트롤
  const [buttonValid, setButtonValid] = useState(false) //주소검색 활성화 컨트롤
  const objectNo = searchParams.get('objectNo') //url에서 물건번호 꺼내서 바로 set

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

  useEffect(() => {
    if (objectNo) {
      console.log('수정화면')
      setEditMode('EDIT')

      if (objectNo.substring(0, 1) === 'R') {
        //진짜
        setIsFormValid(true)
      }
      get({ url: `/api/object/${objectNo}/detail` }).then((res) => {
        // console.log('물건번호로 상세 API 호출')
        if (res != null) {
          // console.log('상세res:::::::', res)
          setDetailData(res)

          // 신규 상세 공통APi
          // 도도부현API
          get({ url: '/api/object/prefecture/list' }).then((res) => {
            if (!isEmptyArray(res)) {
              //console.log('도도부현API 결과:::', res)
              setPrefCodeList(res)
            }
          })
          // 판매점목록 API /api/object/saleStore/판매점코드/list - 판매점 목록 조회
          // 임시 1차점 판매점코드 saleStoreId=201TES01
          // T01
          //1차점 : X167
          get({ url: `/api/object/saleStore/X167/list` }).then((res) => {
            if (!isEmptyArray(res)) {
              console.log('판매점 결과:::::', res)
              setSaleStoreList(res)
              //1차 판매점 자동완성 값 셋팅
              form.setValue('saleStoreId', res[0].saleStoreId)
              //1차 판매점 번호 셋팅
              form.setValue('saleStoreName', res[0].saleStoreId)
              setOtherSaleStoreList([])
            }
          })
        } else {
          alert('삭제된 물건입니다')
          router.push('/management/stuff')
        }
      })
    } else {
      console.log('신규화면')
      // 신규 상세 공통APi
      // 도도부현API
      get({ url: '/api/object/prefecture/list' }).then((res) => {
        if (!isEmptyArray(res)) {
          //console.log('도도부현API 결과:::', res)
          setPrefCodeList(res)
        }
      })
      // 판매점목록 API /api/object/saleStore/판매점코드/list - 판매점 목록 조회
      // 임시 1차점 판매점코드 saleStoreId=201TES01
      // T01
      //1차점 : X167
      get({ url: `/api/object/saleStore/X167/list` }).then((res) => {
        if (!isEmptyArray(res)) {
          console.log('판매점 결과:::::', res)
          const firstList = res.filter((row) => row.saleStoreLevel === '1')
          const otherList = res.filter((row) => row.saleStoreLevel !== '1')
          console.log('first:::::', firstList)
          console.log('otherList:::::', otherList)
          //1차점 셀렉트박스
          setSaleStoreList(firstList)
          //1차 판매점 자동완성 값 셋팅
          form.setValue('saleStoreId', firstList[0].saleStoreId)
          //1차 판매점 번호 셋팅
          form.setValue('saleStoreName', firstList[0].saleStoreId)

          //1차점 아닌 판매점 셀렉트박스
          setOtherSaleStoreList(otherList)
        }
      })
    }
  }, [objectNo])

  //1차점 변경 이벤트
  const onSelectionChange = (key) => {
    if (key == null) {
      form.setValue('saleStoreId', '')
      form.setValue('saleStoreName', '')
    } else {
      form.setValue('saleStoreId', key)
      form.setValue('saleStoreName', key)
    }
  }

  //2차점 변경 이벤트
  const onSelectionChange2 = (key) => {
    console.log(key)
  }
  // 우편번호 숫자만 체크
  const _zipNo = watch('zipNo')
  useEffect(() => {
    if (_zipNo !== '' && _zipNo.length === 7 && !_zipNo.match(/\D/g)) {
      setButtonValid(true)
    } else {
      setButtonValid(false)
    }
  }, [_zipNo])

  //임시저장 저장 버튼 컨트롤
  // dispCompanyName: '', //담당자
  // objectName: '', //물건명
  // objectNameOmit: '', //경칭선택
  // saleStoreId: '', //판매점ID
  // zipNo: '', //우편번호
  // prefId: '', //도도부현
  // address: '', //주소
  // powerSimArea: '', //발전량시뮬레이션지역
  // windSpeed: '', //기준풍속
  // snowCover: '', //수직적설량
  // coldAreaChk: false, //한랭지대책시행
  // surfaceType: 'Ⅲ・Ⅳ', //면조도구분(Ⅲ・Ⅳ / Ⅱ)
  // saltAreaChk: false, //염해지역용아이템사용
  // installHeight: '', //설치높이
  // powerConTerms: '0', //계약조건(잉여 / 전량)
  // remarks: '', //메모
  // tempFlag: 'T', //임시저장(1) 저장(0)
  const _dispCompanyName = watch('dispCompanyName')
  const _objectName = watch('objectName')
  const _objectNameOmit = watch('objectNameOmit')
  const _saleStoreId = watch('saleStoreId')
  const _prefId = watch('prefId')
  const _address = watch('address')
  const _powerSimArea = watch('powerSimArea')
  const _windSpeed = watch('windSpeed')
  const _snowCover = watch('snowCover')
  const _installHeight = watch('installHeight')
  useEffect(() => {
    // console.log('mode:::::', editMode)
    if (editMode === 'NEW') {
      const formData = form.getValues()
      // console.log('폼::::::::::::', formData)
      let errors = {}
      if (!_dispCompanyName || _dispCompanyName.trim().length === 0) {
        errors.dispCompanyName = true
      }
      if (!_objectName || _objectName.trim().length === 0) {
        errors.objectName = true
      }
      if (!_objectNameOmit) {
        errors.objectNameOmit = true
      }
      if (!_saleStoreId) {
        errors.saleStoreId = true
      }

      if (!_zipNo || _zipNo.length != 7) {
        errors.zipCode = true
      }

      if (!_prefId) {
        errors.prefId = true
      }

      if (!_address.trim().length === 0) {
        errors.address = true
      }

      if (!_powerSimArea) {
        errors.powerSimArea = true
      }

      if (!_windSpeed) {
        errors.windSpeed = true
      }

      if (!_snowCover) {
        errors.snowCover = true
      }

      if (!_installHeight) {
        errors.installHeight = true
      }

      // console.log('errors::', errors)
      setIsFormValid(Object.keys(errors).length === 0)
    } else {
      // console.log('상세일때 폼체크')
    }
  }, [_dispCompanyName, _objectName, _objectNameOmit, _saleStoreId, _zipNo, _prefId, _address, _powerSimArea, _windSpeed, _snowCover, _installHeight])

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

  useEffect(() => {
    if (prefValue !== '') {
      // console.log('우편번호 검색해서  도도부현골랐을때::::', prefValue)
      // 발전량시뮬레이션 지역 목록
      // /api/object/prefecture/도도부현코드/list
      get({ url: `/api/object/prefecture/${prefValue}/list` }).then((res) => {
        if (!isEmptyArray(res)) {
          // console.log('발전시뮬레이션::::::::', res)
          setPowerSimAreaList(res)
        }
      })
    }
  }, [prefValue])

  //필수값 다 입력했을때
  const onValid = (data) => {
    // 수정모드일때는 PUT
    // console.log('필수값 다 있고 저장')
    // 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')
    // const _prefId = watch('prefId')
    // const _address = watch('address')
    // const _coldAreaChk = watch('coldAreaChk')
    // console.log(_dispCompanyName)
    // console.log(_objectStatusId)
    // console.log(_objectNameOmit)
    // console.log(_zipNo)
    // console.log(_prefId)
    // console.log('prefValue::', prefValue)
    // console.log(_address)
    // console.log('_coldAreaChk::', _coldAreaChk)
  }

  //필수값 안넣었을때 임시저장 form required사용시
  // const onInvalid = (errors) => {
  //   console.log('22222222222222222222222')
  //   const formData = form.getValues()
  //   console.log('임시저장formData::::', formData)
  // }

  // 임시저장
  const onTempSave = async () => {
    const formData = form.getValues()
    //console.log('임시저장::::::::', formData)

    const params = {
      saleStoreId: formData.saleStoreId,
      saleStoreName: formData.saleStoreName,
      objectStatusId: formData.objectStatusId,
      objectName: formData.objectName,
      objectNameOmit: formData.objectNameOmit,
      objectNameKana: formData.objectNameKana,
      zipNo: formData.zipNo,
      prefId: formData.prefId,
      prefName: formData.prefName,
      address: formData.address,
      powerSimArea: formData.powerSimArea,
      receiveUser: formData.dispCompanyName,
      installHeight: formData.installHeight,
      windSpeed: formData.windSpeed,
      snowCover: formData.snowCover,
      surfaceType: formData.surfaceType,
      powerConTerms: formData.powerConTerms,
      saltAreaChk: formData.saltAreaChk,
      coldAreaChk: formData.coldAreaChk,
      tempFlg: '1',
      workNo: null,
      workName: null,
    }
    console.log('임시저장params::', params)
    return
    await post({ url: '/api/object/save-object', data: params }).then((res) => {
      console.log('res::::::', res)
    })
  }

  // 발전량 시뮬레이션 변경
  const handlePowerSimAreaOnChange = (e) => {
    // console.log('가지고있는 도도부현코드:::::::::', prefValue)
    // console.log('발전량시뮬레이션변경:::::::::', e.target.value)
    //값 set해주고 그거 useEffect로 api호출
  }

  // 물건삭제
  const onDelete = () => {
    //http://localhost:8080/api/object/R201TES01240910023
    // console.log('물건번호::::::::', objectNo)
    alert('사양확정일이 있으면 삭제 불가')
    if (confirm(getMessage('common.message.data.delete'))) {
      let testobj = '10'

      del({ url: `/api/object/${testobj}` }).then((res) => {
        // console.log('삭제 결과:::', res)
        router.push('/management/stuff')
      })
    }
  }

  return (
    <>
      {(editMode === 'NEW' && (
        <form onSubmit={handleSubmit(onValid)}>
          <div>
            <div>(*필수 입력항목)</div>
            <div className="form-input">
              <label>담당자*</label>
              <input type="text" className="input-origin" {...form.register('dispCompanyName')} />
            </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')} />
              <div className="flex w-full max-w-xs flex-col gap-2">
                <select name="objectNameOmit" {...register('objectNameOmit')}>
                  <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')} />
            </div>
            <div className="form-input">
              <label>1차 판매점명 / ID</label>
              <div className="flex w-full max-w-xs flex-col gap2">
                {saleStoreList?.length > 0 && (
                  <Autocomplete
                    className="max-w-xs"
                    defaultItems={saleStoreList}
                    label="판매점ID자동완성"
                    selectedKey={form.watch('saleStoreId')}
                    {...form.register('saleStoreId')}
                    onSelectionChange={onSelectionChange}
                  >
                    {(option) => <AutocompleteItem key={option.saleStoreId}>{option.saleStoreName}</AutocompleteItem>}
                  </Autocomplete>
                )}
                <input type="text" className="input-origin" value={form.watch('saleStoreName')} {...form.register('saleStoreName')} disabled />
              </div>
            </div>
            <div className="form-input">
              <label>2차 판매점명 / ID</label>
              <div className="flex w-full max-w-xs flex-col gap2">
                {otherSaleStoreList?.length > 0 && (
                  <Autocomplete
                    className="max-w-xs"
                    defaultItems={otherSaleStoreList}
                    label="2차판매점ID자동완성"
                    {...form.register('otherSaleStoreId')}
                    onSelectionChange={onSelectionChange2}
                  >
                    {(option) => <AutocompleteItem key={option.saleStoreId}>{option.saleStoreName}</AutocompleteItem>}
                  </Autocomplete>
                )}
              </div>
            </div>
            <div className="form-input">
              <label>우편번호</label>
              <input
                type="text"
                className="input-origin"
                maxLength={7}
                {...form.register('zipNo', {
                  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>
              <div className="flex w-full flex-wrap items-end md:flex-nowrap mb-6 md:mb-0 gap-4">
                {prefCodeList?.length > 0 && (
                  <Select className="max-w-xs" selectedKeys={prefValue} isDisabled {...form.register('prefId')}>
                    {prefCodeList.map((row) => {
                      return <SelectItem key={row.prefId}>{row.prefName}</SelectItem>
                    })}
                  </Select>
                )}
              </div>

              <input type="text" className="input-origin" value={form.watch('address')} {...form.register('address')} />
            </div>
            <div className="form-input">
              <label>발전량시뮬레이션지역</label>
              {powerSimAreaList?.length > 0 && (
                <Select
                  className="max-w-xs"
                  selectedKeys={form.watch('powerSimArea')}
                  {...form.register('powerSimArea')}
                  onChange={handlePowerSimAreaOnChange}
                >
                  {powerSimAreaList.map((row) => {
                    // console.log('row::', row)
                    return (
                      <SelectItem key={row.prefName} value={row.prefId}>
                        {row.prefName}
                      </SelectItem>
                    )
                  })}
                </Select>
              )}
            </div>
            <div className="form-input">
              <label>기준풍속</label>
              <div className="flex w-full max-w-xs flex-col gap-2">
                <select name="windSpeed" {...register('windSpeed')}>
                  <option value="">기준풍속</option>
                  <option value="30">30</option>
                  <option value="50">50</option>
                  <option value="60">60</option>
                </select>
              </div>
            </div>
            <div className="form-input">
              <label>수직적설량</label>
              <input
                type="text"
                className="input-origin"
                maxLength={3}
                {...form.register('snowCover', {
                  pattern: { value: /^[0-9]*$/g, message: '정수만 입력' },
                })}
              />{' '}
              cm
              <Checkbox
                onValueChange={(e) => {
                  form.setValue('coldAreaChk', e)
                }}
                {...form.register('coldAreaChk')}
              >
                한랭지대책시행
              </Checkbox>
            </div>
            <div className="form-input">
              <label>면조도구분</label>
              <input type="radio" name="surfaceType" value="Ⅲ・Ⅳ" id="surfaceType0" {...form.register('surfaceType')} />
              <label htmlFor="surfaceType0">Ⅲ・Ⅳ</label>
              <input type="radio" name="surfaceType" value="Ⅱ" id="surfaceType1" {...form.register('surfaceType')} />
              <label htmlFor="surfaceType1">Ⅱ</label>
              <Checkbox
                {...form.register('saltAreaChk')}
                onValueChange={(e) => {
                  form.setValue('saltAreaChk', e)
                }}
              >
                염해지역용아이템사용
              </Checkbox>
            </div>
            <div className="form-input">
              <label>설치높이</label>
              <div className="flex w-full max-w-xs flex-col gap-2">
                <select name="installHeight" {...register('installHeight')}>
                  <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="radio" name="powerConTerms" value="0" id="powerConTerms0" {...form.register('powerConTerms')} />
              <label htmlFor="powerConTerms0">잉여</label>
              <input type="radio" name="powerConTerms" value="1" id="powerConTerms1" {...form.register('powerConTerms')} />
              <label htmlFor="powerConTerms1">전량</label>
            </div>
            <div className="form-input">
              <label>메모</label>
              <Textarea
                disableAutosize
                classNames={{
                  base: 'max-w-xs',
                  input: 'resize-y min-h-[40px]',
                }}
                {...form.register('remarks')}
                onValueChange={(e) => {
                  // console.log('e::::', e)
                  form.setValue('remarks', e)
                }}
              />
            </div>
          </div>
          {!isFormValid ? (
            <>
              <Button type="submit" onClick={onTempSave}>
                NEW화면임시저장
              </Button>
            </>
          ) : (
            <button type="submit">NEW화면 저장</button>
          )}
          <Link href="/management/stuff">
            <button type="button">NEW화면 물건목록이동</button>
          </Link>
        </form>
      )) || (
        <>
          {objectNo.substring(0, 1) === 'R' ? (
            <>
              <Link href="/management/stuff">
                <button type="button">R상세:물건목록</button>
              </Link>
              <button type="submit">R상세:저장</button>
              <button type="submit" onClick={onDelete}>
                R상세:물건삭제
              </button>
            </>
          ) : (
            <>
              <Link href="/management/stuff">
                <button type="button">T상세:물건목록</button>
              </Link>
              <button type="submit">T상세:저장</button>
            </>
          )}
        </>
      )}
    </>
  )
}
