// ** 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 ShortTextIcon from '@mui/icons-material/ShortText';
import NotesIcon from '@mui/icons-material/Notes';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';

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';
import AddCircleOutline from '@mui/icons-material/AddCircleOutline';
import Loading from 'src/components/Loading';

const axios = require('axios');

const FormEditProducts = ({ product }) => {
  let router = useRouter();
  let initialValues = { ...product, clear_image: false };
  let [categories, setCategories] = useState(null);
  let [product_image_src, setProductImageSrc] = useState(null);
  let [local_preview, setLocalPreview] = useState(false);
  let [local_preview_content, setLocalPrevieContent] = 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('clear_image', values['clear_image']);
    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">
              {values.product_image == '' ? (
                <>
                  <Button
                    style={{ width: '100px', height: '100px', border: '5px dashed gray', borderRadius: '10px' }}
                    onClick={() => {
                      document.querySelector('#product_image').click();
                      setLocalPreview(true);
                    }}
                  >
                    <Box
                      style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                      }}
                    >
                      <AddCircleOutline style={{ fontSize: '2rem', color: 'gray' }} />
                    </Box>
                  </Button>
                </>
              ) : (
                <>
                  <Box>
                    <div
                      style={{
                        width: '100px',
                        height: '100px',
                        backgroundSize: 'contain',
                        backgroundPosition: 'center',
                        backgroundRepeat: 'no-repeat',
                        backgroundImage: local_preview
                          ? local_preview_content
                          : `url('/api/files/get?dir_prefix=${values.product_image}')`,
                      }}
                    ></div>
                  </Box>
                  <Button
                    variant="contained"
                    onClick={() => {
                      setFieldValue('product_image', ['']);
                      setFieldValue('clear_image', true);
                      document.querySelector('#product_image').value = null;
                    }}
                  >
                    Clear picture
                  </Button>

                  <input
                    type="text"
                    id="clear_image"
                    name="clear_image"
                    value={values['clear_image']}
                    style={{ display: 'none' }}
                  />
                </>
              )}

              <input
                type="file"
                accept="image/jpeg, image/png"
                id="product_image"
                name="product_image"
                multiple
                onChange={event => {
                  let input_files = event.target.files;
                  let different_files_list = [];
                  setFieldValue('product_image', [...input_files]);

                  const reader = new FileReader();
                  reader.onload = () => {
                    setLocalPrevieContent(`url(${reader.result})`);
                  };
                  reader.readAsDataURL(input_files[0]);
                }}
                style={{ display: 'none' }}
              />

              <Grid container spacing={5} style={{ marginTop: '2rem' }}>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="Name"
                    placeholder="e.g. French Baguette"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <ShortTextIcon />
                        </InputAdornment>
                      ),
                    }}
                    type="text"
                    name="name"
                    onChange={handleChange}
                    onBlur={handleBlur}
                    value={values.name}
                  />
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label=" Price"
                    placeholder="e.g. 1.1,2,3 ..."
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <AttachMoneyIcon />
                        </InputAdornment>
                      ),
                    }}
                    type="number"
                    id="price"
                    name="price"
                    onChange={handleChange}
                    onBlur={handleBlur}
                    value={values.price}
                  />
                  change price icon here
                </Grid>

                <Grid item xs={12}>
                  <FormControl fullWidth>
                    <InputLabel>Category</InputLabel>
                    <Select
                      name="cid"
                      id="cid"
                      label="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="Description"
                    placeholder="Description of product ... "
                    sx={{ '& .MuiOutlinedInput-root': { alignItems: 'baseline' } }}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <NotesIcon />
                        </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="/admin/products">
                      <Button variant="outlined" size="large">
                        Cancel
                      </Button>
                    </Link>
                  </Stack>
                </Grid>
              </Grid>
            </form>
          )}
        </Formik>
      </CardContent>
    </Card>
  );
};

export default FormEditProducts;
