import * as Yup from 'yup';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import LoadingButton from '@mui/lab/LoadingButton';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import FormProvider, { RHFTextField,} from '@/shared/components/hook-form';
import { IProduct } from '@/shared/types/invoice';
import { createProduct } from '@/shared/api/invoice';

// ----------------------------------------------------------------------

type Props = {
  open: boolean;
  onClose: VoidFunction;
  onCreate: (product: IProduct) => void;
};

export default function ProductNewForm({ open, onClose, onCreate }: Props) {
  const NewProductSchema = Yup.object().shape({
    name: Yup.string().required('name is required'),
  });

  const defaultValues = {
    name: '',
  };

  const methods = useForm({
    resolver: yupResolver(NewProductSchema),
    defaultValues,
  });

  const {
    handleSubmit,
    formState: { isSubmitting },
    reset,
  } = methods;

  const onSubmit = handleSubmit(async (data) => {
    try {
      
      const response = await createProduct(data);
      onCreate(response.data);
      onClose();
      reset();
    } catch (error) {
      console.error(error);
      console.log("add product/service a echoué")
    }
  });

  return (
    <Dialog fullWidth maxWidth="sm" open={open} onClose={onClose}>
      <FormProvider methods={methods} onSubmit={onSubmit}>
        <DialogTitle>New Product/Service</DialogTitle>

        <DialogContent> 
            <RHFTextField name="name" label="Name" placeholder='Product/Service Name' sx={{ mt: 1}} />    
        </DialogContent>

        <DialogActions>
          <Button color="inherit" variant="outlined" onClick={onClose}>
            Cancel
          </Button>
          <LoadingButton type="submit" variant="contained"  loading={isSubmitting}>
            Add
          </LoadingButton>
        </DialogActions>
      </FormProvider>
    </Dialog>
  );
}
