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 { Button, IconButton, Stack } from '@mui/material';
import fetchProduct from 'src/api/fetchProduct';
import fetchCategory from 'src/api/fetchCategory';
import fetchProducts from 'src/api/fetchProducts';
import fetchCategories from 'src/api/fetchCategories';
import Loading from 'src/components/Loading';

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

  const handleViewClick = cid => {
    router.push(`/admin/products/${cid}/view`);
  };

  const handleEditClick = pid => {
    router.push(`/admin/products/${pid}/edit`);
  };

  const handleDeleteClick = async pid => {
    const test_delete = async () => {
      try {
        await axios.delete(`/api/products/delete?pid=${pid}`);
        let fetch_products = await fetchProducts();
        setProducts(fetch_products);
      } catch (error) {
        console.log(error);
      }
    };
    await test_delete();
  };

  useEffect(() => {
    const update = async () => {
      let fetch_products = await fetchProducts();
      let fetch_categories = await fetchCategories();
      setProducts(fetch_products);
      setCategories(fetch_categories);
    };

    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">Price</TableCell>
            <TableCell align="left">Category</TableCell>
            <TableCell align="left">Description</TableCell>
            <TableCell align="right">Action</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {products.map(p => {
            let category = categories.filter(c => c.cid == p.cid)[0];

            return (
              <TableRow
                key={p.name}
                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">{p.name}</TableCell>
                <TableCell align="left">{p.price}</TableCell>
                <TableCell align="left">{category?.name || 'not found'}</TableCell>
                <TableCell align="left">{p.description}</TableCell>
                <TableCell align="left">
                  <Button size="small" variant="outlined" onClick={_ => handleViewClick(p.pid)}>
                    View
                  </Button>
                  <Button size="small" variant="outlined" onClick={_ => handleEditClick(p.pid)}>
                    Edit
                  </Button>
                  <Button size="small" variant="outlined" onClick={_ => handleDeleteClick(p.pid)}>
                    Del
                  </Button>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default TableProducts;
