import React, { FC } from "react";
import { Stack, Text, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import Footer from "@/app/deals/drawers/DealEditorDrawer/tabs/GeneralTab/Footer";
import BoardSelect from "@/components/selects/BoardSelect/BoardSelect";
import StatusSelect from "@/components/selects/StatusSelect/StatusSelect";
import { DealsCrud } from "@/hooks/cruds/useDealsCrud";
import { DealSchema, ProjectSchema } from "@/lib/client";
import { utcDateTimeToLocalString } from "@/utils/datetime";

type Props = {
    project: ProjectSchema;
    dealsCrud: DealsCrud;
    deal: DealSchema;
    setDeal: React.Dispatch<React.SetStateAction<DealSchema>>;
    onClose: () => void;
};

const GeneralTab: FC<Props> = ({
    project,
    deal,
    setDeal,
    dealsCrud,
    onClose,
}) => {
    const form = useForm<Partial<DealSchema>>({
        initialValues: deal,
        validate: {
            name: value => !value && "Введите название",
            board: value => !value && "Выберите доску",
            status: value => !value && "Выберите статус",
        },
    });

    const onSubmit = (values: Partial<DealSchema>) => {
        dealsCrud.onUpdate(deal.id, {
            ...values,
            boardId: values.board?.id,
            statusId: values.status?.id,
        });
        setDeal(prev => ({
            ...prev,
            ...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>
                <BoardSelect
                    label={"Доска"}
                    {...form.getInputProps("board")}
                    onChange={board => {
                        form.setFieldValue("board", board ?? undefined);
                        form.setFieldValue("status", undefined);
                    }}
                    projectId={project?.id}
                />
                <StatusSelect
                    label={"Статус"}
                    {...form.getInputProps("status")}
                    boardId={form.values.board?.id}
                />
                <Footer
                    form={form}
                    initialValues={deal}
                    onDelete={onDelete}
                />
            </Stack>
        </form>
    );
};

export default GeneralTab;
