'use client'

import React, { useState, useEffect } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { useRouter, useSearchParams } from 'next/navigation'
import { globalLocaleStore } from '@/store/localeAtom'
import { useRecoilValue } from 'recoil'
import { useMessage } from '@/hooks/useMessage'
import dayjs from 'dayjs'

export default function StuffHeader() {
  const { getMessage } = useMessage()
  const router = useRouter()
  const searchParams = useSearchParams()
  const objectNo = searchParams.get('objectNo') //url에서 물건번호 꺼내서 바로 set
  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const { get } = useAxios(globalLocaleState)
  const [headerData, setHeaderData] = useState({})

  useEffect(() => {
    get({ url: `/api/object/${objectNo}/detail` }).then((res) => {
      if (res != null && res != '') {
        setHeaderData(res)
      } else {
        alert(getMessage('stuff.detail.header.notExistObjectNo'))
        router.push('/management/stuff')
      }
    })
  }, [objectNo])

  //물건번호 복사
  const copyObjectNo = async (objectNo) => {
    await navigator.clipboard.writeText(objectNo)
    alert(getMessage('stuff.detail.header.message2'))
    try {
    } catch (error) {
      alert(getMessage('stuff.detail.header.message3'))
    }
  }

  return (
    <div className="infomation-box-wrap">
      <div className="sub-table-box">
        <div className="info-title">{getMessage('stuff.detail.header.objectNo')}</div>
        <div className="info-inner">
          {headerData.objectNo}{' '}
          <button
            className="copy-ico"
            onClick={() => {
              copyObjectNo(headerData.objectNo)
            }}
          ></button>
        </div>
      </div>
      <div className="sub-table-box">
        <div className="info-title">{getMessage('stuff.detail.header.specificationConfirmDate')}</div>
        <div className="info-inner">{headerData.specificationConfirmDate}</div>
      </div>
      <div className="sub-table-box">
        <div className="info-title">{getMessage('stuff.detail.header.lastEditDatetime')}</div>
        <div className="info-inner">
          {headerData?.lastEditDatetime ? `${dayjs(headerData.lastEditDatetime).format('YYYY.MM.DD HH:mm:ss')}` : ''}{' '}
          {headerData?.lastEditUserName ? `(${headerData.lastEditUserName})` : null}
        </div>
      </div>
      <div className="sub-table-box">
        <div className="info-title">{getMessage('stuff.detail.header.createDatetime')}</div>
        <div className="info-inner">
          {headerData?.createDatetime ? `${dayjs(headerData.lastEditDatetime).format('YYYY.MM.DD')}` : ''}{' '}
          {headerData?.createUserName ? `(${headerData.createUserName})` : null}
        </div>
      </div>
    </div>
  )
}
