import { SubmitHandler, useForm } from 'react-hook-form'
import { CreateField } from '../interfaces/create'
import { Box, Button, CircularProgress, Stack, TextField, Typography } from '@mui/material';
import { useEffect } from 'react';

interface Props {
    title?: string;
    submitHandler?: any;
    fields: CreateField[];
    submitButtonText?: string;
    mutateHandler?: any;
    defaultValues?: {};
    watchValues?: string[];
}

function FormFields({
    title = '',
    submitHandler,
    fields,
    submitButtonText = 'Сохранить',
    mutateHandler,
    defaultValues
}: Props) {
    const getDefaultValues = (fields: CreateField[]) => {
        let result: { [key: string]: string | boolean } = {}
        fields.forEach((field: CreateField) => {
            result[field.key] = field.defaultValue || defaultValues?.[field.key as keyof {}]
        })
        return result
    }

    const { register, handleSubmit, watch, formState: { errors, isSubmitting, dirtyFields } } = useForm({
        defaultValues: getDefaultValues(fields)
    })

    const onSubmit: SubmitHandler<any> = async (data) => {
        try {
            await submitHandler?.(data).then(() => {
                mutateHandler?.()
            })
        } catch (error) {
            console.error(error)
        }
    }

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <Stack spacing={2} width='100%'>
                <Typography variant="h6" component="h6" gutterBottom>
                    {title}
                </Typography>

                {fields.map((field: CreateField) => {
                    return (
                        <TextField
                            fullWidth
                            margin='normal'
                            key={field.key}
                            type={field.inputType ? field.inputType : 'text'}
                            label={field.headerName || field.key.charAt(0).toUpperCase() + field.key.slice(1)}
                            required={field.required || false}
                            {...register(field.key, {
                                required: `${field.key} обязателен`,
                                validate: (val: string | boolean) => {
                                    if (field.watch) {
                                        if (watch(field.watch) != val) {
                                            return field.watchMessage || ''
                                        }
                                    }
                                }
                            })}
                            error={!!errors[field.key]}
                        />
                    )
                })}

                <Box sx={{
                    display: "flex",
                    justifyContent: "space-between",
                    gap: "8px"
                }}>
                    <Button disabled={isSubmitting} type="submit" variant="contained" color="primary">
                        {isSubmitting ? <CircularProgress size={16} /> : submitButtonText}
                    </Button>
                </Box>
            </Stack>
        </form>
    )
}

export default FormFields