import PropTypes from 'prop-types';
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { Grid, TextField, Button, MenuItem } from '@mui/material';
import { useState } from 'react';
import * as Yup from 'yup';
import { Formik } from 'formik';
import axios from 'axios';
import MainCard from 'components/MainCard';
import AnimateButton from 'components/@extended/AnimateButton';
import Typography from '@mui/material/Typography';

export default function Users() {
  const navigate = useNavigate();
  const serverUrl = import.meta.env.VITE_APP_SERVER_URL;

  const handleFormSubmit = async (values, { setErrors }) => {
    try {
        console.log(serverUrl);
      const response = await axios.post(`${serverUrl}/api/v1/admin/createUser`, {
        name: values.name,
        email: values.email,
        password: values.password,
        userType: values.userType, // Formik now tracks this value
      }, {
        withCredentials: true, // To send cookies with the request
      });
  
      if (response.data.status === 1) {
        console.log('User created successfully');
      } else {
        setErrors({ submit: response.data.message });
      }
    } catch (error) {
      console.error('Error during user creation:', error);
      setErrors({ submit: 'An error occurred. Please try again.' });
    }
  };

  return (
    <Grid
      container
      spacing={0}
      direction="column"
      alignItems="center"
      justifyContent="center"
      sx={{ height: 'auto', mt: 5 }}
    >
      <Grid item xs={12} sm={8} md={6} lg={4}>
        <MainCard
          title="Create User"
          sx={{ width: '100%', maxWidth: 400 }}
          secondary={
            <Button variant="outlined" onClick={() => navigate('/manageusers')}>
              Manage Users
            </Button>
          }
        >
          <Formik
            initialValues={{ name: '', email: '', password: '', userType: '' }}
            validationSchema={Yup.object().shape({
              name: Yup.string().required('Name is required'),
              email: Yup.string().email('Must be a valid email').required('Email is required'),
              password: Yup.string().required('Password is required'),
              userType: Yup.string().required('User Type is required') // Make sure this is part of the validation schema
            })}
            onSubmit={handleFormSubmit}
          >
            {({ errors, handleBlur, handleChange, handleSubmit, isSubmitting, touched, values }) => (
              <form noValidate onSubmit={handleSubmit}>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      label="Name"
                      variant="outlined"
                      name="name"
                      value={values.name}
                      onBlur={handleBlur}
                      onChange={handleChange}
                      error={Boolean(touched.name && errors.name)}
                      helperText={touched.name && errors.name}
                    />
                  </Grid>

                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      label="Email"
                      type="email"
                      variant="outlined"
                      name="email"
                      value={values.email}
                      onBlur={handleBlur}
                      onChange={handleChange}
                      error={Boolean(touched.email && errors.email)}
                      helperText={touched.email && errors.email}
                    />
                  </Grid>

                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      label="Password"
                      type="password"
                      variant="outlined"
                      name="password"
                      value={values.password}
                      onBlur={handleBlur}
                      onChange={handleChange}
                      error={Boolean(touched.password && errors.password)}
                      helperText={touched.password && errors.password}
                    />
                  </Grid>

                  <Grid item xs={12}>
                    <TextField
                      select
                      fullWidth
                      label="User Type"
                      name="userType" // Add this name so Formik can track it
                      value={values.userType}
                      onBlur={handleBlur}
                      onChange={handleChange} // Formik handles the change
                      variant="outlined"
                      error={Boolean(touched.userType && errors.userType)}
                      helperText={touched.userType && errors.userType}
                    >
                      <MenuItem value="admin">Admin</MenuItem>
                      <MenuItem value="subadmin">Sub Admin</MenuItem>
                      <MenuItem value="editor">Editor</MenuItem>
                    </TextField>
                  </Grid>

                  {errors.submit && (
                    <Grid item xs={12}>
                      <Typography variant="body2" color="error">
                        {errors.submit}
                      </Typography>
                    </Grid>
                  )}

                  <Grid item xs={12}>
                    <AnimateButton>
                      <Button
                        disableElevation
                        disabled={isSubmitting}
                        fullWidth
                        size="large"
                        type="submit"
                        variant="contained"
                        color="primary"
                      >
                        Create User
                      </Button>
                    </AnimateButton>
                  </Grid>
                </Grid>
              </form>
            )}
          </Formik>
        </MainCard>
      </Grid>
    </Grid>
  );
}

Users.propTypes = { isDemo: PropTypes.bool };
