/**
 * Core
 * ============================================
 */
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Grid } from '@mui/material';

/**
 * Components
 * ============================================
*/
// - Global -
import { FormProvider, RHFTextField } from '@/components/hook-form';
// - Local -

/**
 * Icon, Utils, Types, Functions
 * ============================================
 */
import { Search } from '@mui/icons-material';
import { SearchType } from '../Model/Types';

type Props = {
    onSubmit: (keyword: string) => void,
    onEmpty: () => void,
};

const FormCreateSearch = ({ onSubmit, onEmpty }: Props) => {
    const defaultValuesSearchForm = {
        keyword: ''
    };

    const methodsSearchForm = useForm<SearchType>({
        defaultValues: defaultValuesSearchForm
    });

    const { handleSubmit, formState: { isDirty } } = methodsSearchForm;

    // search on submit
    const onSubmitSearch = (data: SearchType ) => {
        onSubmit(data.keyword);
    }

    // search on empty
    useEffect(() => {
        if (isDirty === false) {
            onEmpty()
        }
    },[isDirty])

    return (
        <FormProvider methods={methodsSearchForm} onSubmit={handleSubmit(onSubmitSearch)}>
            <Grid container direction={"row"}>
                <Grid item xs={12}>
                    <RHFTextField
                        name="keyword"
                        placeholder="Search..."
                        autoComplete='off'
                        fullWidth
                        InputProps={{ startAdornment: <Search /> }}
                        sx={{ input: { paddingLeft: '14px' } }}
                    />
                </Grid>
            </Grid>
        </FormProvider>
    )
}

export default FormCreateSearch
