'use client'

// MUI Imports
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import { useProductsMutation } from '../../../../../services/mutations/products'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '../../../../../redux-store'
import { CircularProgress } from '@mui/material'
import { resetProduct } from '../../../../../redux-store/slices/product'
import { useParams } from 'next/navigation'

const ProductAddHeader = () => {
  const dispatch = useDispatch()
  const params = useParams()

  const { mutate: createProduct, isPending: isCreating } = useProductsMutation().createProduct
  const { mutate: updateProduct, isPending: isUpdating } = useProductsMutation().updateProduct

  const { productRequest } = useSelector((state: RootState) => state.productReducer)

  const isEdit = !!params?.id

  const handleSubmit = () => {
    const { cost, price, ...rest } = productRequest
    const newProductRequest = { ...rest, cost: Number(cost), price: Number(price) }

    if (isEdit) {
      updateProduct(
        { id: params?.id as string, payload: newProductRequest },
        {
          onSuccess: () => {
            dispatch(resetProduct())
          }
        }
      )
    } else {
      createProduct(newProductRequest, {
        onSuccess: () => {
          dispatch(resetProduct())
        }
      })
    }
  }

  return (
    <div className='flex flex-wrap sm:items-center justify-between max-sm:flex-col gap-6'>
      <div>
        <Typography variant='h4' className='mbe-1'>
          {isEdit ? 'Edit Product' : 'Add a new product'}
        </Typography>
        <Typography>Orders placed across your store</Typography>
      </div>
      <div className='flex flex-wrap max-sm:flex-col gap-4'>
        <Button variant='tonal' color='secondary'>
          Discard
        </Button>
        {/* <Button variant='tonal'>Save Draft</Button> */}
        <Button variant='contained' disabled={isEdit ? isUpdating : isCreating} onClick={handleSubmit}>
          {isEdit ? 'Update Product' : 'Publish Product'}
          {(isCreating || isUpdating) && <CircularProgress color='inherit' size={16} className='ml-2' />}
        </Button>
      </div>
    </div>
  )
}

export default ProductAddHeader
