import * as Yup from 'yup';
import { Formik, Form, Field } from 'formik';
import { AlertDialog } from '../common';
import {
  Button,
  Select as ChakraSelect,
  Input,
  FormErrorMessage,
  FormControl,
  FormLabel,
  Stack,
  HStack,
} from '@chakra-ui/react';
import { Select } from 'chakra-react-select';
import { useQueryClient } from 'react-query';

import { EVENT_NAMES } from '../../constants/define';

const UserCreationSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
  password: Yup.string().min(6, 'Too Short!').max(50, 'Too Long!').required('Required'),
  firstName: Yup.string().required('Required'),
  lastName: Yup.string().required('Required'),
  roles: Yup.array().required('Required'),
  userStatus: Yup.string().required('Required'),
});

const initialFormValues = {
  email: '',
  firstName: '',
  lastName: '',
  password: '',
  roles: [],
  userStatus: 'active',
};

function UserCreationForm({ formRef, isLoading, onCreate }) {
  const queryClient = useQueryClient(),
    roles = queryClient.getQueryData([EVENT_NAMES.ESSENTIAL.RETRIEVE]).roles || [],
    userStatusChoices = queryClient.getQueryData([EVENT_NAMES.ESSENTIAL.RETRIEVE]).userStatusChoices || [];

  const handleCreate = async () => {
    console.log('hello world');
    await onCreate();
  };

  return (
    <AlertDialog onConfirm={handleCreate}>
      {(onOpenConfirmation) => (
        <Formik
          initialValues={initialFormValues}
          innerRef={formRef}
          validationSchema={UserCreationSchema}
          onSubmit={onOpenConfirmation}
        >
          {({ errors, touched }) => (
            <Form>
              <Stack spacing={10}>
                <FormControl isRequired isInvalid={!!errors.email && touched.email}>
                  <FormLabel htmlFor="email">Email</FormLabel>
                  <Field as={Input} id="email" name="email" placeholder="Email" />
                  <FormErrorMessage>{errors.email}</FormErrorMessage>
                </FormControl>
                <FormControl isRequired isInvalid={!!errors.password && touched.password}>
                  <FormLabel htmlFor="password">Password</FormLabel>
                  <Field as={Input} type="password" id="password" name="password" placeholder="Password" />
                  <FormErrorMessage>{errors.password}</FormErrorMessage>
                </FormControl>
                <HStack alignItems="flex-start" justifyContent="space-between">
                  <FormControl isInvalid={!!errors.firstName && touched.firstName} isRequired id="firstName">
                    <FormLabel htmlFor="firstName">First Name</FormLabel>
                    <Field as={Input} id="firstName" name="firstName" placeholder="First Name" />
                    <FormErrorMessage>{errors.firstName}</FormErrorMessage>
                  </FormControl>
                  <FormControl isInvalid={!!errors.lastName && touched.lastName} isRequired id="lastName">
                    <FormLabel htmlFor="lastName">Last Name</FormLabel>
                    <Field as={Input} id="lastName" name="lastName" placeholder="Last Name" />
                    <FormErrorMessage>{errors.lastName}</FormErrorMessage>
                  </FormControl>
                </HStack>
                <FormControl isInvalid={!!errors.roles && touched.roles} isRequired>
                  <FormLabel htmlFor="roles">Roles</FormLabel>
                  <Field name="roles">
                    {({ field }) => (
                      <Select
                        {...field}
                        id="roles"
                        isMulti
                        colorScheme="primary"
                        onChange={(values) => {
                          field.onChange({ target: { name: 'roles', value: values } });
                        }}
                        options={
                          roles?.map((role) =>
                            role
                              ? {
                                  value: role.id,
                                  label: role.name,
                                }
                              : undefined,
                          ) || []
                        }
                      />
                    )}
                  </Field>

                  <FormErrorMessage>
                    {errors.roles?.map((error, errorIndex) => (
                      <div key={errorIndex}>{error}</div>
                    ))}
                  </FormErrorMessage>
                </FormControl>
                <FormControl isInvalid={!!errors.userStatus && touched.userStatus} isRequired>
                  <FormLabel htmlFor="status">Status</FormLabel>
                  <Field id="userStatus" name="userStatus" as={ChakraSelect}>
                    {userStatusChoices?.map((userStatus) => (
                      <option key={userStatus?.value} value={userStatus?.value}>
                        {userStatus?.name}
                      </option>
                    ))}
                  </Field>
                  <FormErrorMessage>{errors.userStatus}</FormErrorMessage>
                </FormControl>
                <Button width="200px" type="submit" colorScheme="primary" isLoading={isLoading} loadingText="Creating">
                  Create
                </Button>
              </Stack>
            </Form>
          )}
        </Formik>
      )}
    </AlertDialog>
  );
}

UserCreationForm.propTypes = {};

export default UserCreationForm;
