import { Button, Modal, Form } from "react-bootstrap";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { toRejectBulkFile } from "@/services/bulkUploadRequest";
import { toast, ToastContainer } from 'react-toastify';

interface Prop {
    isModalStatus: boolean;
    handleModalClosefn: () => void;
    handleModalDatafn: () => void;
    selectedTableRowData: any;
}

const schema = yup.object().shape({
    reason: yup
        .string()
        .required("Reason is required")
        .test('wordCount', 'Maximum 50 words allowed', function (value) {
            const wordCount = value?.trim().split(/\s+/).filter(word => word.length > 0).length || 0;
            return wordCount <= 50;
        }),
});

const BulkImportRejectModal = (props: Prop) => {
    const {
        register,
        handleSubmit,
        formState: { errors },
        reset,
    } = useForm({
        resolver: yupResolver(schema),
        defaultValues: {
            reason: "",
        },
    });

    const onSubmit = async (data: any) => {
        try {
            const makePayload = {
              file_id: props?.selectedTableRowData?.id,
              comment: data?.reason,
            };
        
            const response = await toRejectBulkFile(makePayload);
        
            if (response?.status === 'success') {
              toast.success(response?.message, {
                position: toast.POSITION.TOP_CENTER,
                style: { textAlign: 'left' },
              });
              reset(); // Clear form after submission
              props.handleModalDatafn();
              props.handleModalClosefn();
            } else {
              toast.error(response?.message, {
                position: toast.POSITION.TOP_CENTER,
                style: { textAlign: 'left' },
              });
            }
          } catch (error) {
            console.error(error);
            toast.error("An error occurred while rejecting the file", {
              position: toast.POSITION.TOP_CENTER,
              style: { textAlign: 'left' },
            });
          }
    };

    const handleClose = () => {
        reset(); // Reset to initial state
        props.handleModalClosefn();
    };

    return (
        <div>
            <ToastContainer />
            <Modal show={props.isModalStatus} onHide={handleClose}>
                <Form onSubmit={handleSubmit(onSubmit)}>
                    <Modal.Header closeButton>
                        <Modal.Title>Reason for rejection</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Form.Group controlId="reason">
                            <Form.Control
                                as="textarea"
                                rows={3}
                                {...register("reason")}
                                placeholder="Enter reason (max 50 words)"
                            />
                            {errors.reason && (
                                <p className="text-danger mt-1">{errors.reason.message}</p>
                            )}
                        </Form.Group>
                    </Modal.Body>
                    <Modal.Footer className="bulk-import-modal-footer">
                        <div>
                            <Button
                                type="submit"
                                className="bulk-import-submit-btn mx-2"
                            >
                                Confirm
                            </Button>
                            <Button
                                type="button"
                                className="bulk-import-close-btn mx-2"
                                onClick={handleClose}
                            >
                                Close
                            </Button>
                        </div>
                    </Modal.Footer>
                </Form>
            </Modal>
        </div>
    );
};

export default BulkImportRejectModal;
