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/tenants/tenantsSlice'
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 EditTenants = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'slug': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    plan_tier: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    tenant_status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    activated_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    suspended_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'default_region': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    e2ee_default_enabled: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    education_module_enabled: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    marketplace_enabled: false,
    

    

    

    

    

    

    
    
    

    
    data_retention_policy: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { tenantsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  
    <FormField
        label="TenantName"
    >
        <Field
            name="name"
            placeholder="TenantName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Slug"
    >
        <Field
            name="slug"
            placeholder="Slug"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="PlanTier" labelFor="plan_tier">
        <Field name="plan_tier" id="plan_tier" component="select">
          
            <option value="free">free</option>
          
            <option value="pro">pro</option>
          
            <option value="business">business</option>
          
            <option value="enterprise">enterprise</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="TenantStatus" labelFor="tenant_status">
        <Field name="tenant_status" id="tenant_status" component="select">
          
            <option value="active">active</option>
          
            <option value="trial">trial</option>
          
            <option value="past_due">past_due</option>
          
            <option value="suspended">suspended</option>
          
            <option value="closed">closed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="DefaultRegion"
    >
        <Field
            name="default_region"
            placeholder="DefaultRegion"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='E2EEDefaultEnabled' labelFor='e2ee_default_enabled'>
        <Field
            name='e2ee_default_enabled'
            id='e2ee_default_enabled'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='EducationModuleEnabled' labelFor='education_module_enabled'>
        <Field
            name='education_module_enabled'
            id='education_module_enabled'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='MarketplaceEnabled' labelFor='marketplace_enabled'>
        <Field
            name='marketplace_enabled'
            id='marketplace_enabled'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  
    <FormField label="DataRetentionPolicy" hasTextareaHeight>
        <Field name="data_retention_policy" as="textarea" placeholder="DataRetentionPolicy" />
    </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('/tenants/tenants-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditTenants
