import {Button, Group, TextInput, Text, Textarea, NumberInput, Container, Title, Flex} from '@mantine/core';
import {useForm} from '@mantine/form';
import {useParams} from "react-router";
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
import {InventoryItem} from "./types.ts";
import {useEffect} from "react";

type EditableInventoryItem = Omit<InventoryItem, 'id'>;

function EditItem() {
    const params = useParams();

    const editItemForm = useForm<EditableInventoryItem>({
        mode: 'uncontrolled',
        initialValues: {
            name: "",
            brand: "",
            statusId: "",
            status: {name: "", id: ""},
            serialNumber: "",
            rentalPrice: 0,
            replacementCost: 0,
            notes: "",
        },

        validate: {},
    });

    const {isPending, error, data, isFetching} = useQuery({
        queryKey: ['inventory', params.itemId],
        queryFn: async (): Promise<InventoryItem> => {
            const response = await fetch(
                import.meta.env.VITE_API_URL + '/inventory/' + params.itemId,
            )

            if (!response.ok) throw new Error('Failed to fetch inventory ' + response.statusText)

            return await response.json()
        },
    });

    const queryClient = useQueryClient();

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

            // await <call the api, do the things>
            const result = await fetch(import.meta.env.VITE_API_URL + '/inventory/' + params.itemId, {
                method: 'PUT',
                body: JSON.stringify(values),
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!result.ok) {
                throw new Error('Failed to update inventory item');
            }

            // invalidate the queries so they pull updated information
            // this is a prefix, so it covers both the query that pulls a list, and also `['inventory', itemId]` in this file
            await queryClient.invalidateQueries({
                queryKey: ['inventory']
            });
        }
    })

    useEffect(() => {
        if (data) {
            // Even if query.data changes, form will be initialized only once
            editItemForm.initialize(data);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    if (isPending) return 'Loading...'

    if (error) return 'An error has occurred: ' + error.message

    return (
        <form onSubmit={editItemForm.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">

                    <div>{isFetching ? 'Updating...' : ''}</div>
                    <Title order={1}>Edit Item</Title>
                    <Text>ID: {data.id}</Text>
                    <TextInput withAsterisk key={editItemForm.key('brand')} size="md" label="Brand"
                               placeholder="Brand" {...editItemForm.getInputProps('brand')}/>
                    <TextInput withAsterisk key={editItemForm.key('name')} size="md" label="Name"
                               placeholder="Name" {...editItemForm.getInputProps('name')}/>
                    <TextInput size="md" key={editItemForm.key('statusId')} label="Status"
                               placeholder="Status" {...editItemForm.getInputProps('statusId')}/>
                    <TextInput size="md" key={editItemForm.key('serialNumber')} label="Serial Number"
                               placeholder="Serial Number"{...editItemForm.getInputProps('serialNumber')}/>
                    <NumberInput size="md" key={editItemForm.key('rentalPrice')} label="Rental Price"
                                 placeholder="Rental Price" {...editItemForm.getInputProps('rentalPrice')}/>
                    <NumberInput size="md" key={editItemForm.key('replacementCost')} label="Replacement Cost"
                                 placeholder="Replacement Cost" {...editItemForm.getInputProps('replacementCost')}/>
                    <Textarea label="Notes" key={editItemForm.key('notes')}
                              placeholder="Notes" {...editItemForm.getInputProps('notes')}/>

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

export default EditItem;