"use client"

import React, { useState } from 'react'
import { Container, Paper, Table, Button, TextInput, useMantineTheme, Flex, Image } from '@mantine/core'
import Example from './query'

interface InventoryItem {
  id: number
  name: string
  price: number
  quantity: number
}

async function fetchBlob(url: string) {
  const response = await fetch(url)

  // Here is the significant part 
  // reading the stream as a blob instead of json
  return response.blob()
}

export default function InventoryPage() {
  const theme = useMantineTheme()
  const [items, setItems] = useState<InventoryItem[]>([])
  const [name, setName] = useState('')
  const [price, setPrice] = useState('')
  const [quantity, setQuantity] = useState('')

  const addItem = () => {
    setItems([
      ...items,
      {
        id: items.length + 1,
        name,
        price: parseFloat(price),
        quantity: parseInt(quantity),
      },
    ])
    setName('')
    setPrice('')
    setQuantity('')
  }

  const [imageSourceUrl, setImageSourceUrl] = React.useState("")

  const downloadImageAndSetSource = async (imageUrl: any) => {
    const image = await fetchBlob(imageUrl)
    setImageSourceUrl(URL.createObjectURL(image))
  }

  return (
    <>
      <Container size="md" >
        <Paper >
          <Table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Price</th>
                <th>Quantity</th>
              </tr>
            </thead>
            <tbody>
              {items.map((item) => (
                <tr key={item.id}>
                  <td>{item.id}</td>
                  <td>{item.name}</td>
                  <td>{item.price}</td>
                  <td>{item.quantity}</td>
                </tr>
              ))}
            </tbody>
          </Table>
        </Paper>

        <Flex style={{ marginTop: theme.spacing.md }}>
          <TextInput
            label="Item name"
            placeholder="Enter item name"
            value={name}
            onChange={(event) => setName(event.currentTarget.value)}
          />
          <TextInput
            label="Price"
            placeholder="Enter item price"
            value={price}
            onChange={(event) => setPrice(event.currentTarget.value)}
          />
          <TextInput
            label="Quantity"
            placeholder="Enter item quantity"
            value={quantity}
            onChange={(event) => setQuantity(event.currentTarget.value)}
          />
          <Button onClick={addItem}>Add item</Button>
        </Flex>
      </Container>
      <Flex
        id="GRID OF ITEMS"
        mih={50}
        bg="rgba(0, 0, 0, .3)"
        gap="md"
        justify="flex-start"
        align="flex-start"
        direction="row"
        wrap="wrap"
      >
        {/* would fetch the source from axios */}
        <Image src="x.png" alt="ITEM" />
        <Example />
      </Flex>
    </>
  )
}
