import React, { ReactNode } from "react";
import { Box, Group, Text } from "@mantine/core";
import StatusMenu from "@/app/deals/components/StatusColumnWrapper/StatusMenu";
import { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import InPlaceInput from "@/components/ui/InPlaceInput/InPlaceInput";
import { StatusSchema } from "@/lib/client";

type Props = {
    status: StatusSchema;
    isDragging?: boolean;
    children: ReactNode;
};

const StatusColumnWrapper = ({
    status,
    children,
    isDragging = false,
}: Props) => {
    const { onUpdateStatus } = useStatusesContext();

    const handleSave = (value: string) => {
        const newValue = value.trim();
        if (newValue && newValue !== status.name) {
            onUpdateStatus(status.id, { name: newValue });
        }
    };

    return (
        <Box
            p={"xs"}
            style={{
                borderWidth: 1,
                borderColor: "gray",
                width: "15vw",
                minWidth: 150,
            }}>
            <Group
                wrap={"nowrap"}
                justify={"space-between"}
                ml={"xs"}
                mb={"xs"}>
                <InPlaceInput
                    defaultValue={status.name}
                    onComplete={value => handleSave(value)}
                    inputStyles={{
                        input: {
                            height: 25,
                            minHeight: 25,
                        },
                    }}
                    getChildren={startEditing => (
                        <>
                            <Text
                                style={{
                                    cursor: "grab",
                                    userSelect: "none",
                                    opacity: isDragging ? 0.5 : 1,
                                }}>
                                {status.name}
                            </Text>
                            <StatusMenu
                                status={status}
                                handleEdit={startEditing}
                            />
                        </>
                    )}
                    modalTitle={"Редактирование статуса"}
                />
            </Group>
            {children}
        </Box>
    );
};

export default StatusColumnWrapper;
