import {useMutation, useQueryClient} from '@tanstack/react-query'
import {Formik, Form} from 'formik'
import * as Yup from "yup";
import InputText from '../InputText'
import {addCustomTemplate} from '../../services/siteServices'
import queryKeys from '../../services/queryKeys';


const initialValues = {
    custom_id: "",
    provision_name: "",
};

// To get the validation schema
const validationSchema = Yup.object().shape({
    custom_id: Yup.string().required("custom_id is required").min(6, 'must be upto 6 characters').max(25, 'must not exceed 25 characters'),
    provision_name: Yup.string().required("provision_name is required").min(6, 'must be upto 6 characters').max(25, 'must not exceed 25 characters'),
});

export default function AddTemplate() {

    const queryClient = useQueryClient()

    const customTemplate = useMutation({
        mutationFn: (fields) => {
            if (!fields.custom_id || !fields.provision_name) {
                throw new Error('Please provide all fields marked *')
            }
            return addCustomTemplate(fields)
        },
        onSuccess: () => {
            queryClient.refetchQueries({
                queryKey: [...queryKeys.custom_template],
                // type: 'active',
                // exact: true,
            })
        },
    })

    //FUNCTION TO HANDLE ADD TEMPLATE
    const handleSubmit = (values, helper) => {
        customTemplate.mutate(values)
    };

  return (
    <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
    >
        {(props) => (
            <Form>
                <div
                    className='flex flex-col w-full bg-white rounded-xl p-16 sm:px-20 sm:py-16 shadow'>
                    <div className='w-full flex flex-col gap-4'>
                        <div className='relative text-input flex flex-col sm:flex-row gap-2 sm:items-center'>
                            <label className={`text-base min-w-36 text-end sm:text-left ${(props.errors.custom_id && props.touched.custom_id) && 'text-red-500'}`}>
                                Custom ID
                            </label>
                            <InputText
                                id='custom_id'
                                placeholder='Custom ID'
                                name='custom_id'
                                value={props.values.custom_id}
                                handleChange={props.handleChange}
                            />
                        </div>
                        <div className='relative text-input flex flex-col sm:flex-row gap-2 sm:items-center'>
                            <label className={`text-base min-w-36 text-end sm:text-left ${(props.errors.provision_name && props.touched.provision_name) && 'text-red-500'}`}>
                                Provision Name
                            </label>
                            <InputText
                                id='provision_name'
                                placeholder='Provision Name'
                                name='provision_name'
                                value={props.values.provision_name}
                                handleChange={props.handleChange}
                            />
                        </div>

                        <div className='h-10 my-5 text-end'>
                            <button type='submit' disabled={customTemplate.isPending}
                                    className='px-4 h-full bg-primary text-white font-bold rounded-md'>{customTemplate.isPending ? 'loading...' : 'Add'}</button>
                        </div>

                        {customTemplate.error &&
                            <>
                                <div className="w-full text-center">
                                    <p className='text-red-500 text-sm'>{customTemplate.error.message}</p>
                                </div>
                            </>
                        }
                        {customTemplate.isSuccess &&
                            <>
                                <div className="w-full text-center">
                                    <p className='text-emerald-500 text-sm'>{'Template Added'}</p>
                                </div>
                            </>
                        }
                    </div>
                </div>
            </Form>
        )}
    </Formik>
  )
}
