// React Imports
import { useEffect, useMemo, useState } from 'react'

// MUI Imports
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'

// Third-party Imports
import PerfectScrollbar from 'react-perfect-scrollbar'

// Type Imports

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { Autocomplete } from '@mui/material'
import { useDispatch, useSelector } from 'react-redux'
import { useDebounce } from 'use-debounce'
import { RootState } from '../../../../../redux-store'
import { useProductRecipesMutation } from '../../../../../services/mutations/productRecipes'
import { useIngredients } from '../../../../../services/queries/ingredients'
import { useOutlets } from '../../../../../services/queries/outlets'
import { Product } from '../../../../../types/services/product'
import { ProductRecipeRequest } from '../../../../../types/services/productRecipe'
import { resetProductVariant } from '../../../../../redux-store/slices/productRecipe'

type Props = {
  open: boolean
  handleClose: () => void
  product: Product
}

// Vars
const initialData = {
  outlet_id: '',
  product_id: '',
  variant_id: '',
  ingredient_id: '',
  quantity: 0
}

const AddRecipeDrawer = (props: Props) => {
  const dispatch = useDispatch()

  // Props
  const { open, handleClose, product } = props

  const { currentVariant, currentProductRecipe } = useSelector((state: RootState) => state.productRecipeReducer)

  const [outletInput, setOutletInput] = useState('')
  const [outletDebouncedInput] = useDebounce(outletInput, 500)
  const [ingredientInput, setIngredientInput] = useState('')
  const [ingredientDebouncedInput] = useDebounce(ingredientInput, 500)
  const [formData, setFormData] = useState<ProductRecipeRequest>(initialData)

  const { data: outlets, isLoading: outletsLoading } = useOutlets({
    search: outletDebouncedInput
  })
  const { data: ingredients, isLoading: ingredientsLoading } = useIngredients({
    search: ingredientDebouncedInput
  })

  const outletOptions = useMemo(() => outlets?.outlets || [], [outlets])
  const ingredientOptions = useMemo(() => ingredients?.data || [], [ingredients])

  const { createProductRecipe, updateProductRecipe } = useProductRecipesMutation()

  useEffect(() => {
    if (currentProductRecipe.id) {
      setFormData(currentProductRecipe)
    }
  }, [currentProductRecipe])

  const handleSubmit = (e: any) => {
    e.preventDefault()

    if (currentProductRecipe.id) {
      updateProductRecipe.mutate(
        { id: currentProductRecipe.id, payload: formData },
        {
          onSuccess: () => {
            handleReset()
          }
        }
      )
    } else {
      createProductRecipe.mutate(
        { ...formData, product_id: product.id, variant_id: currentVariant.id || '' },
        {
          onSuccess: () => {
            handleReset()
          }
        }
      )
    }
  }

  const handleReset = () => {
    handleClose()
    dispatch(resetProductVariant())
    setFormData(initialData)
  }

  const handleInputChange = (e: any) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    })
  }

  const setTitleDrawer = (recipe: any) => {
    const addOrEdit = currentProductRecipe.id ? 'Edit ' : 'Add '

    let title = 'Original'

    if (recipe?.name) {
      title = recipe?.name
    }

    return addOrEdit + title
  }

  return (
    <Drawer
      open={open}
      anchor='right'
      variant='temporary'
      onClose={handleReset}
      ModalProps={{ keepMounted: true }}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 400 } } }}
    >
      <div className='flex items-center justify-between pli-6 plb-5'>
        <Typography variant='h5'>{setTitleDrawer(currentVariant)} Variant Ingredient</Typography>
        <IconButton size='small' onClick={handleReset}>
          <i className='tabler-x text-2xl' />
        </IconButton>
      </div>
      <Divider />
      <PerfectScrollbar options={{ wheelPropagation: false, suppressScrollX: true }}>
        <div className='p-6'>
          <form onSubmit={handleSubmit} className='flex flex-col gap-5'>
            <Typography color='text.primary' className='font-medium'>
              Basic Information
            </Typography>
            <Autocomplete
              options={outletOptions}
              loading={outletsLoading}
              getOptionLabel={option => option.name}
              value={outletOptions.find(p => p.id === formData.outlet_id) || null}
              onInputChange={(event, newOutlettInput) => {
                setOutletInput(newOutlettInput)
              }}
              onChange={(event, newValue) => {
                setFormData({
                  ...formData,
                  outlet_id: newValue?.id || ''
                })
              }}
              renderInput={params => (
                <CustomTextField
                  {...params}
                  className=''
                  label='Outlet'
                  fullWidth
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: <>{params.InputProps.endAdornment}</>
                  }}
                />
              )}
            />
            <Autocomplete
              options={ingredientOptions || []}
              loading={ingredientsLoading}
              getOptionLabel={option => option.name}
              value={ingredientOptions?.find(p => p.id === formData.ingredient_id) || null}
              onInputChange={(event, newIngredientInput) => {
                setIngredientInput(newIngredientInput)
              }}
              onChange={(event, newValue) => {
                setFormData({
                  ...formData,
                  ingredient_id: newValue?.id || ''
                })
              }}
              renderInput={params => (
                <CustomTextField
                  {...params}
                  className=''
                  label='Ingredient'
                  fullWidth
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: <>{params.InputProps.endAdornment}</>
                  }}
                />
              )}
            />
            <CustomTextField
              type='number'
              label='Quantity'
              fullWidth
              value={formData.quantity}
              onChange={e => setFormData({ ...formData, quantity: Number(e.target.value) })}
            />
            <div className='flex items-center gap-4'>
              <Button
                variant='contained'
                type='submit'
                disabled={createProductRecipe.isPending || updateProductRecipe.isPending}
              >
                {currentProductRecipe.id
                  ? updateProductRecipe.isPending
                    ? 'Updating...'
                    : 'Update'
                  : createProductRecipe.isPending
                    ? 'Creating...'
                    : 'Create'}
              </Button>
              <Button variant='tonal' color='error' type='reset' onClick={handleReset}>
                Discard
              </Button>
            </div>
          </form>
        </div>
      </PerfectScrollbar>
    </Drawer>
  )
}

export default AddRecipeDrawer
