import React, { FC } from "react";
import { Group, Text } from "@mantine/core";
import StatusMenu from "@/app/deals/components/shared/StatusMenu/StatusMenu";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { useDealsContext } from "@/app/deals/contexts/DealsContext";
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;
};

const StatusColumnHeader: FC<Props> = ({ status, isDragging }) => {
    const { statusesCrud, refetchStatuses } = useStatusesContext();
    const { selectedBoard } = useBoardsContext();
    const { groupDealsSelection } = useDealsContext();

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

    return (
        <Group
            justify={"space-between"}
            p={"sm"}
            wrap={"nowrap"}
            mb={"xs"}
            style={{
                borderBottom: `solid ${status.color} 3px`,
            }}>
            <InPlaceInput
                value={status.name}
                onChange={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
                            board={selectedBoard}
                            status={status}
                            handleEdit={startEditing}
                            onStatusColorChange={color =>
                                statusesCrud.onUpdate(status.id, { color })
                            }
                            refetchStatuses={refetchStatuses}
                            onDeleteStatus={statusesCrud.onDelete}
                            startDealsSelecting={
                                groupDealsSelection.startSelecting
                            }
                        />
                    </>
                )}
                modalTitle={"Редактирование статуса"}
            />
        </Group>
    );
};

export default StatusColumnHeader;
