components/SpeedLimitFiller.tsx

src/ui/components/widgets/SpeedLimitSection/components/SpeedLimitFiller.tsx
mail@pastecode.io avatar
unknown
typescript
25 days ago
11 kB
3
Indexable
Never
import { useSearchParams } from '@Hooks'
import { CButton, CLabel, CRow, CSelect } from '@coreui/react'
import { useLocation } from 'react-router-dom'
import { ActionTypes, actionCreatorsProps, speedLimitStates } from '../types'
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
  fetchTSOSpeedLimitsByRouteId,
  fetchZoneSpeedLimitsByRouteId
} from '@Redux/slices/portalDataSlice'
import { useSpeedLimitStore } from '@Contexts'
import { Icons } from '@Assets/icons/Icons'
import CustomDropDown from './DropDown/CustomDropDown'

interface SpeedLimitFillerType {
  route: any[]
  state: speedLimitStates
  actions: actionCreatorsProps
}

const SpeedLimitFiller = ({ route, state, actions }: SpeedLimitFillerType) => {
  const searchParams = useSearchParams<
    'route-id' | 'direction' | 'type' | 'page'
  >()
  const dispatch = useDispatch()
  const location = useLocation()
  const {
    data: { railroadId }
  } = useSelector((state: any) => state.userInfo)

  const {
    zoneSpeedLimitsByRouteId: {
      data: zoneSpeedLimitsData,
      loading: zoneSpeedLimitsLoading,
      error: zoneSpeedLimitsError
    }
  } = useSelector((state: any) => state.portalData)

  const {
    TSOSpeedLimitsByRouteId: {
      data: TSOSpeedLimitsData,
      loading: TSOSpeedLimitsLoading,
      error: TSOSpeedLimitsError
    }
  } = useSelector((state: any) => state.portalData)

  const speedLimitStore = useSpeedLimitStore

  const { actionType, directionList, direction, routeId } = state
  const [isDisable, setIsDisable] = useState<boolean>()
  const speedLimitData = useSpeedLimitStore.use.speedLimits()
  // console.log('🚀 ~ SpeedLimitFiller ~ speedLimitData:', speedLimitData)
  const removeFirstSpeedLimit = useSpeedLimitStore.use.removeFirstSpeedLimit()

  const handleSelectionTypeChange = useCallback(
    (selected: string[]) => {
      const type = selected.join(',')
      if (type !== '') {
        searchParams.setSearchParam({ k: 'type', v: type })
      } else {
        searchParams.delSearchParam('type')
      }
      setTimeout(() => {
        actions.onChangePage('')
        actions.onChangeType(type)
      }, 50)
    },
    [actions, searchParams]
  )

  // const handleBeforeAdd = useCallback(async () => {
  //   const newSpeedLimitData = [{}, ...(speedLimitData ?? [])]
  //   console.log('🚀 ~ handleBeforeAdd ~ newSpeedLimitData:', newSpeedLimitData)
  //   await speedLimitStore.setState({ speedLimits: newSpeedLimitData })
  // }, [speedLimitData])

  useEffect(() => {
    const routeIdParam = searchParams.getSearchParam('route-id')
    const directionParam = searchParams.getSearchParam('direction')
    const endDestinationId = routeIdParam
      ?.split('_')
      .filter(item => item !== directionParam)
    if (routeIdParam) {
      dispatch(
        fetchZoneSpeedLimitsByRouteId({
          routeId: routeIdParam,
          railroadId: railroadId,
          startDestinationId: directionParam,
          endDestinationId: endDestinationId![0]
        })
      )
      dispatch(
        fetchTSOSpeedLimitsByRouteId({
          routeId: routeIdParam,
          railroadId: railroadId,
          startDestinationId: directionParam,
          endDestinationId: endDestinationId![0]
        })
      )
    }
  }, [])

  useEffect(() => {
    const routeIdParam = searchParams.getSearchParam('route-id')
    const directionParam = searchParams.getSearchParam('direction')
    const typeParam = searchParams.getSearchParam('type')

    routeIdParam && actions.onChangeRouteId(routeIdParam)

    directionParam && actions.onChangeDirection(directionParam)

    typeParam && actions.onChangeType(typeParam)
  }, [])

  useEffect(() => {
    state.page !== ''
      ? searchParams.setSearchParam({ k: 'page', v: state.page })
      : searchParams.delSearchParam('page')
  }, [state.page])

  useEffect(() => {
    routeId ? setIsDisable(false) : setIsDisable(true)
  }, [routeId])

  return (
    <CRow className="justify-between mx-0 mb-4 py-8 ">
      <div className="flex w-[70%] flex-wrap gap-8">
        <div className="w-[20%]">
          <CLabel
            key="routeId"
            className="flex justify-center w-full font-semibold"
          >
            Route
          </CLabel>
          <CSelect
            className=" text-center text-align-last-center w-full"
            value={routeId}
            onChange={(e: any) => {
              const v = e.target.value
              const direction = v.split('_')

              if (v !== '') {
                searchParams.setSearchParam({ k: 'route-id', v })
                searchParams.setSearchParam({ k: 'direction', v: direction[0] })
              } else {
                searchParams.delSearchParam('route-id')
                searchParams.delSearchParam('direction')
                speedLimitStore.setState({ speedLimits: [] })
              }

              actions.onChangeRouteId(v)

              if (v !== '') {
                dispatch(
                  fetchZoneSpeedLimitsByRouteId({
                    routeId: v,
                    railroadId: railroadId,
                    startDestinationId: direction[0],
                    endDestinationId: direction[1]
                  })
                )
                dispatch(
                  fetchTSOSpeedLimitsByRouteId({
                    routeId: v,
                    railroadId: railroadId,
                    startDestinationId: direction[0],
                    endDestinationId: direction[1]
                  })
                )
              }
            }}
          >
            <option className="text-left" value="">
              None
            </option>
            {route?.map((item, index) => (
              <option className="text-left" value={item?.route_id} key={index}>
                {item?.route_id}
              </option>
            ))}
          </CSelect>
        </div>

        <div className="w-[20%]">
          <CLabel key="direction" className="flex justify-center w-full">
            Direction
          </CLabel>
          <CSelect
            className="text-center text-align-last-center w-full"
            value={direction}
            onChange={(e: any) => {
              const v = e.target.value
              const endDestinationId = directionList.filter(item => item !== v)
              v !== ''
                ? searchParams.setSearchParam({ k: 'direction', v: v })
                : searchParams.delSearchParam('direction')
              dispatch(
                fetchZoneSpeedLimitsByRouteId({
                  routeId: routeId,
                  railroadId: railroadId,
                  startDestinationId: v,
                  endDestinationId: endDestinationId[0]
                })
              )
              dispatch(
                fetchTSOSpeedLimitsByRouteId({
                  routeId: routeId,
                  railroadId: railroadId,
                  startDestinationId: v,
                  endDestinationId: endDestinationId[0]
                })
              )
              actions.onChangeDirection(v)
            }}
          >
            {directionList?.length > 1 &&
              directionList.map((item, index) => (
                <option className="text-left" value={item} key={index}>
                  {item}
                </option>
              ))}
          </CSelect>
        </div>
        <div className="w-[20%]">
          <CLabel key="type" className="flex justify-center w-full">
            Type
          </CLabel>
          <CustomDropDown
            options={[
              { value: 'Zone', label: 'Zone' },
              { value: 'TSO', label: 'TSO' }
            ]}
            search={false}
            placeholder="select type"
            onChange={handleSelectionTypeChange}
          />
          {/* <CSelect
            className="w-full text-center text-align-last-center"
            value={type}
            onChange={e => {
              const v = (e.target as HTMLInputElement).value
              v !== ''
                ? searchParams.setSearchParam({ k: 'type', v: v })
                : searchParams.delSearchParam('type')
              setTimeout(() => {
                actions.onChangePage('')
              }, 50)
              actions.onChangeType(v)
            }}
          >
            <option className="text-left" value="">
              Any
            </option>
            <option className="text-left" value="Zone">
              Zone
            </option>
            <option className="text-left" value="TSO">
              TSO
            </option>
          </CSelect> */}
        </div>
      </div>

      <div className="flex w-[30%] gap-4 items-end justify-end">
        <CButton
          onClick={() => {
            actions.onChangeActionType(ActionTypes.Add)
          }}
          disabled={isDisable}
          className="bg-slate-500 text-white w-max "
        >
          <div className="flex justify-center items-center gap-2">
            <Icons.AddIcon className="w-[14px] h-[14px]" />
            <span>Add Speed Limit</span>
          </div>
        </CButton>

        {actionType === ActionTypes.Edit ||
        actionType === ActionTypes.EditItem ? (
          <CButton
            onClick={() => {
              actions.onChangeActionType(ActionTypes.View)
              actions.onSelectedItem({
                selectedIndex: -1,
                selectedItemData: null
              })
            }}
            className="bg-red-400 stroke-[#D9DBE0] text-white w-24"
          >
            <div className="flex justify-center items-center gap-1">
              <Icons.EditIcon className="stroke-red-400" />
              <span>Cancel</span>
            </div>
          </CButton>
        ) : (
          <CButton
            onClick={() => {
              Object.keys(speedLimitData?.[0]!).length === 0 &&
                speedLimitData?.[0].constructor === Object &&
                removeFirstSpeedLimit()
              actions.onChangeActionType(ActionTypes.Edit)
              actions.onSelectedItem({
                selectedIndex: -1,
                selectedItemData: null
              })
            }}
            disabled={
              (zoneSpeedLimitsData?.length === 0 &&
                TSOSpeedLimitsData?.length === 0) ||
              isDisable
            }
            className="bg-[#DDDDDD] stroke-[#D9DBE0] text-[#3F4B62]"
          >
            <div className="flex justify-center items-center gap-1">
              <Icons.EditIcon />
              <span>Edit</span>
            </div>
          </CButton>
        )}
      </div>
    </CRow>
  )
}

export default SpeedLimitFiller
Leave a Comment