import { CheckBoxApp } from "@components/CheckBoxApp";
import {
    getParticipantStatusOptions,
    OPTIONS_PARTICIPANTS_PARTICIPATION,
} from "@components/Options/participants/OptionsParticipants";
import { useState } from "react";
import { useMemo } from "react";
import { Button, Col, Form, Modal, Row } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import {
    startNotifyParticipants,
    startShow,
} from "@redux/slices/eventParticipants/eventParticipants";
import { useEffect } from "react";
import { InputApp } from "@components/InputApp";
import { useForm } from "@hooks/useForm";
import { RichTextApp } from "@components/RichTextApp";
import { IconApp } from "@components/IconApp";

const defaultValues = {
    subject: "",
    content: "",
    apply_status: false,
    errors: {},
};

export const MassiveNotificationModal = ({
    active,
    closeButton,
    callback = () => {},
}) => {
    const dispatch = useDispatch();

    const { count } = useSelector((state) => state.eventParticipants);
    const { user } = useSelector((state) => state.auth);

    const [selectedParticipation, setSelectedParticipation] = useState([]);
    const [selectedRoundtable, setSelectedRoundtable] = useState([]);
    const [selectedWorkshop, setSelectedWorkshop] = useState([]);
    const [selectedStatus, setSelectedStatus] = useState([]);

    const {
        values,
        handleInputChange,
        setInputValue,
        setErrors,
    } = useForm(defaultValues);
    const { subject, content, apply_status, errors } = values;

    useEffect(() => {
        if (active) {
            getCount();
        }
    }, [
        selectedParticipation,
        selectedRoundtable,
        selectedWorkshop,
        selectedStatus,
    ]);

    const { roundtables, workshops } = useMemo(() => {
        return {
            roundtables: active?.items_by_type?.["MESA DE PARTICIPACIÓN"] || [],
            workshops: active?.items_by_type?.["TALLER"] || [],
        };
    }, [active]);

    const getCount = () => {
        dispatch(
            startShow({
                academic_event_id: active.id,
                participation: selectedParticipation.join(","),
                activity_item_id: [
                    ...selectedRoundtable,
                    ...selectedWorkshop,
                ].join(","),
                approval_status: selectedStatus.join(","),
                count: true,
            })
        );
    };

    const handleCheck = (target, value) => {
        switch (target) {
            case "participation":
                setSelectedParticipation((prev) => {
                    const exists = prev.includes(value);
                    if (exists) {
                        // quitar
                        return prev.filter((v) => v !== value);
                    } else {
                        // agregar
                        return [...prev, value];
                    }
                });
                break;

            case "roundtable":
                setSelectedRoundtable((prev) => {
                    const exists = prev.includes(value);
                    if (exists) {
                        // quitar
                        return prev.filter((v) => v !== value);
                    } else {
                        // agregar
                        return [...prev, value];
                    }
                });
                break;

            case "workshop":
                setSelectedWorkshop((prev) => {
                    const exists = prev.includes(value);
                    if (exists) {
                        // quitar
                        return prev.filter((v) => v !== value);
                    } else {
                        // agregar
                        return [...prev, value];
                    }
                });
                break;

            case "status":
                setSelectedStatus((prev) => {
                    const exists = prev.includes(value);
                    if (exists) {
                        // quitar
                        return prev.filter((v) => v !== value);
                    } else {
                        // agregar
                        return [...prev, value];
                    }
                });
                break;
        }
    };

    const notify = (test = false) => {
        dispatch(
            startNotifyParticipants(
                {
                    // Filtros
                    academic_event_id: active.id,
                    participation: selectedParticipation.join(","),
                    activity_item_id: [
                        ...selectedRoundtable,
                        ...selectedWorkshop,
                    ].join(","),
                    approval_status: selectedStatus.join(","),
                    // Notificacion
                    subject,
                    content,
                    // Extras
                    apply_status,
                    test,
                },
                setErrors,
                callback
            )
        );
    };

    return (
        <>
            <Modal.Body>
                <h4 className="m-0 fw-bold">Filtros para notificar</h4>
                <p className="text-size-12">
                    Elige los filtros para enviar la notificación a los
                    participantes correspondientes.
                </p>

                <Row>
                    <Col xs={12} className="text-size-12 ">
                        <div className="border bg-secondary-subtle py-2 px-3 rounded">
                            <p className="text-size-12 m-0 mb-2">
                                <strong>Participación:</strong>
                            </p>
                            <div className="d-flex justify-content-around">
                                {OPTIONS_PARTICIPANTS_PARTICIPATION.map(
                                    (opt, i) => (
                                        <Form.Check
                                            className="m-0"
                                            type="checkbox"
                                            id={`participation-${i}`}
                                            value={opt}
                                            label={opt}
                                            checked={selectedParticipation.includes(
                                                opt
                                            )}
                                            onChange={(e) =>
                                                handleCheck(
                                                    "participation",
                                                    e.target.value
                                                )
                                            }
                                        />
                                    )
                                )}
                            </div>
                        </div>
                    </Col>

                    <Col xs={6} className="text-size-12 mt-3">
                        <div className="border bg-secondary-subtle py-2 px-3 rounded">
                            <p className="text-size-12 m-0 mb-2">
                                <strong>Mesa:</strong>
                            </p>
                            <div className="h-100">
                                {roundtables.map((r, i) => (
                                    <Form.Check
                                        className="m-0 mb-2"
                                        type="checkbox"
                                        id={`roundtable-${i}`}
                                        value={r.id}
                                        label={r.name}
                                        checked={selectedRoundtable.includes(
                                            r.id + ""
                                        )}
                                        onChange={(e) =>
                                            handleCheck(
                                                "roundtable",
                                                e.target.value
                                            )
                                        }
                                    />
                                ))}
                            </div>
                        </div>
                    </Col>

                    <Col xs={6} className="text-size-12 mt-3">
                        <div className="border bg-secondary-subtle py-2 px-3 rounded h-100">
                            <p className="text-size-12 m-0 mb-2">
                                <strong>Taller:</strong>
                            </p>
                            <div className="">
                                {workshops.map((w, i) => (
                                    <Form.Check
                                        className="m-0 mb-2"
                                        type="checkbox"
                                        id={`workshop-${i}`}
                                        value={w.id}
                                        label={w.name}
                                        checked={selectedWorkshop.includes(
                                            w.id + ""
                                        )}
                                        onChange={(e) =>
                                            handleCheck(
                                                "workshop",
                                                e.target.value
                                            )
                                        }
                                    />
                                ))}
                            </div>
                        </div>
                    </Col>

                    <Col xs={12} className="text-size-12 mt-3">
                        <div className="border bg-secondary-subtle py-2 px-3 rounded">
                            <p className="text-size-12 m-0 mb-2">
                                <strong>Estatus:</strong>
                            </p>
                            <div className="d-flex justify-content-around">
                                {getParticipantStatusOptions().map((opt, i) => (
                                    <Form.Check
                                        className="m-0"
                                        type="checkbox"
                                        id={`status-${i}`}
                                        value={opt.value}
                                        label={opt.label}
                                        checked={selectedStatus.includes(
                                            opt.value
                                        )}
                                        onChange={(e) =>
                                            handleCheck(
                                                "status",
                                                e.target.value
                                            )
                                        }
                                    />
                                ))}
                            </div>
                        </div>
                    </Col>

                    <Col xs={12} className="text-size-14 mt-3">
                        <div className="border bg-secondary-subtle py-2 px-3 rounded">
                            <p className="text-center my-2">
                                La notificación se enviará a{" "}
                                <strong className="text-info">{count}</strong>{" "}
                                participantes según los filtros aplicados.
                            </p>
                        </div>
                    </Col>

                    <Col xs={12} className="mt-3">
                        <InputApp
                            title="Asunto"
                            placeholder="Ingrese el asunto"
                            name="subject"
                            value={subject}
                            onChange={handleInputChange}
                            errorText={errors.subject && errors.subject[0]}
                            maxLength={190}
                            required
                        />
                    </Col>

                    <Col xs={12} className="mt-3">
                        <RichTextApp
                            title="Contenido"
                            placeholder="Ingrese el contenido"
                            name="content"
                            value={content}
                            onChange={handleInputChange}
                            errorText={errors.content && errors.content[0]}
                            required
                        />
                    </Col>
                    <Col xs={6} className="mt-3">
                        <CheckBoxApp
                            name="apply_status"
                            label={
                                <span className="text-black">
                                    Aplicar estatus{" "}
                                    <strong>"ENLACE ENVIADO"</strong>
                                </span>
                            }
                            onChange={handleInputChange}
                            className={"custom-checkbox-app"}
                            style={{ fontSize: "14px" }}
                            checked={apply_status}
                            errorText={
                                errors.apply_status && errors.apply_status[0]
                            }
                        />
                    </Col>
                    <Col xs={6} className="mt-3 text-end">
                        <IconApp
                            iconClassName="fas fa-circle-info text-warning fa-2xl me-2"
                            description={`El correo de prueba se enviará al correo del usuario en sesión (${user.email})`}
                        />
                        <Button
                            className="btn-app py-2"
                            onClick={() => notify(true)}
                        >
                            <span className="text-size-16">
                                Realizar prueba
                                <IconApp iconClassName="fas fa-flask-vial mx-2" />
                            </span>
                        </Button>
                    </Col>
                </Row>
            </Modal.Body>
            <Modal.Footer className="justify-content-between">
                {closeButton()}

                <Button
                    className="text-white fw-bold py-2"
                    variant="primary"
                    disabled={!count}
                >
                    <span className="text-size-16" onClick={() => notify()}>
                        Notificar
                        <IconApp iconClassName="fas fa-bell ms-2" />
                    </span>
                </Button>
            </Modal.Footer>
        </>
    );
};
