Skip to content

Instantly share code, notes, and snippets.

@haris-aqeel
Last active October 30, 2023 06:07
Show Gist options
  • Save haris-aqeel/451c2db88a98350f183cb8c394bc0982 to your computer and use it in GitHub Desktop.
Save haris-aqeel/451c2db88a98350f183cb8c394bc0982 to your computer and use it in GitHub Desktop.
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import * as Yup from 'yup';
import LoadingButton from '@mui/lab/LoadingButton';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Grid from '@mui/material/Unstable_Grid2';
// eslint-disable-next-line import/no-extraneous-dependencies
import { Typography } from '@mui/material';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { uploadFoodImage, useGetRestaurantFood, useGetRestaurantMeals } from 'src/api/restaurant';
import FormProvider, {
RHFMultiSelect,
RHFSwitch,
RHFTextField,
RHFUploadAvatar,
} from 'src/components/hook-form';
import { useSnackbar } from 'src/components/snackbar';
import { fData } from 'src/utils/format-number';
// ----------------------------------------------------------------------
export default function RestaurantEditFood({ id }: { id: string | undefined }) {
const { enqueueSnackbar } = useSnackbar();
const [imageFile, setImageFile] = useState<File | undefined>(undefined);
const { restaurantFood } = useGetRestaurantFood(id);
const restaurant_id = localStorage.getItem('restaurant_id');
const { restaurantMeals } = useGetRestaurantMeals(restaurant_id || undefined);
const UpdateRestaurantFoodSchema = Yup.object().shape({
title: Yup.string().required('Title is required'),
title_arabic: Yup.string().required('Arabic title is required'),
starches: Yup.number().required('Starches value is required'),
repeated_days: Yup.array().required('Repeated days are required'),
protein: Yup.number().required('Protein value is required'),
photo: Yup.string().url('Must be a valid URL').required('Photo is required'),
photoURL: Yup.mixed().optional(),
meat: Yup.number().required('Meat value is required'),
meals: Yup.array(),
fat: Yup.number().required('Fat value is required'),
description: Yup.string().required('Description is required'),
description_arabic: Yup.string().required('Arabic description is required'),
carb: Yup.number().required('Carb value is required'),
calories: Yup.number().required('Calories value is required'),
available_days: Yup.array(),
availability: Yup.boolean().required('Availability status is required'),
// meals_dropdown: Yup.array().optional()
});
// interface ServerDayProps extends PickersDayProps<string> {
// highlightedDays?: string[]
// onDateClick?: (updatedHighlightedDays: string[]) => void
// handleDay?: (day: string) => void
// }
const defaultValues = useMemo(() => ({
title: restaurantFood?.title || '',
title_arabic: restaurantFood?.title_arabic || '',
availability: restaurantFood?.availability || false,
calories: restaurantFood?.calories || 0,
protein: restaurantFood?.protein || 0,
carb: restaurantFood?.carb || 0,
fat: restaurantFood?.fat || 0,
description: restaurantFood?.description || '',
description_arabic: restaurantFood?.description_arabic || '',
meat: restaurantFood?.meat || 0,
starches: restaurantFood?.starches || 0,
repeated_days: restaurantFood?.repeated_days || [],
available_days: restaurantFood?.available_days || [],
meals: restaurantFood?.meals || [],
photo: restaurantFood?.photo || '',
photoURL: "",
// meals_dropdown: restaurantFood?.meals?.map(m => m?.id.toString()) || [],
}), [restaurantFood]);
const methods = useForm({
resolver: yupResolver(UpdateRestaurantFoodSchema),
defaultValues,
});
const {
setValue,
handleSubmit,
formState: { isSubmitting, errors },
reset,
} = methods;
console.log(errors)
// useEffect(() => {
// if (restaurantFood) {
// reset(restaurantFood);
// setValue("meals_dropdown", restaurantFood?.meals?.map(m => m?.id.toString()) || []);
// }
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [restaurantFood]);
const onSubmit = handleSubmit(async (data) => {
try {
const upload_data = {
"meals": data.meals,
"title": data.title,
"title_arabic": data.title_arabic,
"availability": data.availability,
"calories": data.calories,
"protein": data.protein,
"carb": data.carb,
"fat": data.fat,
"description": data.description,
"description_arabic": data.description_arabic,
"meat": data.meat,
"starches": data.starches,
"repeated_days": data.repeated_days,
"available_days": data.available_days
}
console.log(upload_data)
const ID = 3;
if (ID && (imageFile)) {
await uploadFoodImage(ID.toString(), imageFile);
}
enqueueSnackbar('Update success!');
} catch (error) {
console.error(error);
}
});
const handleDrop = useCallback(
(acceptedFiles: File[]) => {
const file = acceptedFiles[0];
const newFile = Object.assign(file, {
preview: URL.createObjectURL(file),
});
if (file) {
setValue('photoURL', newFile, { shouldValidate: true });
setImageFile(newFile);
}
},
[setValue]
);
return (
<FormProvider methods={methods} onSubmit={onSubmit}>
<Grid container spacing={3}>
<Grid xs={12} md={12}>
<Card sx={{ pt: 5, pb: 5, px: 3, textAlign: 'center' }}>
<RHFSwitch
name="availability"
labelPlacement="start"
label="Availablility"
sx={{ mt: 5 }}
/>
</Card>
</Grid>
<Grid xs={12} md={12}>
<Card sx={{ p: 3 }}>
<Typography variant="h5" sx={{ my: 3 }}>Details</Typography>
<Box
rowGap={3}
columnGap={2}
display="grid"
gridTemplateColumns={{
xs: 'repeat(1, 1fr)',
sm: 'repeat(2, 1fr)',
}}
>
<RHFTextField name="title" label="Title" />
<RHFTextField name="title_arabic" label="Title Ar" />
<RHFTextField name="description" label="Description" />
<RHFTextField name="description_arabic" label="description Ar" />
</Box>
<Typography variant="h5" sx={{ my: 3 }}>Meals</Typography>
<Box rowGap={3} columnGap={2} display="grid" gridTemplateColumns={{ xs: 'repeat(1, 1fr)', sm: 'repeat(1, 1fr)' }}>
// <RHFMultiSelect
// name="meals_dropdown"
// chip
// checkbox
// options={restaurantMeals?.map((m) => ({
// label: m.title,
// value: m?.id.toString()
// }))}
// />
</Box>
<Typography variant="h5" sx={{ my: 3 }}>Marcos</Typography>
<Box rowGap={3} columnGap={2} display="grid" gridTemplateColumns={{ xs: 'repeat(2, 1fr)', sm: 'repeat(4, 1fr)' }}>
<RHFTextField name="calories" label="Calories" />
<RHFTextField name="protein" label="Protein" />
<RHFTextField name="fat" label="Fat" />
<RHFTextField name="carb" label="Carbs" />
</Box>
<Typography variant="h5" sx={{ my: 3 }}>Size</Typography>
<Box rowGap={10} columnGap={2} display="grid" gridTemplateColumns={{ xs: 'repeat(1, 1fr)', sm: 'repeat(2, 1fr)' }}>
<RHFTextField name="meat" label="Protein G" />
<RHFTextField name="starches" label="Carbs G" />
<RHFUploadAvatar
sx={{ mt: 7 }}
name="photo"
maxSize={3145728}
onDrop={handleDrop}
helperText={
<Typography
variant="caption"
sx={{
mt: 3,
mx: 'auto',
display: 'block',
textAlign: 'center',
color: 'text.disabled',
}}
>
Allowed *.jpeg, *.jpg, *.png, *.gif
<br /> max size of {fData(3145728)}
</Typography>
}
/>
{/* <StaticDatePicker<Date>
orientation="landscape"
openTo="day"
shouldDisableDate={isWeekend}
/> */}
{/* <Box>
<Typography variant="h5" sx={{ my: 3 }}>Available Dates</Typography>
<MultiSelectCalendar />
</Box> */}
</Box>
<Stack spacing={3} alignItems="flex-end" sx={{ mt: 3 }}>
<LoadingButton type="submit" variant="contained" loading={isSubmitting}>
Save Changess
</LoadingButton>
</Stack>
</Card>
</Grid>
</Grid>
</FormProvider >
    );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment