import axios from 'axios';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';

// ** MUI Imports
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableRow from '@mui/material/TableRow';
import TableHead from '@mui/material/TableHead';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import { Box, Button, InputAdornment, Stack, TextField, Typography } from '@mui/material';

import Inventory2Icon from '@mui/icons-material/Inventory2';
import AddCircleOutline from '@mui/icons-material/AddCircleOutline';
import fetchProduct from 'src/api/fetchProduct';
import fetchProducts from 'src/api/fetchProducts';
import fetchCategories from 'src/api/fetchCategories';
import Loading from 'src/components/Loading';

const TableInventory = () => {
  const router = useRouter();
  const [products, setProducts] = useState(null);
  const [categories, setCategories] = useState(null);

  const categoriNameLookup = cid => {
    if (categories && cid) {
      let result = categories.filter(c => c.cid == cid)[0];
      if (result) {
        return result.name;
      } else {
        return '--';
      }
    }
  };

  const handleInventoryAddClick = async ({ pid, count }) => {
    try {
      let response = await axios.post('/api/inventory/check_in', { pid, count, description: '' });
      let { data } = await response;
      alert('item added');

      let result = await fetchProducts();
      setProducts(result);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    const update = async () => {
      let result;
      result = await fetchProducts();
      setProducts(result);

      result = await fetchCategories();
      setCategories(result);
    };

    update();
  }, []);

  if (!products || !categories)
    return (
      <>
        <Loading />
      </>
    );

  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>id</TableCell>
            <TableCell align="left">Image</TableCell>
            <TableCell align="left">Name</TableCell>
            <TableCell align="left">Category</TableCell>
            <TableCell align="left">unsold</TableCell>
            <TableCell align="left">sold</TableCell>
            <TableCell align="left">Inventory Add</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {products.map((p, idx) => {
            let category = categories.filter(c => c.cid == p.cid)[0];

            return (
              <TableRow
                key={idx}
                sx={{
                  '&:last-of-type td, &:last-of-type th': {
                    border: 0,
                  },
                }}
              >
                <TableCell component="th" scope="row">
                  {p.pid}
                </TableCell>

                <TableCell align="left">
                  <div
                    style={{
                      backgroundImage: `url('/api/files/get?dir_prefix=${p.product_image}')`,
                      backgroundColor: `lightgrey`,
                      backgroundSize: 'cover',
                      backgroundPosition: 'center',
                      backgroundRepeat: 'no-repeat',
                      height: '100px',
                      width: '100px',
                      borderRadius: '5px',
                    }}
                  />
                </TableCell>

                <TableCell align="left">
                  <Typography variant="paragraph" fontWeight={'bold'}>
                    {p.name}
                  </Typography>
                </TableCell>
                <TableCell align="left">
                  <Typography variant="paragraph">{categoriNameLookup(p.cid)}</Typography>
                </TableCell>
                <TableCell align="left">{p.unsold_count}</TableCell>
                <TableCell align="left">{p.sold_count}</TableCell>
                <TableCell align="left">
                  <Stack direction="row" spacing="1rem">
                    <TextField
                      variant="standard"
                      placeholder={1}
                      defaultValue={1}
                      InputProps={{
                        min: 1,
                        max: 50,
                        startAdornment: (
                          <InputAdornment position="start">
                            <Inventory2Icon />
                          </InputAdornment>
                        ),
                      }}
                      type="number"
                      id={`pid_${p.pid}`}
                      sx={{ width: '100px' }}
                      onBlur={e => {
                        try {
                          if (e.target.value < 1) {
                            e.target.value = 1;
                          }
                        } catch (error) {
                          e.target.value = 1;
                        }
                      }}
                    />

                    <Button
                      size="small"
                      variant="outlined"
                      onClick={_ => {
                        try {
                          let count_raw = document.querySelector(`#pid_${p.pid}`).value;
                          let count = parseInt(count_raw);

                          if (count > 0) {
                            handleInventoryAddClick({ pid: p.pid, count });
                            document.querySelector(`#pid_${p.pid}`).value = 1;
                          } else {
                            alert('please check count');
                          }
                        } catch (error) {
                          console.error(error);
                        }
                      }}
                    >
                      <Stack direction="row" spacing={'0.2rem'}>
                        <AddCircleOutline />
                        <Box>Add</Box>
                      </Stack>
                    </Button>
                  </Stack>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default TableInventory;
