import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import dayjs from "dayjs";

import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'

import { Field, Form, Formik } from 'formik'
import FormField from '../../components/FormField'
import BaseDivider from '../../components/BaseDivider'
import BaseButtons from '../../components/BaseButtons'
import BaseButton from '../../components/BaseButton'
import FormCheckRadio from '../../components/FormCheckRadio'
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
import FormFilePicker from '../../components/FormFilePicker'
import FormImagePicker from '../../components/FormImagePicker'
import { SelectField } from "../../components/SelectField";
import { SelectFieldMany } from "../../components/SelectFieldMany";
import { SwitchField } from '../../components/SwitchField'
import {RichTextField} from "../../components/RichTextField";

import { update, fetch } from '../../stores/marketplace_listings/marketplace_listingsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import {saveFile} from "../../helpers/fileSaver";
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from "../../components/ImageField";

import {hasPermission} from "../../helpers/userPermissions";



const EditMarketplace_listings = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    seller_tenant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    harvest: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    species: null,
    

    
    
    
    'listing_title': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    product_form: '',
    

    

    

    

    
    
    
    'available_quantity_kg': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'price_per_kg': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'currency': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    available_from: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    expires_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    listing_status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    photos: [],
    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    fulfillment_location: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

    
    
    
  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { marketplace_listings } = useAppSelector((state) => state.marketplace_listings)
  
  const { currentUser } = useAppSelector((state) => state.auth);
  

  const { marketplace_listingsId } = router.query

  useEffect(() => {
    dispatch(fetch({ id: marketplace_listingsId }))
  }, [marketplace_listingsId])

  useEffect(() => {
    if (typeof marketplace_listings === 'object') {
      setInitialValues(marketplace_listings)
    }
  }, [marketplace_listings])

  useEffect(() => {
      if (typeof marketplace_listings === 'object') {

          const newInitialVal = {...initVals};

          Object.keys(initVals).forEach(el => newInitialVal[el] = (marketplace_listings)[el])

          setInitialValues(newInitialVal);
      }
  }, [marketplace_listings])

  const handleSubmit = async (data) => {
    await dispatch(update({ id: marketplace_listingsId, data }))
    await router.push('/marketplace_listings/marketplace_listings-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit marketplace_listings')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit marketplace_listings'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='SellerTenant' labelFor='seller_tenant'>
        <Field
            name='seller_tenant'
            id='seller_tenant'
            component={SelectField}
            options={initialValues.seller_tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'tenant_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Harvest' labelFor='harvest'>
        <Field
            name='harvest'
            id='harvest'
            component={SelectField}
            options={initialValues.harvest}
            itemRef={'harvests'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'notes'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Species' labelFor='species'>
        <Field
            name='species'
            id='species'
            component={SelectField}
            options={initialValues.species}
            itemRef={'species'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'species_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="ListingTitle"
    >
        <Field
            name="listing_title"
            placeholder="ListingTitle"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='Description' hasTextareaHeight>
        <Field
            name='description'
            id='description'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ProductForm" labelFor="product_form">
        <Field name="product_form" id="product_form" component="select">
          
            <option value="live">live</option>
          
            <option value="whole">whole</option>
          
            <option value="gutted">gutted</option>
          
            <option value="fillet">fillet</option>
          
            <option value="frozen">frozen</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="AvailableQuantityKg"
    >
        <Field
            type="number"
            name="available_quantity_kg"
            placeholder="AvailableQuantityKg"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PricePerKg"
    >
        <Field
            type="number"
            name="price_per_kg"
            placeholder="PricePerKg"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Currency"
    >
        <Field
            name="currency"
            placeholder="Currency"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="AvailableFrom"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.available_from ?
                  new Date(
                      dayjs(initialValues.available_from).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'available_from': date})}
          />
      </FormField>
  

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="ExpiresAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.expires_at ?
                  new Date(
                      dayjs(initialValues.expires_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'expires_at': date})}
          />
      </FormField>
  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ListingStatus" labelFor="listing_status">
        <Field name="listing_status" id="listing_status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="active">active</option>
          
            <option value="paused">paused</option>
          
            <option value="sold_out">sold_out</option>
          
            <option value="expired">expired</option>
          
            <option value="removed">removed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    
        <FormField>
            <Field
                label='Photos'
                color='info'
                icon={mdiUpload}
                path={'marketplace_listings/photos'}
                name='photos'
                id='photos'
                schema={{
                    size: undefined,
                    formats: undefined,
                }}
                component={FormImagePicker}
            ></Field>
        </FormField>
    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='FulfillmentLocation' labelFor='fulfillment_location'>
        <Field
            name='fulfillment_location'
            id='fulfillment_location'
            component={SelectField}
            options={initialValues.fulfillment_location}
            itemRef={'tenant_locations'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'location_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='organizations' labelFor='organizations'>
        <Field
            name='organizations'
            id='organizations'
            component={SelectField}
            options={initialValues.organizations}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  


  

              <BaseDivider />
              <BaseButtons>
                <BaseButton type="submit" color="info" label="Submit" />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton type='reset' color='danger' outline label='Cancel' onClick={() => router.push('/marketplace_listings/marketplace_listings-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

EditMarketplace_listings.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated
        
          permission={'UPDATE_MARKETPLACE_LISTINGS'}
        
      >
          {page}
      </LayoutAuthenticated>
  )
}

export default EditMarketplace_listings
