import { useDepartmentContext } from "../../contexts/DepartmentContext.tsx";
import { DataTable } from "mantine-datatable";
import { IconBuildings, IconChevronRight } from "@tabler/icons-react";
import classes from "./DepartmentsTree.module.css";
import clsx from "clsx";
import { useEffect, useState } from "react";
import "mantine-datatable/styles.css";
import DepartmentActions from "../DepartmentActions.tsx";
import DepartmentSectionsTable from "../DepartmentSectionsTable.tsx";

const DepartmentsTree = () => {
    const { departments } = useDepartmentContext();

    const [departmentIds, setDepartmentIds] = useState<number[]>([]);
    let isInitialSetting = true;

    useEffect(() => {
        if (isInitialSetting && departments) {
            isInitialSetting = false;
            setDepartmentIds(departments.map(department => department.id));
        }
    }, [departments]);

    return (
        <DataTable
            noHeader
            withTableBorder
            columns={[
                {
                    accessor: "name",
                    title: "Департамент",
                    noWrap: true,
                    render: ({ id, name }) => (
                        <>
                            <IconChevronRight
                                className={clsx(classes.icon, classes.expandIcon, {
                                    [classes.expandIconRotated]: departmentIds?.includes(id),
                                })}
                            />
                            <IconBuildings className={classes.icon} />
                            <span>{name}</span>
                        </>
                    ),
                },
                {
                    accessor: "actions",
                    title: "",
                    width: "0%",
                    render: (department) => (
                        <DepartmentActions element={department} isSection={false} />
                    ),
                },
            ]}
            records={departments.sort((a, b) => a.id - b.id)}
            rowExpansion={{
                allowMultiple: true,
                expanded: { recordIds: departmentIds, onRecordIdsChange: setDepartmentIds },
                content: ({ record }) => (
                    <DepartmentSectionsTable parentItem={record} level={1} />
                ),
            }}
        />
    );
};

export default DepartmentsTree;
