// ** MUI Imports
import Card from '@mui/material/Card';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import CardHeader from '@mui/material/CardHeader';
import CardContent from '@mui/material/CardContent';
import InputAdornment from '@mui/material/InputAdornment';

// ** Icons Imports
import Phone from 'mdi-material-ui/Phone';
import EmailOutline from 'mdi-material-ui/EmailOutline';
import AccountOutline from 'mdi-material-ui/AccountOutline';
import MessageOutline from 'mdi-material-ui/MessageOutline';
import { Box, FormControl, InputLabel, Link, MenuItem, Select, Stack } from '@mui/material';
import { Formik } from 'formik';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

const axios = require('axios');

const FormEditProducts = ({ product }) => {
  let router = useRouter();
  let initialValues = product;
  let [categories, setCategories] = useState(null);
  let [product_image_src, setProductImageSrc] = useState(null);

  let validate = values => {
    const errors = {};
    // if (!values.email) {
    //   errors.email = 'Required';
    // } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
    //   errors.email = 'Invalid email address';
    // }
    return errors;
  };

  const fetchCategory = () => {
    axios
      .get('/api/categories/list')
      .then(function (response) {
        let { data } = response;
        let { categories } = data;
        setCategories(categories);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .finally(function () {
        // always executed
      });
  };

  let onSubmit = async (values, { setSubmitting }) => {
    values['cid'] = parseInt(values['cid']);
    const formData = new FormData();

    formData.append('name', values['name']);
    formData.append('description', values['description']);
    formData.append('cid', values['cid']);
    formData.append('pid', values['pid']);
    formData.append('price', values['price']);
    formData.append('product_image', values['product_image'][0]);

    await fetch('/api/products/update', { method: 'POST', body: formData })
      .then(response => {
        router.replace('/admin/products');
      })
      .catch(error => {
        console.error(error);
      });
  };

  useEffect(() => {
    fetchCategory();
    //
  }, []);

  if (!categories) return <>loading</>;

  return (
    <Card>
      <CardHeader title="Edit Products" titleTypographyProps={{ variant: 'h6' }} />
      <CardContent>
        <Formik initialValues={initialValues} validate={validate} onSubmit={onSubmit}>
          {({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, setFieldValue }) => (
            <form onSubmit={handleSubmit} encType="multipart/form-data">
              <input
                type="file"
                id="product_image"
                name="product_image"
                multiple
                onChange={event => {
                  let input_files = event.target.files;
                  let different_files_list = [];
                  setFieldValue('product_image', [...input_files]);
                  setFieldValue('clear_image', false);
                }}
              />

              <Box>Current picture</Box>
              <div
                style={{
                  width: '100px',
                  height: '100px',
                  backgroundImage: `url('/api/files/get?dir_prefix=${values.product_image}')`,
                }}
              ></div>

              <div
                style={{
                  width: '100px',
                  height: '100px',
                  backgroundImage: `url('${product_image_src}')`,
                }}
              ></div>

              <Box>Preview picture</Box>
              <div
                id="previewImage"
                style={{
                  width: '100px',
                  height: '100px',
                  backgroundImage: ``,
                }}
              ></div>
              <Button variant="contained">Clear picture</Button>

              <input type="file" id="myImage" accept="image/jpeg, image/png" />
              <button
                type="button"
                onClick={() => {
                  const input = document.getElementById('myImage');
                  if (input.files && input.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                      document.getElementById('previewImage').src = e.target.result;
                    };
                    reader.readAsDataURL(input.files[0]);
                  }
                }}
              >
                Preview Image
              </button>

              <Grid container spacing={5}>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="Product Name"
                    placeholder="food ?"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <AccountOutline />
                        </InputAdornment>
                      ),
                    }}
                    type="text"
                    name="name"
                    onChange={handleChange}
                    onBlur={handleBlur}
                    value={values.name}
                  />
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="Product Price"
                    placeholder="food ?"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <AccountOutline />
                        </InputAdornment>
                      ),
                    }}
                    type="text"
                    id="price"
                    name="price"
                    onChange={handleChange}
                    onBlur={handleBlur}
                    value={values.price}
                  />
                  change price icon here
                </Grid>

                <Grid item xs={12}>
                  <FormControl fullWidth>
                    <InputLabel>Product Category</InputLabel>
                    <Select
                      name="cid"
                      id="cid"
                      label="Product Category"
                      defaultValue={values.cid}
                      onChange={handleChange}
                      onBlur={handleBlur}
                      value={values.cid}
                    >
                      {categories.map(c => (
                        <MenuItem value={c.cid}>{c.name}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    multiline
                    minRows={10}
                    label="Product detail"
                    placeholder="Product detail insert here"
                    sx={{ '& .MuiOutlinedInput-root': { alignItems: 'baseline' } }}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <MessageOutline />
                        </InputAdornment>
                      ),
                    }}
                    type="text"
                    name="description"
                    onChange={handleChange}
                    onBlur={handleBlur}
                    value={values.description}
                  />
                </Grid>
                <Grid item xs={12}>
                  <Stack direction="row" gap="1rem">
                    <Button type="submit" variant="contained" size="large">
                      Save
                    </Button>

                    <Link href="/products">
                      <Button variant="outlined" size="large">
                        Cancel
                      </Button>
                    </Link>
                  </Stack>
                </Grid>
              </Grid>
            </form>
          )}
        </Formik>
      </CardContent>
    </Card>
  );
};

export default FormEditProducts;
