"use client";
import { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import DataGrid, { DataGridColumn, DataGridRow } from "@components/DataGrid/DataGrid";

import { useSessionStore } from "@store/Sesion.Store";
import { formatPrice } from "@core/app/helpers/Numbers";
import {
    DiscountEmailView,
    PaginateDiscountsEmailParams,
    PaginateDiscountsEmailViewResults,
} from "@core/Models/DiscountsEmail.model";
import { formatDiscountType } from "../discounts/Discounts.Service";
import { DiscountType, FindDiscountsParams } from "@core/Models/Discounts.model";
import { deleteDiscountEmail, findDiscountsEmailByOrganization } from "./DiscountsEmail.Service";
import { ThemeProvider } from "@emotion/react";
import turnosXpressTheme from "@core/app/theme/turnosXpress";
import { ButtonGroup } from "@mui/material";
import ButtonMaterial from "@mui/material/Button";
import { useNavigation } from "@core/app/hooks/goto";
import dayjs from "dayjs";
import IconButton from "@mui/material/IconButton";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import { useAlert } from "@core/Store/Alert.Store";
import Textbox from "@components/Textbox/Textbox";
import Filterable from "@core/app/components/Filterable/Filterable";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import TextObjectFilterItem from "@core/app/components/TextObjectFilterItem/TextObjectFilterItem";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";
import { useFilterStore } from "@core/Store/Filter.Store";
import filterObjects from "@components/TextObjectFilter/Filter.Service";

type UrlData = {
    id: string;
};

//----------------->

interface FilterContentProps {
    discountData: TextObjectFilterResult[];
    setDiscountId: (id: string) => void;
    filterEmail: string;
    setFilterEmail: (email: string) => void;
}

const FilterContent = (props: FilterContentProps) => {
    const [auxEmailFilter, setAuxEmailFilter] = useState<string>("");
    const [discountFilterContent] = 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 código del descuento para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

    return (
        <>
            <Textbox
                placeholder="Email"
                type="text"
                value={auxEmailFilter || ""}
                width="100%"
                onChange={(e) => {
                    props.setFilterEmail(e.target.value);
                    setAuxEmailFilter(e.target.value);
                }}
            />
            <TextObjectFilter
                placeholder="Descuento"
                content={discountFilterContent}
                data={props.discountData}
                onChange={(id) => {
                    props.setDiscountId(id);
                }}
            />
        </>
    );
};

//-----------------<

export type DiscountEmailRow = DataGridRow & DiscountEmailView;

export default function DiscountsEmailGrid() {
    const data = useParams<UrlData>();
    const oid = data.id;
    const location = useLocationStore();
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const alert = useAlert();
    const confirm = useConfirmStore();
    const filter = useFilterStore();
    const [searchByFilters, setSearchByFilters] = useState<boolean>(false);

    const [filterEmail, setFilterEmail] = useState<string>("");

    //--------->

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

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

    //---------<

    const { goTo } = useNavigation();
    const { userId } = useSessionStore();
    const [dataGridColumns] = useState<DataGridColumn<DiscountEmailRow>[]>([
        {
            field: "email",
            title: "Email",
            width: null,
            render: (value: DiscountEmailRow) => (
                <div style={{ paddingBottom: "10px" }}>
                    <div>
                        <div style={{ paddingLeft: "10px", paddingTop: "10px", fontWeight: "bold" }}>
                            {value.discountName + " (" + value.discountCode + ")"}
                        </div>
                        <div style={{ paddingLeft: "10px", paddingTop: "0px", fontWeight: "bold" }}>
                            {value.email}
                        </div>
                        <div
                            style={{
                                paddingLeft: "10px",
                                paddingTop: "0px",
                                fontWeight: "normal",
                                color: "var(--wine-darkest)",
                            }}
                        >
                            {dayjs(value.startDate).format("DD/MM/YYYY")} -{" "}
                            {dayjs(value.endDate).format("DD/MM/YYYY")}
                        </div>
                        <div style={{ paddingLeft: "10px", color: "var(--gray-dark)" }}>
                            {formatDiscountType(value.discountType)}
                            <span
                                style={{
                                    paddingLeft: "10px",
                                    color: "var(--green-darkestX2)",
                                }}
                            >
                                {value.discountType === DiscountType.FIXED
                                    ? formatPrice(value.discountValue)
                                    : value.discountValue + "%"}
                            </span>
                        </div>
                    </div>
                </div>
            ),
        },
        {
            field: "actions",
            title: "",
            width: 50,
            render: (value: DiscountEmailRow) => (
                <div
                    style={{
                        paddingBottom: "10px",
                        height: "100%",
                    }}
                >
                    <IconButton onClick={() => handleDelete(value)}>
                        <DeleteIcon sx={{ mr: "15px" }} />
                    </IconButton>
                </div>
            ),
        },
    ]);

    const [pageSize] = useState<number>(
        parseInt(
            process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE ? process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE : "10"
        )
    );
    const [discounts, setDiscounts] = useState<PaginateDiscountsEmailViewResults>();
    const discountsRef = useRef(discounts);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
    }, []);

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

        location.add({
            url: "/admin/org",
            title: "Mis organizaciones",
            icon: null,
        });

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

        location.add({
            url: "",
            title: "Descuentos por email",
            icon: <DiscountsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        loadDiscountsEmail(1, pageSize);
    }, []);

    useEffect(() => {
        discountsRef.current = discounts;
    }, [discounts]);

    useEffect(() => {
        if (!searchByFilters) {
            return;
        }

        let loadPage = 1;

        if (discountsRef.current) {
            loadPage = discountsRef.current.page;
        }
        loadDiscountsEmail(loadPage, pageSize);
    }, [discountId, filterEmail, searchByFilters]);

    useEffect(() => {
        filter.clear();
        filter.setTitle("Filtrar Descuentos");
        filter.clearFilterData();
        filter.setContent(
            <FilterContent
                discountData={discountFilterData}
                setDiscountId={setDiscountId}
                filterEmail={filterEmail}
                setFilterEmail={setFilterEmail}
            />
        );
        filter.setOnFilter(() => {
            setSearchByFilters(true);
        });

        return () => {
            filter.clear();
        };
    }, [discountFilterData]);

    const loadDiscountsEmail = (page: number = 1, pageSize: number = 30) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        const filterData: PaginateDiscountsEmailParams = {
            companyId: oid,
            page: page,
            limit: pageSize,
            sessionUser: userId,
        };

        if (discountId) {
            filterData.discountId = discountId;
        }

        if (filterEmail !== "") {
            filterData.email = filterEmail;
        }

        findDiscountsEmailByOrganization(filterData)
            .then((res) => {
                setDiscounts(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
                setSearchByFilters(false);
            });
    };

    const handleDelete = (discount: DiscountEmailRow) => {
        if (!discount.id) {
            return;
        }

        confirm.show(
            `¿Estás seguro de eliminar el descuento ${discount.discountName} para ${discount.email}?`,
            () => {
                deleteDiscountEmail({
                    id: discount.id,
                    companyId: oid,
                    sessionUser: SessionInfo.userId,
                })
                    .then(() => {
                        alert.showSuccess("Descuento eliminado correctamente");
                        loadDiscountsEmail();
                    })
                    .catch((err) => {
                        alert.showError(err.format());
                    });
            },
            () => {}
        );
    };

    return (
        <>
            <Location />
            <Filterable />

            <div style={{ display: "flex", justifyContent: "center", marginTop: "15px" }}>
                <ThemeProvider theme={turnosXpressTheme}>
                    <ButtonGroup variant="outlined" aria-label="Basic button group">
                        <ButtonMaterial
                            variant="outlined"
                            onClick={() => {
                                goTo(`/admin/org/profile/${oid}/discounts`);
                            }}
                        >
                            Descuentos
                        </ButtonMaterial>
                        <ButtonMaterial variant="contained">Asignados</ButtonMaterial>
                    </ButtonGroup>
                </ThemeProvider>
            </div>

            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    marginTop: "60px",
                    position: "absolute",
                    left: "0px",
                    right: "0px",
                    top: "60px",
                    bottom: "10px",
                }}
            >
                <DataGrid
                    columns={dataGridColumns}
                    data={discounts ? discounts.data : []}
                    pagination={true}
                    page={discounts?.page}
                    pages={discounts?.pages}
                    pageSize={pageSize}
                    handleRefresh={loadDiscountsEmail}
                />
            </div>
        </>
    );
}
