"use client";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useSessionStore } from "@store/Sesion.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import Textbox from "@components/Textbox/Textbox";
import { useAlert } from "@store/Alert.Store";
import MaterialAlert from "@mui/material/Alert";
import { useNavigation } from "@hooks/goto";
import { useEffect, useState } from "react";
import {
    loadServicesById,
    createService,
    updateService,
    uploadImage,
    savePublishedStatus,
    applyDiscount,
    deleteDiscount,
} from "../Services.Service";
import {
    ApplyDiscountParams,
    CompanyServiceView,
    DeleteDiscountParams,
    SERVICE_PUBLISHED_STATUS,
    SetPublishedStatusParams,
} from "@core/Models/Service.model";
import ImagePicker from "@core/app/components/ImagePicker/ImagePicker";
import { PopoverPicker } from "@core/app/components/ColorPicker/ColorPicker";
import Switch from "@core/app/components/Switch/Switch";
import { Grid2 } from "@mui/material";
import ButtonMaterial from "@mui/material/Button";
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
import { DiscountType, FindDiscountsParams } from "@core/Models/Discounts.model";
import { formatPrice } from "@core/app/helpers/Numbers";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import TextObjectFilterItem from "@core/app/components/TextObjectFilterItem/TextObjectFilterItem";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import DialogWindow from "@core/app/components/DialogWindow/DialogWindow";
import { DialogActions, DialogContent } from "@mui/material";
import Link from "next/link";
import { useConfirmStore } from "@core/Store/Confirm.Store";

type UrlData = {
    id: string;
    sid: string;
};

export default function OrganizationService() {
    const data = useParams<UrlData>();
    const id = data.id;
    const sid = data.sid;
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const location = useLocationStore();
    const alert = useAlert();
    const confirm = useConfirmStore();
    const bottomToolbar = useBottomToolbarStore();
    const { goTo } = useNavigation();

    const [serviceName, setServiceName] = useState("");
    const [serviceDescription, setServiceDescription] = useState("");
    const [serviceOriginalPrice, setServiceOriginalPrice] = useState("");
    const [serviceLimit, setServiceLimit] = useState("");
    const [serviceLength, setServiceLength] = useState("");

    const [serviceImage, setServiceImage] = useState("");
    const [serviceColor, setServiceColor] = useState("");
    const [serviceFontColor, setServiceFontColor] = useState("");
    const [serviceFontShadowColor, setServiceFontShadowColor] = useState("");

    const [serviceDiscountType, setServiceDiscountType] = useState<string | undefined>(undefined);
    const [serviceDiscountValue, setServiceDiscountValue] = useState<number | undefined>(undefined);
    const [serviceDiscountName, setServiceDiscountName] = useState<string | undefined>(undefined);

    const [servicePublished, setServicePublished] = useState<SERVICE_PUBLISHED_STATUS | undefined>(
        undefined
    );

    const [savePublishedStatusAvailable, setSavePublishedStatusAvailable] = useState(false);

    const [dialogDiscountVisible, setDialogDiscountVisible] = useState(false);

    const [discountsFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div
                    style={{
                        fontWeight: "700",
                        fontSize: "14px",
                        paddingTop: "7px",
                    }}
                >
                    Seleccionar Descuento:
                </div>
                <p
                    style={{
                        fontWeight: "500",
                        fontSize: "13px",
                        paddingTop: "2px",
                    }}
                >
                    Ingrese el nombre del descuento para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

    const [discountsFilterData, setDiscountsFilterData] = useState<TextObjectFilterResult[]>([]);
    const [discountId, setDiscountId] = useState<string>("");

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);

        bottomToolbar.set(
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    flexDirection: "row",
                    fontWeight: "bold",
                    color: "var(--white)",
                    padding: "10px",
                    width: "100%",
                    fontSize: "22px",
                    paddingRight: "50px",
                }}
            >
                <ButtonMaterial
                    variant="text"
                    startIcon={<DiscountsIcon />}
                    sx={{ color: "var(--white)", marginLeft: "30px" }}
                    onClick={() => {
                        setDialogDiscountVisible(true);
                    }}
                >
                    Aplicar Descuento
                </ButtonMaterial>
            </div>
        );
    }, []);

    useEffect(() => {
        location.clear();

        location.add({
            url: "/admin/org/profile/" + id,
            title: "Organizacion",
            icon: null,
        });

        location.add({
            url: "/admin/org/profile/" + id + "/services",
            title: "Servicios",
            icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "/admin/org/services",
            title: sid === "new" ? "Crear servicio" : "Editar Servicio",
            icon: <StorefrontOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        if (sid !== "new") {
            eventHandler.setEventType(EVENT_TYPES.LOADING);
            cargarDatos();
        }
    }, []);

    useEffect(() => {
        const filter: FindDiscountsParams = {
            companyId: id,
            sessionUser: SessionInfo.userId,
        };
        filterObjects<FindDiscountsParams>("discounts/filter-all", filter).then((res) => {
            setDiscountsFilterData(res);
        });
    }, [SessionInfo.userId]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            //validar datos
            if (sid === "new") {
                //crear nuevo servicio.

                createService({
                    companyId: id,
                    name: serviceName,
                    description: serviceDescription,
                    originalPrice: parseFloat(serviceOriginalPrice),
                    limit: parseInt(serviceLimit),
                    length: parseInt(serviceLength),
                    sessionUser: SessionInfo.userId,
                })
                    .then(() => {
                        alert.showSuccess("Servicio creado");
                        goTo("/admin/org/profile/" + id + "/services");
                    })
                    .catch((error) => {
                        alert.showError(error.message);
                    })
                    .finally(() => {
                        eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    });
            } else {
                //editar servicio actual.
                updateService({
                    id: sid,
                    companyId: id,
                    name: serviceName,
                    description: serviceDescription,
                    originalPrice: parseFloat(serviceOriginalPrice),
                    limit: parseInt(serviceLimit),
                    length: parseInt(serviceLength),
                    color: serviceColor,
                    fontColor: serviceFontColor,
                    fontShadowColor: serviceFontShadowColor,
                    sessionUser: SessionInfo.userId,
                })
                    .then(() => {
                        alert.showSuccess("Servicio Actualizado");
                    })
                    .catch((error: Error) => {
                        alert.showError(error.message);
                    })
                    .finally(() => {
                        eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    });
            }
        }
    }, [eventHandler.eventType]);

    const cargarDatos = () => {
        loadServicesById(sid)
            .then((response: CompanyServiceView) => {
                setServiceName(response.name);
                setServiceDescription(response.description);
                setServiceLength(response.length.toString());
                setServiceOriginalPrice(response.originalPrice.toString());
                setServiceLimit(response.limit.toString());
                setServiceImage(response.image);
                setServiceColor(response.color);
                setServiceFontColor(response.fontColor);
                setServiceFontShadowColor(response.fontShadowColor);
                setServicePublished(response.published);
                setServiceDiscountType(response.discountType);
                setServiceDiscountValue(response.discountValue);
                setServiceDiscountName(response.discountName);
            })
            .catch(() => {})
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const formatDiscount = (
        value: number | undefined,
        type: string | undefined,
        name: string | undefined
    ): string => {
        if (value === undefined || value === null || type === undefined || type === null) {
            return "";
        }

        if (type === DiscountType.PERCENTAGE) {
            const newPrice = Number(serviceOriginalPrice) * (1 - value / 100);
            return `${value}% - ${name} - Precio final: ${formatPrice(newPrice)}`;
        } else if (type === DiscountType.FIXED) {
            const newPrice = Number(serviceOriginalPrice) - value;
            return `${formatPrice(value)} - ${name} - Precio final: ${formatPrice(newPrice)}`;
        }

        return `${value}`;
    };

    const handleServiceImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        e.preventDefault();

        const file = e.target.files?.[0];

        if (!file) {
            return;
        }

        const formData = new FormData();
        formData.append("companyId", id);
        formData.append("serviceId", sid);
        formData.append("sessionUser", SessionInfo.userId); // Añade el ID del usuario
        formData.append("file", file);

        uploadImage(formData)
            .then((res) => {
                if (res.success) {
                    alert.showSuccess("Imagen actualizada");
                }
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const getPublishedStatusText = () => {
        if (servicePublished === SERVICE_PUBLISHED_STATUS.PUBLISHED) {
            return "Público";
        } else {
            return "Privado";
        }
    };

    const savePublishedStatusHandler = () => {
        if (!servicePublished) {
            return;
        }

        const data: SetPublishedStatusParams = {
            serviceId: sid,
            published: servicePublished,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        savePublishedStatus(data)
            .then(() => {
                alert.showSuccess("Estado de publicación actualizado");
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const createDiscountHandler = () => {
        if (!SessionInfo.userId) {
            return;
        }

        if (!discountId || discountId === "") {
            alert.showError("Debe seleccionar un descuento para aplicar.");
            return;
        }

        const data: ApplyDiscountParams = {
            companyId: id,
            serviceId: sid,
            discountId: discountId,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        applyDiscount(data)
            .then(() => {
                alert.showSuccess("Descuento aplicado al servicio");
                cargarDatos();
                setDialogDiscountVisible(false);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const deleteDiscountHandler = () => {
        if (!SessionInfo.userId) {
            return;
        }

        const data: DeleteDiscountParams = {
            companyId: id,
            serviceId: sid,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        deleteDiscount(data)
            .then(() => {
                alert.showSuccess("Descuento aplicado al servicio");
                cargarDatos();
                setDialogDiscountVisible(false);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    useEffect(() => {
        if (!SessionInfo.userId) {
            return;
        }

        if (!sid || sid === "new") {
            return;
        }

        if (!savePublishedStatusAvailable) {
            return;
        }
        savePublishedStatusHandler();
    }, [servicePublished]);

    return (
        <>
            <Location />
            <div
                style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                }}
            >
                <p style={{ marginTop: "10px" }}>
                    Desde aquí puedes configurar los datos de un servicio específico.
                </p>
                <div
                    style={{
                        marginTop: "10px",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                    }}
                >
                    <Switch
                        checked={servicePublished === SERVICE_PUBLISHED_STATUS.PUBLISHED}
                        onChange={(checked) => {
                            setSavePublishedStatusAvailable(true);
                            setServicePublished(
                                checked
                                    ? SERVICE_PUBLISHED_STATUS.PUBLISHED
                                    : SERVICE_PUBLISHED_STATUS.PRIVATE
                            );
                        }}
                    />
                    <span
                        style={
                            servicePublished === SERVICE_PUBLISHED_STATUS.PUBLISHED
                                ? { color: "var(--green-darkestX2)" }
                                : { color: "var(--error)" }
                        }
                    >
                        {getPublishedStatusText()}
                    </span>
                </div>
            </div>

            <Textbox
                name="serviceName"
                placeholder="Nombre del servicio"
                type="text"
                value={serviceName}
                width="100%"
                limitSize={32}
                onChange={(e) => {
                    setServiceName(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <Textbox
                name="serviceDescription"
                placeholder="Descripción del servicio"
                type="text"
                value={serviceDescription}
                width="100%"
                limitSize={84}
                onChange={(e) => {
                    setServiceDescription(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <Textbox
                name="servicePrice"
                placeholder="Precio del servicio"
                type="number"
                value={serviceOriginalPrice}
                width="100%"
                onChange={(e) => {
                    setServiceOriginalPrice(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            {serviceDiscountValue && serviceDiscountValue > 0 ? (
                <div
                    style={{
                        marginTop: "10px",
                        color: "var(--green-darkestX2)",
                        fontWeight: "bold",
                    }}
                >
                    {formatDiscount(serviceDiscountValue, serviceDiscountType, serviceDiscountName)}
                    &nbsp;-
                    <Link
                        href={""}
                        onClick={() => {
                            confirm.show(
                                "¿Está seguro que desea quitar el descuento para este servicio?",
                                () => {
                                    deleteDiscountHandler();
                                },
                                () => {}
                            );
                        }}
                    >
                        {" "}
                        Quitar descuento
                    </Link>
                </div>
            ) : (
                <></>
            )}

            <Grid2 container>
                <Grid2>
                    <PopoverPicker
                        placeholder="Fondo"
                        color={serviceColor}
                        onChange={(color: string) => {
                            setServiceColor(color);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
                <Grid2 sx={{ width: "40px" }}></Grid2>
                <Grid2>
                    <PopoverPicker
                        placeholder="Fuente"
                        color={serviceFontColor}
                        onChange={(color: string) => {
                            setServiceFontColor(color);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
                <Grid2 sx={{ width: "40px" }}></Grid2>
                <Grid2>
                    <PopoverPicker
                        placeholder="Sombra"
                        color={serviceFontShadowColor}
                        onChange={(color: string) => {
                            setServiceFontShadowColor(color);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
            </Grid2>

            {sid === "new" && (
                <MaterialAlert severity="info" sx={{ marginTop: "20px", marginBottom: "20px" }}>
                    <b>Imagen:</b> Es la imagen representativa de un servicio. Para poder elegirla
                    primero debe estar creado el servicio.
                </MaterialAlert>
            )}

            <div
                style={{
                    marginTop: "20px",
                    color: "var(--black)",
                    fontWeight: "bold",
                    paddingTop: "5px",
                    paddingBottom: "10px",
                }}
            >
                Imagen
            </div>

            <ImagePicker
                src={serviceImage}
                alt="Logo"
                style={{ width: "378px", height: "378px" }}
                readOnly={sid === "new"}
                onChange={handleServiceImageChange}
                mbLimit={5}
                imageSizeSrc="/service-image-size.webp"
            />

            <MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
                <b>Duración del servicio:</b> Este parámetro (en minutos) indica la duración del
                turno para este servicio. Por ejemplo, si la duración es 15, el turno durará 15
                minutos; si es 30, durará 30 minutos, etc.
            </MaterialAlert>
            <Textbox
                name="serviceLength"
                placeholder="Duración del servicio"
                type="number"
                value={serviceLength}
                width="100%"
                onChange={(e) => {
                    setServiceLength(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
                <b>Limite del servicio:</b> Este parámetro indica cuántos clientes pueden recibir el
                servicio simultáneamente. Si los turnos son personalizados, pon 1. Si son grupales,
                por ejemplo, 4 permitirá que 4 clientes reserven al mismo tiempo.
            </MaterialAlert>
            <Textbox
                name="serviceLimit"
                placeholder="Limite del servicio"
                type="number"
                value={serviceLimit}
                width="100%"
                onChange={(e) => {
                    setServiceLimit(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            <DialogWindow visible={dialogDiscountVisible} setVisible={setDialogDiscountVisible}>
                <>
                    <DialogContent
                        style={{
                            maxWidth: "500px",
                            minWidth: "300px",
                            margin: "auto",
                        }}
                    >
                        <>
                            <TextObjectFilter
                                placeholder="Descuento"
                                content={discountsFilterContent}
                                data={discountsFilterData}
                                onChange={(id) => {
                                    setDiscountId(id);
                                }}
                            />
                        </>
                    </DialogContent>
                    <DialogActions>
                        <ButtonMaterial
                            variant="contained"
                            color="primary"
                            onClick={createDiscountHandler}
                        >
                            Aplicar Descuento
                        </ButtonMaterial>
                        <ButtonMaterial
                            variant="contained"
                            color="secondary"
                            onClick={() => {
                                setDialogDiscountVisible(false);
                            }}
                        >
                            Cancelar
                        </ButtonMaterial>
                    </DialogActions>
                </>
            </DialogWindow>

            <div style={{ marginBottom: "10px" }}>&nbsp;</div>
        </>
    );
}
