import { type FC, useState } from 'react'
import DefaulModal from '@/components/DefaulModal'
import Input from '@/components/Input'
import DatePicker from '@/components/DatePicker'
import Button from '@/components/Button'
import { useAddTrackCode } from '@/pages/orders/hooks/useOrderData'
import type { AddTrackCodeType } from '@/pages/orders/types/ReturnTypes'

type Props = {
  open: boolean
  onClose: () => void
  orderId: string | null
  onSuccess?: () => void
}

const AddTrackCodeModal: FC<Props> = ({ open, onClose, orderId, onSuccess }) => {
  const [trackCode, setTrackCode] = useState('')
  const [postingDate, setPostingDate] = useState('')
  const [postingReceipt, setPostingReceipt] = useState('')

  const { mutateAsync, isPending } = useAddTrackCode()

  const handleSubmit = async () => {
    if (!orderId) return
    if (!trackCode || !postingDate) return

    const payload: AddTrackCodeType = {
      orderId,
      trackCode,
      postingDate,
      postingReceipt,
    }

    await mutateAsync(payload)
    setTrackCode('')
    setPostingDate('')
    setPostingReceipt('')
    onClose()
    if (onSuccess) {
      onSuccess()
    }
  }

  return (
    <DefaulModal open={open} close={onClose} isHeader title_header='افزودن کد رهگیری' width={520}>
      <div className='space-y-4 mt-4 w-[400px]'>

        <DatePicker
          label='تاریخ ارسال'
          placeholder='انتخاب تاریخ'
          defaulValue={postingDate}
          onChange={(val) => setPostingDate(val)}
        />

        <Input
          label='کد رهگیری'
          placeholder='مثال: 1234567890'
          value={trackCode}
          onChange={(e) => setTrackCode(e.target.value)}
        />



        <Input
          label='شماره رسید پست (اختیاری)'
          placeholder='مثال: 98-001-ABC'
          value={postingReceipt}
          onChange={(e) => setPostingReceipt(e.target.value)}
        />

        <div className='flex items-center gap-3 pt-2'>
          <Button variant='outline' onClick={onClose} disabled={isPending}>
            انصراف
          </Button>
          <Button onClick={handleSubmit} disabled={!trackCode || !postingDate || isPending}>
            ثبت
          </Button>
        </div>
      </div>
    </DefaulModal>
  )
}

export default AddTrackCodeModal


