import {Button, Group, TextInput, NumberInput, Container, Title, Flex} from '@mantine/core';
import {useForm} from '@mantine/form';
import {useMutation} from "@tanstack/react-query";
import {NewItem} from "./types.ts";
import { useNavigate} from "react-router";
import { IconX, IconCheck } from '@tabler/icons-react';
import { notifications } from '@mantine/notifications';

function AddItem() {

    const navigate = useNavigate();

    const newItemForm = useForm<NewItem>({
        mode: 'uncontrolled',
        initialValues: {
            name: "",
            brand: "",
            serialNumber: "",
            rentalPrice: 0,
            replacementCost: 0,
        },

        validate: {},
    });

    const updateItem = useMutation({
        mutationFn: async (values: NewItem) => {

            const result = await fetch(import.meta.env.VITE_API_URL + '/inventory', {
                method: 'POST',
                body: JSON.stringify(values),
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (result.ok) {
                notifications.show({
                    icon: <IconCheck size={20} />,
                    color:"teal",
                    title: "All good!",
                    message: "Item Created",
                    position: 'top-center',
                });
                navigate("/inventory");

            }

            if (!result.ok) {
                notifications.show({
                    icon: <IconX size={20} />,
                    color:"red",
                    title: "Bummer!",
                    message: "Something went wrong",
                    position: 'top-center',
                });
                throw new Error('Failed to create inventory item');
            }

        }
    })


    return (
        <>
            <form onSubmit={newItemForm.onSubmit(async (values) => await
                updateItem.mutateAsync(values))}>
                <Container m="lg">
                    <Flex mih={50}
                          gap="md"
                          justify="flex-start"
                          align="flex-start"
                          direction="column"
                          wrap="wrap">

                        <Title order={1}>Add Item</Title>

                        <TextInput withAsterisk key={newItemForm.key('brand')} size="md" label="Brand"
                                   placeholder="Brand" {...newItemForm.getInputProps('brand')}/>
                        <TextInput withAsterisk key={newItemForm.key('name')} size="md" label="Name"
                                   placeholder="Name" {...newItemForm.getInputProps('name')}/>
                        <TextInput size="md" key={newItemForm.key('serialNumber')} label="Serial Number"
                                   placeholder="Serial Number"{...newItemForm.getInputProps('serialNumber')}/>
                        <NumberInput size="md" key={newItemForm.key('rentalPrice')} label="Rental Price"
                                     placeholder="Rental Price" {...newItemForm.getInputProps('rentalPrice')}/>
                        <NumberInput size="md" key={newItemForm.key('replacementCost')} label="Replacement Cost"
                                     placeholder="Replacement Cost" {...newItemForm.getInputProps('replacementCost')}/>

                        <Group justify="flex-end" mt="md">
                            <Button type="submit">Submit</Button>
                        </Group>
                    </Flex>
                </Container>
            </form>
        </>
    );
}

export default AddItem;