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 { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import InPlaceInput from "@/components/ui/InPlaceInput/InPlaceInput";
import { StatusSchema } from "@/lib/client";
import styles from "./StatusColumnHeader.module.css";

type Props = {
    status: StatusSchema;
    isDragging: boolean;
};

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

    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"}
            className={styles.header}>
            <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}
                            refetchStatuses={refetchStatuses}
                            onDeleteStatus={statusesCrud.onDelete}
                        />
                    </>
                )}
                modalTitle={"Редактирование статуса"}
            />
        </Group>
    );
};

export default StatusColumnHeader;
