import React,{useEffect} from "react";
import {  Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField } from "@mui/material";
import { useForm, Controller } from "react-hook-form";

interface AddEditTagsModalProps {
    open: boolean;
    handleClose: () => void;
    editRow:any;
}

interface FormData {
    tag: string;
}

const AddEditTagsModal: React.FC<AddEditTagsModalProps> = ({ open, handleClose,editRow }) => {
    const { control, handleSubmit, formState: { errors },setValue,reset } = useForm<FormData>({
        defaultValues: {
            tag: "",
        },
    });

    const onSubmit = (data: FormData) => {
        console.log(data.tag);
        handleClose();
        reset(); 
    };

    useEffect(() => {
        if (editRow) {
          setValue('tag', editRow.name);      
        } else {
          reset(); 
        }
      }, [editRow, setValue, reset]);

    return (
        <>
            <Dialog
                open={open}
                onClose={handleClose}
                maxWidth="md" 
                fullWidth
                PaperProps={{
                    component: 'form',
                    onSubmit: handleSubmit(onSubmit), 
                }}
            >
                <DialogTitle>{editRow ? "Edit" : 'Add'} Tag</DialogTitle>
                <DialogContent>
                    <Controller
                        name="tag"
                        control={control}
                        rules={{
                            required: "Tag Name is required",  
                           
                        }}
                        render={({ field }) => (
                            <TextField
                                {...field}
                                autoFocus
                                required
                                margin="dense"
                                label="Add Tag Name"
                                type="text"
                                fullWidth
                                variant="standard"
                                error={!!errors.tag}  
                                helperText={errors.tag?.message}  
                            />
                        )}
                    />
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleClose}>Cancel</Button>
                    <Button type="submit">Save</Button>
                </DialogActions>
            </Dialog>
        </>
    );
};

export default AddEditTagsModal;
