"use client";

import { useMemo } from "react";
import { DataTableColumn } from "mantine-datatable";
import { Center, List, Text } from "@mantine/core";
import { useServicesContext } from "@/app/services/contexts/ServicesContext";
import useServicesActions from "@/app/services/hooks/useServicesActions";
import UpdateDeleteTableActions from "@/components/ui/BaseTable/components/UpdateDeleteTableActions";
import useIsMobile from "@/hooks/utils/useIsMobile";
import { ServiceSchema } from "@/lib/client";

const useServicesInnerTableColumns = () => {
    const { onChangeService } = useServicesActions();
    const { servicesCrud } = useServicesContext();
    const isMobile = useIsMobile();

    const getPriceRow = (service: ServiceSchema) => {
        if (service.priceRanges.length === 0) {
            return <>{service.price.toLocaleString("ru")}₽</>;
        }
        return (
            <List>
                {service.priceRanges.map(range => (
                    <List.Item key={range.id}>
                        <Text>
                            {`${range.fromQuantity} - ${range.toQuantity}: ${range.price.toLocaleString("ru")}₽`}
                        </Text>
                    </List.Item>
                ))}
            </List>
        );
    };

    return useMemo(
        () =>
            [
                { accessor: "", hiddenContent: true, width: 2 },
                {
                    accessor: "name",
                    title: "Название",
                    width: isMobile ? 70 : 350,
                },
                {
                    accessor: "price",
                    title: "Цена",
                    render: service => getPriceRow(service),
                    width: isMobile ? 40 : 200,
                },
                {
                    accessor: "cost",
                    title: isMobile ? "Себестоим." : "Себестоимость",
                    render: service => `${service.cost?.toLocaleString("ru")}₽`,
                    width: isMobile ? 40 : 200,
                },
                {
                    accessor: "actions",
                    title: isMobile ? "" : "Действия",
                    sortable: false,
                    textAlign: "center",
                    width: "0%",
                    render: service => (
                        <Center>
                            <UpdateDeleteTableActions
                                onDelete={() => servicesCrud.onDelete(service)}
                                onChange={() => onChangeService(service)}
                                dotsForMobile
                            />
                        </Center>
                    ),
                },
            ] as DataTableColumn<ServiceSchema>[],
        [isMobile]
    );
};

export default useServicesInnerTableColumns;
