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/data_sources/data_sourcesSlice'
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 EditData_sourcesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    
    'name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    source_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    
    'connector_type': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'endpoint_url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'auth_method': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    poll_interval_seconds: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    last_ingested_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

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

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

  const { id } = router.query

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

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

  useEffect(() => {
      if (typeof data_sources === 'object') {
          const newInitialVal = {...initVals};
          Object.keys(initVals).forEach(el => newInitialVal[el] = (data_sources)[el])
          setInitialValues(newInitialVal);
      }
  }, [data_sources])

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

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


  

  

  

  

  

  

  

  

  

  
    {hasPermission(currentUser, 'READ_ORGANIZATIONS') && 
    <FormField label='Organization' labelFor='organization'>
        <Field
            name='organization'
            id='organization'
            component={SelectField}
            options={initialValues.organization}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
     } 

  

  

    

  



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

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="SourceType" labelFor="source_type">
        <Field name="source_type" id="source_type" component="select">
          
            <option value="siem">siem</option>
          
            <option value="edr">edr</option>
          
            <option value="ids_ips">ids_ips</option>
          
            <option value="firewall">firewall</option>
          
            <option value="proxy">proxy</option>
          
            <option value="dns">dns</option>
          
            <option value="cloud_logs">cloud_logs</option>
          
            <option value="kubernetes_audit">kubernetes_audit</option>
          
            <option value="endpoint">endpoint</option>
          
            <option value="threat_feed">threat_feed</option>
          
            <option value="dark_web">dark_web</option>
          
            <option value="vulnerability_scanner">vulnerability_scanner</option>
          
            <option value="email_gateway">email_gateway</option>
          
            <option value="web_gateway">web_gateway</option>
          
            <option value="custom_api">custom_api</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="active">active</option>
          
            <option value="paused">paused</option>
          
            <option value="error">error</option>
          
            <option value="onboarding">onboarding</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="ConnectorType"
    >
        <Field
            name="connector_type"
            placeholder="ConnectorType"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="EndpointURL"
    >
        <Field
            name="endpoint_url"
            placeholder="EndpointURL"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="AuthMethod"
    >
        <Field
            name="auth_method"
            placeholder="AuthMethod"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PollIntervalSeconds"
    >
        <Field
            type="number"
            name="poll_interval_seconds"
            placeholder="PollIntervalSeconds"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

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

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

export default EditData_sourcesPage
