import categories, { NO_CATEGORY } from "@core/Models/Categories.type";
import TextObjectFilter from "../../TextObjectFilter/TextObjectFilter";
import { useEffect, useState } from "react";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import TextObjectFilterItem from "../../TextObjectFilterItem/TextObjectFilterItem";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { useHeaderStore } from "@core/Store/Header.Store";
import TextFromTo from "../../TextFromTo/TextFromTo";
import Button from "../../Button/Button";
import { PaginateServicesParams } from "@core/Models/Service.model";
import classNames from "classnames";
import style from "./style.module.css";
import { IconButton } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

export type FindFilterServiceParams = Omit<PaginateServicesParams, "page" | "limit">;

export interface FindFilterProps {
    visible: boolean;
    onFilter: () => void;
    setFilterCompany: (companyId: string) => void;
    setFilterCategory: (categoryId: string) => void;
    setFilterLocation: (locationId: string) => void;
    setFilterPriceFrom: (price: number | null) => void;
    setFilterPriceTo: (price: number | null) => void;
    setFilterDurationFrom: (duration: number | null) => void;
    setFilterDurationTo: (duration: number | null) => void;
}

export default function Filters(props: FindFilterProps) {
    const headerState = useHeaderStore();

    const [priceFrom, setPriceFrom] = useState<string>("");
    const [priceTo, setPriceTo] = useState<string>("");
    const [duracionFrom, setDuracionFrom] = useState<string>("");
    const [duracionTo, setDuracionTo] = useState<string>("");
    const [visible, setVisible] = useState<boolean>(props.visible);

    const [categoryFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Categoría:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre de la categoría para buscarla.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

    const [categoryFilterData, setCategoryFilterData] = useState<TextObjectFilterResult[]>([]);
    const [categoryId, setCategoryId] = useState<string>("");

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

    //const [locationId, setLocationId] = useState<string>("");

    const [organizationFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Organización:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre de la organización para buscarla.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

    //const [organizationId, setOrganizationId] = useState<string>("");

    const loadCategories = () => {
        setCategoryFilterData(
            categories.map((category) => ({
                id: category.id.toString(),
                name: category.name,
                description: category.description,
            }))
        );
    };

    useEffect(() => {
        loadCategories();
        if (headerState.publicFindCategoryId !== NO_CATEGORY) {
            setCategoryId(headerState.publicFindCategoryId.toString());
            props.setFilterCategory(headerState.publicFindCategoryId.toString());
        }
    }, [categoryId]);

    useEffect(() => {
        if (headerState.publicFindCategoryId == NO_CATEGORY) {
            setCategoryId("");
            props.setFilterCategory("");
        }
    }, [headerState.publicFindCategoryId]);

    useEffect(() => {
        //la primera vez que carga emite la señal de busqueda para hacer el primer filtro
        headerState.setPublicFindTrigger(true);
    }, []);

    useEffect(() => {
        setVisible(props.visible);
    }, [props.visible]);

    const getContainerClasses = () => {
        const items: classNames.ArgumentArray = [];

        items.push("card-base");
        items.push(style.filterContainer);

        if (visible) {
            items.push(style.filterContainerVisible);
        } else {
            items.push(style.filterContainerHidden);
        }

        return classNames(items);
    };

    return (
        <div className={getContainerClasses()}>
            <div style={{ paddingLeft: "5px" }}>
                <div
                    style={{
                        display: "flex",
                        flexDirection: "row",
                        justifyContent: "space-between",
                        alignItems: "center",
                    }}
                >
                    <h4>Filtros</h4>
                    {headerState.publicFindText && (
                        <div
                            style={{
                                backgroundColor: "var(--wine-dark)",
                                borderRadius: "5px",
                                padding: "5px",
                                marginTop: "5px",
                                display: "inline-block",
                                color: "var(--white)",
                            }}
                        >
                            {headerState.publicFindText}
                        </div>
                    )}
                    <IconButton
                        style={{ display: "none" }}
                        onClick={() => {
                            setVisible(false);
                        }}
                    >
                        <CloseIcon />
                    </IconButton>
                </div>
            </div>
            <TextObjectFilter
                placeholder="Organización"
                content={organizationFilterContent}
                endpoint="companies/filter-all"
                onChange={(id) => {
                    //setOrganizationId(id);
                    props.setFilterCompany(id);
                }}
            />

            <TextObjectFilter
                placeholder="Categoría"
                content={categoryFilterContent}
                data={categoryFilterData}
                selectedId={categoryId}
                onChange={(id) => {
                    //setCategoryId(id);
                    headerState.setPublicFindCategoryId(NO_CATEGORY);
                    props.setFilterCategory(id);
                }}
            />

            <TextObjectFilter
                placeholder="Localidad"
                content={locationFilterContent}
                endpoint="location/localidades-filter-paginate"
                onChange={(id) => {
                    //setLocationId(id);
                    props.setFilterLocation(id);
                }}
            />

            <TextFromTo
                label="Precio ($)"
                width="100%"
                from={priceFrom}
                to={priceTo}
                onChangeFrom={(e) => {
                    setPriceFrom(e.target.value);
                    props.setFilterPriceFrom(parseFloat(e.target.value));
                }}
                onChangeTo={(e) => {
                    setPriceTo(e.target.value);
                    props.setFilterPriceTo(parseFloat(e.target.value));
                }}
            />

            <TextFromTo
                label="Duración (min)"
                width="100%"
                from={duracionFrom}
                to={duracionTo}
                onChangeFrom={(e) => {
                    setDuracionFrom(e.target.value);
                    props.setFilterDurationFrom(parseInt(e.target.value));
                }}
                onChangeTo={(e) => {
                    setDuracionTo(e.target.value);
                    props.setFilterDurationTo(parseInt(e.target.value));
                }}
            />

            <Button
                text="Filtrar"
                width="100%"
                onClick={() => {
                    headerState.setPublicFindTrigger(true);
                    props.onFilter();
                }}
                style={{ marginTop: "20px" }}
            />
        </div>
    );
}
