import { ArrowRightOutlined } from "@ant-design/icons";
import Buttons from "../../../../Components/Forms/Buttons";
import { gettableData, postPreferenceAppNames } from "../../../../Features/PreferenceMaster/PreferenceMaster";
import { getSession } from "../../../../Services/Others";
import { useDispatch } from "react-redux";
import { useEffect, useState } from "react";
import { getPreferenceData } from "../../../../Features/BookingScreen/BookingData/BookingData";
import { Messages } from "../../../../Components/Notifications/Messages";
import { changeSelectedPrintdummyData } from "../../../../Features/ThemeChange/ThemeChange";

const SelectPrintMode = ({ closeModel }) => {
    const CompId = getSession("CompId");
    const BranchId = getSession("BranchId");
    const AppId = getSession("AppId");
    const UserId = getSession("UserId");
    const dispatch = useDispatch();

    const [modes, setModes] = useState([]);
    const [selected, setSelected] = useState({
        whatsapp: false,
        sms: false,
        print: false,
        email: false
    });
    const [messageType, setMessageType] = useState("");
    const [messageData, setMessageData] = useState("");

    console.log(selected, 'selected');


    useEffect(() => {
        fetchTableData();
    }, []);

    const fetchTableData = async () => {

        const response = await dispatch(
            gettableData({ CompId, BranchId, AppId })
        ).unwrap();

        const data = response?.data?.data?.[0]?.SettingDtlDetails || [];
        console.log(data, 'datadata');

        setModes(data);

        // Pre-fill checkboxes from API data
        setSelected({
            whatsapp: !!data.find(
                (i) =>
                    i.SettingIdName?.trim()?.toLowerCase() === "whatsapp" &&
                    i.SettingValue === "Y"
            ),
            sms: !!data.find(
                (i) =>
                    i.SettingIdName?.trim()?.toLowerCase() === "sms" &&
                    i.SettingValue === "Y"
            ),
            print: !!data.find(
                (i) =>
                    i.SettingIdName?.trim()?.toLowerCase() === "print" &&
                    i.SettingValue === "Y"
            ),
            email: !!data.find(
                (i) =>
                    i.SettingIdName?.trim()?.toLowerCase() === "email" &&
                    i.SettingValue === "Y"
            )
        });

    };

    const handleChange = (key) => {
        setSelected((prev) => ({
            ...prev,
            [key]: !prev[key]
        }));


    };


    const handleSave = async () => {
        const allowed = ["whatsapp", "sms", "print", "email"];

        const updatedSettings = modes.map((item) => {
            const name = item.SettingIdName?.trim()?.toLowerCase();

            if (allowed?.includes(name)) {
                return {
                    ...item,
                    SettingValue: selected[name] ? "Y" : "N"
                };
            }

            return item;

        });

        const payload = {
            CompId,
            BranchId,
            CreatedBy: UserId,
            AppId,
            SettingDtlDetails: updatedSettings
        };

        console.log(payload, "payload to send");

        try {
            const response = await dispatch(postPreferenceAppNames(payload)).unwrap();

            if (response?.data?.statusCode === 1) {
                setMessageType("success");
                setMessageData("Printer settings saved successfully.");
                dispatch(changeSelectedPrintdummyData(false));
                await updatePreference();
                closeModel()
            } else {
                setMessageType("error");
                setMessageData(response?.data?.message || "Failed to save printer settings.");
            }
        } catch (error) {
            console.error("Error while saving:", error);
        }
    };

    const updatePreference = async () => {
        await dispatch(getPreferenceData({ CompId, BranchId, AppId }));
    }

    return (
        <div
            style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "center",
            }}
        >
            <Messages
                messageType={messageType}
                messageData={messageData}
                onComplete={() => {
                    setMessageData(null);
                    setMessageType(null);
                }}
            />
            <p style={{ fontSize: "18px", marginBottom: "10px" }}>
                Select Print Mode
            </p>

            <div style={{ display: "flex", gap: "1rem", padding: "10px" }}>
                <label>
                    <input
                        type="checkbox"
                        style={{ marginRight: "0.5rem" }}
                        checked={selected.whatsapp}
                        onChange={() => handleChange("whatsapp")}
                    />
                    WhatsApp
                </label>

                <label>
                    <input
                        type="checkbox"
                        style={{ marginRight: "0.5rem" }}
                        checked={selected.sms}
                        onChange={() => handleChange("sms")}
                    />
                    SMS
                </label>

                <label>
                    <input
                        type="checkbox"
                        style={{ marginRight: "0.5rem" }}
                        checked={selected.print}
                        onChange={() => handleChange("print")}
                    />
                    Print
                </label>

                <label>
                    <input
                        type="checkbox"
                        style={{ marginRight: "0.5rem" }}
                        checked={selected.email}
                        onChange={() => handleChange("email")}
                    />
                    Email
                </label>
            </div>


            <div
                style={{
                    width: "100%",
                    display: "flex",
                    justifyContent: "flex-end",
                    marginTop: 24,
                }}
            >
                <Buttons
                    buttonText="Save"
                    color="901D77"
                    icon={<ArrowRightOutlined />}
                    htmlType={true}
                    handleSubmit={handleSave}
                />
            </div>
        </div>
    );
};

export default SelectPrintMode;
