import { FC, useState } from "react";
import { isEqual } from "lodash";
import { Button, Group, Stack, Text, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { DealsCrud } from "@/hooks/cruds/useDealsCrud";
import { DealSchema } from "@/lib/client";
import { utcDateTimeToLocalString } from "@/utils/datetime";

type Props = {
    dealsCrud: DealsCrud;
    deal: DealSchema;
    onClose: () => void;
};

const GeneralTab: FC<Props> = ({ deal, dealsCrud, onClose }) => {
    const [initialValues, setInitialValues] = useState(deal);
    const form = useForm<DealSchema>({
        initialValues,
        validate: {
            name: value => !value && "Введите название",
        },
    });

    const onSubmit = (values: DealSchema) => {
        dealsCrud.onUpdate(deal.id, values);
        setInitialValues(values);
    };

    const onDelete = () => {
        dealsCrud.onDelete(deal, onClose);
    };

    return (
        <form onSubmit={form.onSubmit(onSubmit)}>
            <Stack p={"md"}>
                <TextInput
                    label={"Название"}
                    {...form.getInputProps("name")}
                />
                <Text>Создано: {utcDateTimeToLocalString(deal.createdAt)}</Text>
                <Group
                    justify={"space-between"}
                    wrap={"nowrap"}>
                    <Group wrap={"nowrap"}>
                        <Button
                            type={"submit"}
                            disabled={isEqual(form.values, initialValues)}
                            variant={"filled"}>
                            Сохранить
                        </Button>
                        <Button
                            type={"reset"}
                            onClick={() => form.reset()}
                            disabled={isEqual(form.values, initialValues)}
                            variant={"default"}>
                            Отменить
                        </Button>
                    </Group>
                    <Button
                        onClick={onDelete}
                        color={"red"}
                        variant={"outline"}>
                        Удалить
                    </Button>
                </Group>
            </Stack>
        </form>
    );
};

export default GeneralTab;
