import { ProductSchema } from "../client";
import { isNil } from "lodash";
import { ProductFieldNames } from "../pages/LeadsPage/tabs/ProductAndServiceTab/components/ProductView/ProductView.tsx";
import UseObjectState from "./UseObjectState.ts";
import { CRUDTableProps } from "./CRUDTable.tsx";
import { MRT_RowData } from "mantine-react-table";

export type ObjectWithNameAndId = {
    id: number;
    name: string;
};

export type BaseFormInputProps<T> = {
    onChange: (value: T) => void;
    value: T;
    error?: string | null;
};
export const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString("ru-RU");
};

export const getProductFields = (product: ProductSchema) => {
    return (
        Object.entries(product)
            .map(([key, value]) => {
                const fieldName = ProductFieldNames[key as keyof ProductSchema];
                if (!fieldName || isNil(value) || value === "" || !value)
                    return;
                return [fieldName.toString(), value.toString()];
            })
            .filter(obj => obj !== undefined) || []
    );
};

export function ObjectStateToTableProps<T extends MRT_RowData>(
    state: UseObjectState<T>
): CRUDTableProps<T> {
    return {
        items: state.objects,
        onDelete: state.onDelete,
        onChange: state.onChange,
        onCreate: state.onCreate,
    };
}

export const floatHoursToHoursAndMinutes = (hours: number): number[] => {
    const resHours = Math.floor(hours);
    const minutes = Math.floor((hours - resHours) * 60);
    return [resHours, minutes];
};

export const strTimeToFloatHours = (time: string): number => {
    const values = time.split(":");
    if (values.length !== 2) return -1;
    const hours = parseInt(values[0]);
    const minutes = parseInt(values[1]);

    return hours + minutes / 60;
}

export const dateToString = (date: Date | null) => {
    if (date === null) return null;
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const monthStr = month < 10 ? `0${month}` : month;
    const dayStr = day < 10 ? `0${day}` : day;
    return `${date.getFullYear()}-${monthStr}-${dayStr}`;
};