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/source_items/source_itemsSlice'
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 EditSource_items = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    project: null,
    

    
    
    

    

    

    

    

    

    

    

    
    source_type: '',
    

    

    

    

    
    
    
    'title': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    attachments: [],
    

    

    

    
    
    

    
    raw_text: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    extracted_summary: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    ingestion_status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    ingested_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'tags': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { source_itemsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="SourceType" labelFor="source_type">
        <Field name="source_type" id="source_type" component="select">
          
            <option value="url">url</option>
          
            <option value="article">article</option>
          
            <option value="pdf">pdf</option>
          
            <option value="doc">doc</option>
          
            <option value="ppt">ppt</option>
          
            <option value="text_note">text_note</option>
          
            <option value="spreadsheet">spreadsheet</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="Title"
    >
        <Field
            name="title"
            placeholder="Title"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="URL"
    >
        <Field
            name="url"
            placeholder="URL"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='Attachments'
            color='info'
            icon={mdiUpload}
            path={'source_items/attachments'}
            name='attachments'
            id='attachments'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></Field>
        </FormField>
  



  

  
    <FormField label="RawText" hasTextareaHeight>
        <Field name="raw_text" as="textarea" placeholder="RawText" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='ExtractedSummary' hasTextareaHeight>
        <Field
            name='extracted_summary'
            id='extracted_summary'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="IngestionStatus" labelFor="ingestion_status">
        <Field name="ingestion_status" id="ingestion_status" component="select">
          
            <option value="queued">queued</option>
          
            <option value="processing">processing</option>
          
            <option value="completed">completed</option>
          
            <option value="failed">failed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="Tags"
    >
        <Field
            name="tags"
            placeholder="Tags"
        />
    </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('/source_items/source_items-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditSource_items
