import { User } from "@/interfaces/user";
import { checkAccess } from "@/utils/permissions";
import Select from "../Low/Select";
import { ReactNode, useEffect, useState } from "react";
import clsx from "clsx";
import useUsers from "@/hooks/useUsers";
import useGroups from "@/hooks/useGroups";
import useRecordStore from "@/stores/recordStore";


type TimeFilter = "months" | "weeks" | "days";
type Filter = TimeFilter | "assignments" | undefined;

interface Props {
    user: User;
    filterState: {
        filter: Filter,
        setFilter: React.Dispatch<React.SetStateAction<Filter>>
    },
    assignments?: boolean;
    children?: ReactNode
}

const defaultSelectableCorporate = {
    value: "",
    label: "All",
};

const RecordFilter: React.FC<Props> = ({
    user,
    filterState,
    assignments = true,
    children
}) => {
    const { filter, setFilter } = filterState;

    const [statsUserId, setStatsUserId] = useRecordStore((state) => [
        state.selectedUser,
        state.setSelectedUser
    ]);

    const { users } = useUsers();
    const { groups: allGroups } = useGroups({});
    const { groups } = useGroups({ admin: user?.id, userType: user?.type });

    const toggleFilter = (value: "months" | "weeks" | "days" | "assignments") => {
        setFilter((prev) => (prev === value ? undefined : value));
    };

    const selectableCorporates = [
        defaultSelectableCorporate,
        ...users
            .filter((x) => groups.flatMap((g) => [g.admin, ...g.participants]).includes(x.id))
            .filter((x) => x.type === "corporate")
            .map((x) => ({
                value: x.id,
                label: `${x.name} - ${x.email}`,
            })),
    ];

    const [selectedCorporate, setSelectedCorporate] = useState<string>(defaultSelectableCorporate.value);

    const getUsersList = (): User[] => {
        if (selectedCorporate) {
            const selectedCorporateGroups = allGroups.filter((x) => x.admin === selectedCorporate);
            const selectedCorporateGroupsParticipants = selectedCorporateGroups.flatMap((x) => x.participants);

            const userListWithUsers = selectedCorporateGroupsParticipants.map((x) => users.find((y) => y.id === x)) as User[];
            return userListWithUsers.filter((x) => x);
        }

        return user.type !== "mastercorporate" ? users : users.filter((x) => groups.flatMap((g) => [g.admin, ...g.participants]).includes(x.id));
    };

    const corporateFilteredUserList = getUsersList();

    const getSelectedUser = () => {
        if (selectedCorporate) {
            const userInCorporate = corporateFilteredUserList.find((x) => x.id === statsUserId);
            return userInCorporate || corporateFilteredUserList[0];
        }

        return users.find((x) => x.id === statsUserId) || user;
    };

    const selectedUser = getSelectedUser();
    const selectedUserSelectValue = selectedUser
        ? {
            value: selectedUser.id,
            label: `${selectedUser.name} - ${selectedUser.email}`,
        }
        : {
            value: "",
            label: "",
        };

    return (
        <div className="w-full flex -xl:flex-col -xl:gap-4 justify-between items-center">
            <div className="xl:w-3/4">
                {checkAccess(user, ["developer", "admin", "mastercorporate"]) && !children && (
                    <>
                        <label className="font-normal text-base text-mti-gray-dim">Corporate</label>

                        <Select
                            options={selectableCorporates}
                            value={selectableCorporates.find((x) => x.value === selectedCorporate)}
                            onChange={(value) => setSelectedCorporate(value?.value || "")}
                            styles={{
                                menuPortal: (base) => ({ ...base, zIndex: 9999 }),
                                option: (styles, state) => ({
                                    ...styles,
                                    backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
                                    color: state.isFocused ? "black" : styles.color,
                                }),
                            }}></Select>
                        <label className="font-normal text-base text-mti-gray-dim">User</label>

                        <Select
                            options={corporateFilteredUserList.map((x) => ({
                                value: x.id,
                                label: `${x.name} - ${x.email}`,
                            }))}
                            value={selectedUserSelectValue}
                            onChange={(value) => setStatsUserId(value?.value!)}
                            styles={{
                                menuPortal: (base) => ({ ...base, zIndex: 9999 }),
                                option: (styles, state) => ({
                                    ...styles,
                                    backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
                                    color: state.isFocused ? "black" : styles.color,
                                }),
                            }}
                        />
                    </>
                )}
                {(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && !children && (
                    <>
                        <label className="font-normal text-base text-mti-gray-dim">User</label>

                        <Select
                            options={users
                                .filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
                                .map((x) => ({
                                    value: x.id,
                                    label: `${x.name} - ${x.email}`,
                                }))}
                            value={selectedUserSelectValue}
                            onChange={(value) => setStatsUserId(value?.value!)}
                            styles={{
                                menuPortal: (base) => ({ ...base, zIndex: 9999 }),
                                option: (styles, state) => ({
                                    ...styles,
                                    backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
                                    color: state.isFocused ? "black" : styles.color,
                                }),
                            }}
                        />
                    </>
                )}
                {children}
            </div>
            <div className="flex gap-4 w-full justify-center xl:justify-end">
                {assignments && (
                    <button
                        className={clsx(
                            "bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
                            "transition duration-300 ease-in-out",
                            filter === "assignments" && "!bg-mti-purple-light !text-white",
                        )}
                        onClick={() => toggleFilter("assignments")}>
                        Assignments
                    </button>
                )}
                <button
                    className={clsx(
                        "bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
                        "transition duration-300 ease-in-out",
                        filter === "months" && "!bg-mti-purple-light !text-white",
                    )}
                    onClick={() => toggleFilter("months")}>
                    Last month
                </button>
                <button
                    className={clsx(
                        "bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
                        "transition duration-300 ease-in-out",
                        filter === "weeks" && "!bg-mti-purple-light !text-white",
                    )}
                    onClick={() => toggleFilter("weeks")}>
                    Last week
                </button>
                <button
                    className={clsx(
                        "bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
                        "transition duration-300 ease-in-out",
                        filter === "days" && "!bg-mti-purple-light !text-white",
                    )}
                    onClick={() => toggleFilter("days")}>
                    Last day
                </button>
            </div>
        </div>
    );
}

export default RecordFilter;