import { useState, useRef, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { Space, Flex, Card, Splitter, Divider } from 'antd'
import loglevel from 'loglevel'
import config from '../../../../config.js'
import useCollapseState from '../../hooks/useCollapseState.js'
import NotesPanel from '../../common/NotesPanel.jsx'
import InfoCollapse from '../../common/InfoCollapse.jsx'
import ViewButton from '../../common/ViewButton.jsx'
import NoteIcon from '../../../Icons/NoteIcon.jsx'
import ObjectForm from '../../common/ObjectForm.jsx'
import EditButtons from '../../common/EditButtons.jsx'
import ActionHandler from '../../common/ActionHandler.jsx'
import ObjectActions from '../../common/ObjectActions.jsx'

import ObjectInfo from '../../common/ObjectInfo.jsx'
import PrinterIcon from '../../../Icons/PrinterIcon.jsx'

import PrinterTemperaturePanel from '../../common/PrinterTemperaturePanel.jsx'
import PrinterPositionPanel from '../../common/PrinterPositionPanel.jsx'
import PrinterMovementPanel from '../../common/PrinterMovementPanel.jsx'

import JobIcon from '../../../Icons/JobIcon.jsx'
import SubJobIcon from '../../../Icons/SubJobIcon.jsx'
import FilamentStockIcon from '../../../Icons/FilamentStockIcon.jsx'
import MissingPlaceholder from '../../common/MissingPlaceholder.jsx'
import { useMediaQuery } from 'react-responsive'
import AlertsDisplay from '../../common/AlertsDisplay.jsx'

const log = loglevel.getLogger('ControlPrinter')
log.setLevel(config.logLevel)

const ControlPrinter = () => {
  const location = useLocation()
  const objectFormRef = useRef(null)
  const actionHandlerRef = useRef(null)
  const isMobile = useMediaQuery({ maxWidth: 768 })
  const printerId = new URLSearchParams(location.search).get('printerId')
  const [collapseState, updateCollapseState] = useCollapseState(
    'ControlPrinter',
    {
      printer: true,
      job: true,
      subjob: true,
      filamentStock: true,
      temperature: true,
      position: true,
      movement: true
    }
  )

  const [sideBarVisible, setSideBarVisible] = useState(
    collapseState.temperature ||
      collapseState.position ||
      collapseState.movement
  )

  useEffect(() => {
    setSideBarVisible(
      collapseState.temperature ||
        collapseState.position ||
        collapseState.movement
    )
  }, [collapseState])

  const [objectFormState, setEditFormState] = useState({
    isEditing: false,
    editLoading: false,
    formValid: false,
    locked: false,
    loading: false,
    objectData: {}
  })

  const actions = {
    reload: () => {
      objectFormRef?.current.handleFetchObject()
      return true
    },
    edit: () => {
      objectFormRef?.current.startEditing()
      return false
    },
    cancelEdit: () => {
      objectFormRef?.current.cancelEditing()
      return true
    },
    finishEdit: () => {
      objectFormRef?.current.handleUpdate()
      return true
    }
  }

  const sideBarItems = (
    <Flex gap={isMobile ? 'large' : 'middle'} vertical>
      {collapseState.temperature && (
        <Card style={{ width: '100%' }}>
          <PrinterTemperaturePanel id={printerId} />
        </Card>
      )}
      {collapseState.position && (
        <Card style={{ width: '100%' }}>
          <PrinterPositionPanel />
        </Card>
      )}
      {collapseState.movement && (
        <Card style={{ width: '100%' }}>
          <PrinterMovementPanel />
        </Card>
      )}
    </Flex>
  )

  return (
    <Flex
      gap='large'
      vertical='true'
      style={{
        maxHeight: '100%',
        minHeight: 0
      }}
    >
      <Flex justify={'space-between'}>
        <Space size='middle'>
          <Space size='small'>
            <ObjectActions
              type='printer'
              id={printerId}
              disabled={objectFormState.loading}
              visibleActions={{ edit: false }}
            />
            <ViewButton
              disabled={objectFormState.loading}
              items={[
                {
                  key: 'printer',
                  label: 'Printer'
                },
                {
                  key: 'job',
                  label: 'Job'
                },
                {
                  key: 'subJob',
                  label: 'Sub Job'
                },
                {
                  key: 'filamentStock',
                  label: 'Filament Stock'
                },
                {
                  key: 'temperature',
                  label: 'Temperature'
                },
                {
                  key: 'position',
                  label: 'Position'
                },
                {
                  key: 'movement',
                  label: 'Movement'
                },
                { key: 'notes', label: 'Notes' }
              ]}
              visibleState={collapseState}
              updateVisibleState={updateCollapseState}
            />
            <AlertsDisplay alerts={objectFormState.objectData?.alerts} />
          </Space>
        </Space>
        <Space>
          <EditButtons
            isEditing={objectFormState.isEditing}
            handleUpdate={() => {
              actionHandlerRef.current.callAction('finishEdit')
            }}
            cancelEditing={() => {
              actionHandlerRef.current.callAction('cancelEdit')
            }}
            startEditing={() => {
              actionHandlerRef.current.callAction('edit')
            }}
            editLoading={objectFormState.editLoading}
            formValid={objectFormState.formValid}
            disabled={objectFormState.lock?.locked || objectFormState.loading}
            loading={objectFormState.editLoading}
          />
        </Space>
      </Flex>

      <div style={{ height: '100%', overflowY: 'scroll' }}>
        <Flex vertical gap={'large'}>
          <ActionHandler
            actions={actions}
            loading={objectFormState.loading}
            ref={actionHandlerRef}
          >
            <ObjectForm
              id={printerId}
              type='printer'
              ref={objectFormRef}
              onStateChange={(state) => {
                console.log('Got edit form state change', state)
                setEditFormState((prev) => ({ ...prev, ...state }))
              }}
            >
              {({
                loading: printerObjectLoading,
                objectData: printerObjectData
              }) => {
                return (
                  <Flex vertical>
                    <Splitter className={'farmcontrol-splitter'}>
                      <Splitter.Panel>
                        <Flex vertical gap={'large'}>
                          <InfoCollapse
                            title={'Printer'}
                            icon={<PrinterIcon />}
                            collapseKey='printer'
                            active={collapseState.printer}
                            onToggle={(expanded) =>
                              updateCollapseState('printer', expanded)
                            }
                          >
                            <ObjectInfo
                              loading={printerObjectLoading}
                              column={sideBarVisible ? 1 : undefined}
                              visibleProperties={{
                                connectedAt: false,
                                vendor: false,
                                'vendor._id': false,
                                host: false,
                                'host._id': false,
                                'moonraker.port': false,
                                'moonraker.apiKey': false,
                                'moonraker.protocol': false,
                                'moonraker.host': false,
                                tags: false,
                                firmware: false
                              }}
                              objectData={printerObjectData}
                              type='printer'
                            />
                          </InfoCollapse>
                          <InfoCollapse
                            title={'Job'}
                            icon={<JobIcon />}
                            collapseKey='job'
                            active={collapseState.job}
                            onToggle={(expanded) =>
                              updateCollapseState('job', expanded)
                            }
                          >
                            {printerObjectData?.currentJob?._id ? (
                              <ObjectForm
                                id={printerObjectData.currentJob._id}
                                type='job'
                                onStateChange={() => {}}
                              >
                                {({
                                  loading: jobObjectLoading,
                                  objectData: jobObjectData
                                }) => {
                                  return (
                                    <ObjectInfo
                                      loading={jobObjectLoading}
                                      column={sideBarVisible ? 1 : undefined}
                                      visibleProperties={{
                                        printers: false,
                                        createdAt: false
                                      }}
                                      objectData={jobObjectData}
                                      type='job'
                                    />
                                  )
                                }}
                              </ObjectForm>
                            ) : (
                              <MissingPlaceholder message={'No job.'} />
                            )}
                          </InfoCollapse>
                          <InfoCollapse
                            title={'Sub Job'}
                            icon={<SubJobIcon />}
                            collapseKey='subJob'
                            active={collapseState.subJob}
                            onToggle={(expanded) =>
                              updateCollapseState('subJob', expanded)
                            }
                          >
                            {printerObjectData?.currentSubJob?._id ? (
                              <ObjectForm
                                id={printerObjectData.currentSubJob._id}
                                type='subjob'
                                onStateChange={() => {}}
                              >
                                {({
                                  loading: subJobObjectLoading,
                                  objectData: subJobObjectData
                                }) => {
                                  return (
                                    <ObjectInfo
                                      loading={subJobObjectLoading}
                                      column={sideBarVisible ? 1 : undefined}
                                      visibleProperties={{
                                        printers: false,
                                        createdAt: false
                                      }}
                                      objectData={subJobObjectData}
                                      type='subJob'
                                    />
                                  )
                                }}
                              </ObjectForm>
                            ) : (
                              <MissingPlaceholder message={'No sub job.'} />
                            )}
                          </InfoCollapse>
                          <InfoCollapse
                            title={'Filament Stock'}
                            icon={<FilamentStockIcon />}
                            collapseKey='filamentStock'
                            active={collapseState.filamentStock}
                            onToggle={(expanded) =>
                              updateCollapseState('filamentStock', expanded)
                            }
                          >
                            {printerObjectData?.currentFilamentStock?._id ? (
                              <ObjectForm
                                id={printerObjectData.currentFilamentStock._id}
                                type='filamentStock'
                                onStateChange={() => {}}
                              >
                                {({
                                  loading: filamentStockObjectLoading,
                                  objectData: filamentStockObjectData
                                }) => {
                                  return (
                                    <ObjectInfo
                                      loading={filamentStockObjectLoading}
                                      column={sideBarVisible ? 1 : undefined}
                                      showHyperlink={true}
                                      visibleProperties={{
                                        updatedAt: false,
                                        createdAt: false
                                      }}
                                      objectData={filamentStockObjectData}
                                      type='filamentStock'
                                    />
                                  )
                                }}
                              </ObjectForm>
                            ) : (
                              <MissingPlaceholder message={'No sub job.'} />
                            )}
                          </InfoCollapse>
                        </Flex>
                      </Splitter.Panel>
                      {sideBarVisible && !isMobile ? (
                        <Splitter.Panel
                          style={{ minWidth: '325px' }}
                          defaultSize='20%'
                          max='35%'
                        >
                          {sideBarItems}
                        </Splitter.Panel>
                      ) : null}
                    </Splitter>
                    {isMobile ? (
                      <>
                        <Divider />
                        {sideBarItems}
                      </>
                    ) : null}
                  </Flex>
                )
              }}
            </ObjectForm>
          </ActionHandler>
          <InfoCollapse
            title='Notes'
            icon={<NoteIcon />}
            active={collapseState.notes}
            onToggle={(expanded) => updateCollapseState('notes', expanded)}
            collapseKey='notes'
          >
            <Card>
              <NotesPanel _id={printerId} type='printer' />
            </Card>
          </InfoCollapse>
        </Flex>
      </div>
    </Flex>
  )
}

export default ControlPrinter
