"use client";
import { useState, useEffect } 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 { findDiscountsByOrganization, formatDiscountType } from "./Discounts.Service";
import {
    IDiscount,
    PaginateDiscountsResults,
    PaginateDiscountsParams,
    DiscountType,
} from "@models/Discounts.model";

import { useSessionStore } from "@store/Sesion.Store";
import { formatPrice } from "@core/app/helpers/Numbers";
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";

type UrlData = {
    id: string;
};

export type DiscountRow = DataGridRow & IDiscount;

export default function DiscountsGrid() {
    const data = useParams<UrlData>();
    const oid = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();

    const { goTo } = useNavigation();
    const { userId } = useSessionStore();
    const [dataGridColumns] = useState<DataGridColumn<DiscountRow>[]>([
        {
            field: "name",
            title: "Nombre",
            width: null,
            render: (value: DiscountRow) => (
                <div>
                    <div style={{ paddingLeft: "10px", paddingTop: "10px", fontWeight: "bold" }}>
                        {value.name + " (" + value.code + ")"}
                    </div>
                    <div style={{ paddingLeft: "10px", color: "var(--gray-dark)" }}>
                        {formatDiscountType(value.type)}
                    </div>
                </div>
            ),
        },
        {
            field: "value",
            title: "Valor",
            width: 150,
            render: (value: DiscountRow) => (
                <div>
                    <div
                        style={{
                            paddingTop: "10px",
                            textAlign: "right",
                            paddingRight: "10px",
                            color: "var(--green-darkestX2)",
                        }}
                    >
                        {value.type === DiscountType.FIXED ? formatPrice(value.value) : value.value + "%"}
                    </div>
                </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<PaginateDiscountsResults>();

    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",
            icon: <DiscountsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

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

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

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

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

    const handleDiscountClick = (discount: DiscountRow) => {
        // goTo("/admin/org/" + oid + "/discount/" + discount.id + "/profile");
        console.log("Discount clicked:", discount);
    };

    return (
        <>
            <Location />
            <div style={{ display: "flex", justifyContent: "center", marginTop: "15px" }}>
                <ThemeProvider theme={turnosXpressTheme}>
                    <ButtonGroup variant="outlined" aria-label="Basic button group">
                        <ButtonMaterial variant="contained">Descuentos</ButtonMaterial>
                        <ButtonMaterial
                            variant="outlined"
                            onClick={() => {
                                goTo(`/admin/org/profile/${oid}/discounts-email`);
                            }}
                        >
                            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={loadDiscounts}
                    handleRowClick={handleDiscountClick}
                />
            </div>
        </>
    );
}
