import { useMemo } from "react";
import { MRT_ColumnDef, MRT_Row } from "mantine-react-table";
import { WorkShiftRowSchema } from "../../../../../client";


type Props = {
    isActiveShiftsTable: boolean;
}

export const useShiftsTableColumns = ({ isActiveShiftsTable }: Props) => {
    const getWorkedHoursString = (seconds: number) => {
        const hours = Math.floor(seconds / 3_600);
        const minutes = Math.floor(seconds % 3_600 / 60);
        if (hours === 0) {
            return `${minutes} мин.`;
        }
        return `${hours} ч. ${minutes} мин.`;
    };

    const getColumnsForHistory = () => {
        return isActiveShiftsTable ? [] : [
            {
                header: "Конец смены",
                accessorKey: "workShift.finishedAt",
                Cell: ({ row }: { row: MRT_Row<WorkShiftRowSchema> }) =>
                    row.original.workShift.finishedAt && new Date(row.original.workShift.finishedAt).toLocaleString("ru-RU"),
            },
            {
                header: "Длительность смены",
                accessorKey: "totalHours",
                Cell: ({ row }: { row: MRT_Row<WorkShiftRowSchema> }) =>
                    getWorkedHoursString(row.original.totalHours ?? 0),
            },
            {
                header: "Перерывы",
                accessorKey: "pauseHours",
                Cell: ({ row }: { row: MRT_Row<WorkShiftRowSchema> }) =>
                    getWorkedHoursString(row.original.pauseHours ?? 0),
            },
            {
                header: "Отработано",
                Cell: ({ row }: { row: MRT_Row<WorkShiftRowSchema> }) =>
                    getWorkedHoursString((row.original.totalHours ?? 0) - (row.original.pauseHours ?? 0)),
            },
        ] as MRT_ColumnDef<WorkShiftRowSchema>[];
    };

    return useMemo<MRT_ColumnDef<WorkShiftRowSchema>[]>(
        () => [
            {
                header: "ФИО",
                Cell: ({ row }: { row: MRT_Row<WorkShiftRowSchema> }) =>
                    `${row.original.workShift.user.firstName} ${row.original.workShift.user.secondName}`,
            },
            {
                header: "Роль",
                accessorKey: "workShift.user.role.name",
            },
            {
                header: "Должность",
                accessorKey: "workShift.user.position.name",
            },
            {
                header: "Начало смены",
                accessorKey: "workShift.startedAt",
                Cell: ({ row }) =>
                    new Date(row.original.workShift.startedAt).toLocaleString("ru-RU"),
            },
            ...getColumnsForHistory(),
        ],
        [isActiveShiftsTable],
    );
};
