import React, { useEffect, useReducer, useState } from 'react'; import { Accordion, AccordionDetails, AccordionSummary, Alert, Button, ChevronDownIcon, DatePicker, Drawer, Grid, IconButton, SaveIcon, Select, TextField, Typography, XmarkIcon } from '@noahspan/noahspan-components'; import { useForm, Controller, FormProvider } from 'react-hook-form'; import { ILogbookEntryFormProps } from './ILogbookEntryFormProps'; import { initialState, reducer } from './reducer'; import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios'; import { useHttpClient } from '../../hooks/httpClient/UseHttpClient'; import { useAccessToken } from '../../hooks/accessToken/UseAcessToken'; import { useIsAuthenticated } from '@azure/msal-react'; import { FormMode } from '../../enums/formMode'; import { usePilots } from '../../hooks/pilots/UsePilots'; const LogbookEntryForm: React.FC = ({ entryId, isDrawerOpen, mode, onOpenClose }) => { const [state, dispatch] = useReducer(reducer, initialState); const httpClient: AxiosInstance = useHttpClient(); const { getAccessToken } = useAccessToken(); const isAuthenticated = useIsAuthenticated(); const defaultValues = { partitionKey: '', rowKey: '', pilotId: '', pilotName: '', date: null, aircraftMakeModel: '', aircraftIdentity: '', routeFrom: '', routeTo: '', durationOfFlight: null, singleEngineLand: null, simulatorAtd: null, landingsDay: null, landingsNight: null, groundTrainingReceived: null, flightTrainingReceived: null, crossCountry: null, night: null, solo: null, pilotInCommand: null, instrumentActual: null, instrumentSimulated: null, instrumentApproaches: null, instrumentHolds: null, instrumentNavTrack: null, notes: '' }; const methods = useForm(); const { pilots } = usePilots(); const onCancel = () => { methods.reset(defaultValues); dispatch({ type: 'SET_IS_DISABLED', payload: false }); onOpenClose(FormMode.CANCEL); }; const onSubmit = async (data: unknown) => { try { dispatch({ type: 'SET_IS_LOADING', payload: true }); const accessToken: string = await getAccessToken(); if (!entryId) { await httpClient.post(`api/logbook`, data, { headers: { Authorization: accessToken } }); } else { await httpClient.put(`api/logbook/${entryId}`, data, { headers: { Authorization: accessToken } }); } methods.reset(defaultValues); dispatch({ type: 'SET_IS_DISABLED', payload: false }); onOpenClose(FormMode.CANCEL); } catch (error) { const axiosError = error as AxiosError; dispatch({ type: 'SET_ERROR', payload: axiosError.message }); } finally { dispatch({ type: 'SET_IS_LOADING', payload: false }); } }; useEffect(() => { if (mode === FormMode.VIEW) { dispatch({ type: 'SET_IS_DISABLED', payload: true }); } }, [mode]); useEffect(() => { const getEntry = async () => { try { dispatch({ type: 'SET_IS_LOADING', payload: true }); const config = isAuthenticated ? { headers: { Authorization: await getAccessToken() } } : {}; const response: AxiosResponse = await httpClient.get( `api/logbook/${entryId}`, config ); const entry = response.data; methods.reset(entry); } catch (error) { const axiosError = error as AxiosError; dispatch({ type: 'SET_ERROR', payload: axiosError.message }); } finally { dispatch({ type: 'SET_IS_LOADING', payload: false }); } }; if (entryId && isDrawerOpen) { getEntry(); } }, [entryId]); useEffect(() => { if (pilots) { const newPilotsOptions = pilots.map((pilot) => { return { label: pilot.name, value: pilot.id }; }); dispatch({ type: 'SET_PILOT_OPTIONS', payload: newPilotsOptions }); } }, [pilots]); return (
{`${mode.toString().toLowerCase().charAt(0).toUpperCase() + mode.toString().slice(1).toLowerCase()} Pilot`} {state.error && ( dispatch({ type: 'SET_ERROR', payload: undefined }) } severity="error" sx={{ width: '100%' }} > {state.error} )} Pilot * { useEffect(() => { if (value && mode !== FormMode.ADD) { const pilot = pilots?.find((pilot) => pilot.id === value); dispatch({ type: 'SET_SELECTED_ENTRY_PILOT_NAME', payload: pilot.name }); } }, [value]); return ( <> {mode === FormMode.ADD && (