import React from 'react';
import { Field, Form, Formik } from 'formik';
import { useRouter } from 'next/router';

const Search = () => {
  const router = useRouter();

  const validateSearch = (value) => {
    let error;
    if (!value) {
      error = 'Required';
    } else if (value.length < 2) {
      error = 'Minimum length: 2 characters';
    }
    return error;
  };

  return (
    <Formik
      initialValues={{
        search: '',
      }}
      onSubmit={(values, { setSubmitting, resetForm }) => {
        router.push(`/search?query=${values.search}`);
        resetForm();
        setSubmitting(false);
      }}
      validateOnBlur={false}
      validateOnChange={false}
    >
      {({ errors, touched, values }) => (
        <Form className='relative w-[340px] max-w-[44vw]'>
          <Field
            id='search'
            name='search'
            validate={validateSearch}
            placeholder='Search accounts, orders, SKUs'
            className='h-10 w-full rounded-xl border border-slate-200 bg-slate-50 px-4 text-sm text-slate-900 outline-none transition focus:border-emerald-500 focus:bg-white focus:ring-2 focus:ring-emerald-100 dark:border-dark-700 dark:bg-dark-900 dark:text-white dark:placeholder-dark-600'
          />
          {errors.search && touched.search && values.search.length < 2 ? (
            <div className='absolute left-2 top-11 text-xs font-semibold text-red-500'>
              {errors.search}
            </div>
          ) : null}
        </Form>
      )}
    </Formik>
  );
};

export default Search;
