import { TextObjectFilterResult } from "@models/TextObjectFilter.model";
import style from "../TextObjectFilter/TextObjectFilter.module.css";
import CloseIcon from "@mui/icons-material/Close";
import { HEADER_WIDGETS, useHeaderStore } from "@store/Header.Store";
import { TextObjectModalContent, useTextObjectModalStore } from "@store/TextObjectModal.Store";
import { useEffect, useState } from "react";
import { IconButton, Chip } from "@mui/material";

export interface TextObjectMultiFilterProps {
    placeholder: string;
    content: TextObjectModalContent;
    data?: TextObjectFilterResult[];
    endpoint?: string;
    selectedIds?: string[];
    onChange?: (ids: string[]) => void;
}

export default function TextObjectMultiFilter(props: TextObjectMultiFilterProps): React.ReactElement {
    const { placeholder, content, selectedIds = [] } = props;
    const header = useHeaderStore();
    const modal = useTextObjectModalStore();
    const [itemsSelected, setItemsSelected] = useState<TextObjectFilterResult[]>([]);
    const [data, setData] = useState<TextObjectFilterResult[] | undefined>(props.data);
    const [endpoint, setEndpoint] = useState<string | undefined>(props.endpoint);

    useEffect(() => {
        setData(props.data);
    }, [props.data]);

    const selectedIdsKey = (props.selectedIds || []).join(',');

    useEffect(() => {
        const ids = props.selectedIds || [];
        if (ids.length > 0 && data) {
            const selected = data.filter((item) => ids.includes(item.id));
            setItemsSelected(selected);
        } else {
            setItemsSelected(prev => prev.length === 0 ? prev : []);
        }
    }, [selectedIdsKey, data]);

    useEffect(() => {
        setEndpoint(props.endpoint);
    }, [props.endpoint]);

    const handleItemClick = (item: TextObjectFilterResult) => {
        header.setActiveWidget(HEADER_WIDGETS.NONE);
        
        const exists = itemsSelected.find(i => i.id === item.id);
        if (exists) return;
        
        const newSelection = [...itemsSelected, item];
        setItemsSelected(newSelection);
        if (props.onChange) {
            props.onChange(newSelection.map(i => i.id));
        }
    };

    const handleRemove = (e: React.MouseEvent, id: string) => {
        e.stopPropagation(); // prevent opening the modal when clicking remove on a chip
        const newSelection = itemsSelected.filter(i => i.id !== id);
        setItemsSelected(newSelection);
        if (props.onChange) {
            props.onChange(newSelection.map(i => i.id));
        }
    };

    return (
        <>
            <div>
                <div className={style.textObjectFilterLabel}>{placeholder}</div>
            </div>
            <div 
                className={style.textObjectFilter}
                style={{ height: "auto", minHeight: "42px", padding: "5px 10px", lineHeight: "normal", flexWrap: "wrap" }}
                onClick={() => {
                    header.setFindText("");
                    modal.setContent(content);
                    if (endpoint) {
                        modal.setEndPoint(endpoint);
                    } else {
                        modal.setEndPoint("");
                    }
                    if (data) {
                        modal.setData(data);
                    } else {
                        modal.setData([]);
                    }
                    modal.setOnSelected(handleItemClick);
                    header.setActiveWidget(HEADER_WIDGETS.FIND);
                }}
            >
                <div className={style.textObjectFilterItemSelected} style={{ flexWrap: "wrap", gap: "5px", width: "100%", justifyContent: "flex-start" }}>
                    {itemsSelected.length > 0 ? (
                        itemsSelected.map(item => (
                            <Chip 
                                key={item.id}
                                label={item.name} 
                                onDelete={(e) => handleRemove(e, item.id)} 
                                size="small"
                                style={{ margin: "2px", fontWeight: "bold" }}
                                clickable={false}
                            />
                        ))
                    ) : (
                        <div style={{ color: "var(--gray-dark)", fontStyle: "italic", lineHeight: "32px", fontSize: "14px" }}>
                            Tocar para añadir...
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}
