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/artifacts/artifactsSlice'
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 EditArtifactsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    workflow: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    evidence_model: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    source_system: null,
    

    
    
    
    'artifact_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    artifact_type: '',
    

    

    

    

    
    
    

    
    artifact_reference: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    collected_by_user: null,
    

    
    
    

    

    

    

    

    
    collected_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    event_timestamp: new Date(),
    

    

    

    

    

    

    

    
    
    
    'subject_user': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    approver_user: null,
    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    
    validation_notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'evidence_strength_score': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'chain_integrity_score': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    retention_expiry: new Date(),
    

    

    

    

    

    

    

    
    
    
    'tags': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    uploaded_files: [],
    

    

    

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

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

  const { id } = router.query

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit artifacts')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit artifacts'} 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='Workflow' labelFor='workflow'>
        <Field
            name='workflow'
            id='workflow'
            component={SelectField}
            options={initialValues.workflow}
            itemRef={'identity_workflows'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'workflow_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  
    <FormField
        label="ArtifactName"
    >
        <Field
            name="artifact_name"
            placeholder="ArtifactName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ArtifactType" labelFor="artifact_type">
        <Field name="artifact_type" id="artifact_type" component="select">
          
            <option value="screenshot">screenshot</option>
          
            <option value="export_csv">export_csv</option>
          
            <option value="export_json">export_json</option>
          
            <option value="audit_log">audit_log</option>
          
            <option value="ticket">ticket</option>
          
            <option value="attestation">attestation</option>
          
            <option value="configuration">configuration</option>
          
            <option value="policy_document">policy_document</option>
          
            <option value="api_snapshot">api_snapshot</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="ArtifactReference" hasTextareaHeight>
        <Field name="artifact_reference" as="textarea" placeholder="ArtifactReference" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="SubjectUser"
    >
        <Field
            name="subject_user"
            placeholder="SubjectUser"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="pending">pending</option>
          
            <option value="collected">collected</option>
          
            <option value="validated">validated</option>
          
            <option value="rejected">rejected</option>
          
            <option value="expired">expired</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="ValidationNotes" hasTextareaHeight>
        <Field name="validation_notes" as="textarea" placeholder="ValidationNotes" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EvidenceStrengthScore"
    >
        <Field
            type="number"
            name="evidence_strength_score"
            placeholder="EvidenceStrengthScore"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="ChainIntegrityScore"
    >
        <Field
            type="number"
            name="chain_integrity_score"
            placeholder="ChainIntegrityScore"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="Tags"
    >
        <Field
            name="tags"
            placeholder="Tags"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='UploadedFiles'
            color='info'
            icon={mdiUpload}
            path={'artifacts/uploaded_files'}
            name='uploaded_files'
            id='uploaded_files'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></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('/artifacts/artifacts-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditArtifactsPage
