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 { IPaymentMethod } from '@/shared/types/invoice';
import { createPaymentMode } from '@/shared/api/invoice';

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

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

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

  const defaultValues = {
    name: '',
  };

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

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

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

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

        <DialogContent> 
            <RHFTextField name="name" label="Name" placeholder='Payment Method 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>
  );
}
