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/detections/detectionsSlice'
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 EditDetections = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    event: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    model: null,
    

    
    
    

    

    

    

    

    
    detected_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    detection_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    
    'confidence': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'risk_score': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'title': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    evidence: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    requires_response: false,
    

    

    

    

    

    

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

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

  const { detectionsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit detections')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit detections'} 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='TelemetryEvent' labelFor='event'>
        <Field
            name='event'
            id='event'
            component={SelectField}
            options={initialValues.event}
            itemRef={'telemetry_events'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'summary'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="DetectionType" labelFor="detection_type">
        <Field name="detection_type" id="detection_type" component="select">
          
            <option value="anomaly">anomaly</option>
          
            <option value="malware">malware</option>
          
            <option value="phishing">phishing</option>
          
            <option value="ransomware">ransomware</option>
          
            <option value="lateral_movement">lateral_movement</option>
          
            <option value="data_exfiltration">data_exfiltration</option>
          
            <option value="policy_violation">policy_violation</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="new">new</option>
          
            <option value="triaged">triaged</option>
          
            <option value="confirmed">confirmed</option>
          
            <option value="false_positive">false_positive</option>
          
            <option value="suppressed">suppressed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Confidence"
    >
        <Field
            type="number"
            name="confidence"
            placeholder="Confidence"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RiskScore"
    >
        <Field
            type="number"
            name="risk_score"
            placeholder="RiskScore"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



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

  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Evidence" hasTextareaHeight>
        <Field name="evidence" as="textarea" placeholder="Evidence" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='RequiresResponse' labelFor='requires_response'>
        <Field
            name='requires_response'
            id='requires_response'
            component={SwitchField}
        ></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('/detections/detections-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditDetections
