import { useRef, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { Card, Flex, Space } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import ActionHandler from '../../common/ActionHandler'
import AuditLogIcon from '../../../Icons/AuditLogIcon'
import DocumentPrintButton from '../../common/DocumentPrintButton'
import EditButtons from '../../common/EditButtons'
import ObjectTableNavigationButtons from '../../common/ObjectTableNavigationButtons.jsx'
import HotEndIcon from '../../../Icons/HotEndIcon'
import InfoCircleIcon from '../../../Icons/InfoCircleIcon'
import MultiMotionIcon from '../../../Icons/MultiMotionIcon'
import PictureIcon from '../../../Icons/PictureIcon'
import RulerIcon from '../../../Icons/RulerIcon'
import InfoCollapse from '../../common/InfoCollapse'
import InfoCollapsePlaceholder from '../../common/InfoCollapsePlaceholder'
import ActivityIndicator from '../../common/ActivityIndicator'
import NoteIcon from '../../../Icons/NoteIcon'
import NotesPanel from '../../common/NotesPanel'
import ObjectActions from '../../common/ObjectActions'
import ObjectForm from '../../common/ObjectForm'
import ObjectInfo from '../../common/ObjectInfo'
import ObjectTable from '../../common/ObjectTable'
import ScrollBox from '../../common/ScrollBox'
import UserNotifierToggle from '../../common/UserNotifierToggle'
import ViewButton from '../../common/ViewButton'
import useCollapseState from '../../hooks/useCollapseState'
import ObjectProperty from '../../common/ObjectProperty'
import { getModelProperty } from '../../../../database/ObjectModels'
import GCodeFileIcon from '../../../Icons/GCodeFileIcon'
import SettingsIcon from '../../../Icons/SettingsIcon'
import ExclamationOctagonIcon from '../../../Icons/ExclamationOctagonIcon'

const PrinterProfileInfo = () => {
  const location = useLocation()
  const objectFormRef = useRef(null)
  const actionHandlerRef = useRef(null)
  const printerProfileId = new URLSearchParams(location.search).get(
    'printerProfileId'
  )
  const [collapseState, updateCollapseState] = useCollapseState(
    'PrinterProfileInfo',
    {
      info: true,
      dimensions: true,
      bedExcludeArea: true,
      extruders: true,
      motion: true,
      gCodeSettings: true,
      optional: true,
      thumbnails: true,
      notes: true,
      auditLogs: false
    }
  )
  const [objectFormState, setObjectFormState] = useState({
    isEditing: false,
    editLoading: false,
    formValid: false,
    lock: null,
    loading: false,
    editDisabled: false,
    objectData: {}
  })

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

  return (
    <Flex
      gap='large'
      vertical='true'
      style={{ maxHeight: '100%', minHeight: 0 }}
    >
      <Flex justify='space-between'>
        <Space size='small'>
          <Space size='small'>
            <ObjectActions
              type='printerProfile'
              id={printerProfileId}
              disabled={objectFormState.loading}
              objectData={objectFormState.objectData}
            />
            <ViewButton
              disabled={objectFormState.loading}
              items={[
                { key: 'info', label: 'Printer Profile Information' },
                { key: 'dimensions', label: 'Dimensions' },
                { key: 'bedExcludeArea', label: 'Excluded Bed Area' },
                { key: 'extruders', label: 'Extruders' },
                { key: 'motion', label: 'Motion' },
                { key: 'gCodeSettings', label: 'G-Code Settings' },
                { key: 'miscellaneous', label: 'Miscellaneous' },
                { key: 'thumbnails', label: 'Thumbnail Sizes' },
                { key: 'notes', label: 'Notes' },
                { key: 'auditLogs', label: 'Audit Logs' }
              ]}
              visibleState={collapseState}
              updateVisibleState={updateCollapseState}
            />
            <UserNotifierToggle
              type='printerProfile'
              objectData={objectFormState.objectData}
              disabled={objectFormState.loading}
            />
            <DocumentPrintButton
              type='printerProfile'
              objectData={objectFormState.objectData}
              disabled={objectFormState.loading}
            />
          </Space>
          <ActivityIndicator
            activities={objectFormState.activities}
            showStartingDivider={true}
          />
        </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.beingEditedByOther ||
              objectFormState.loading ||
              objectFormState.editDisabled
            }
            loading={objectFormState.editLoading}
          />
          <ObjectTableNavigationButtons
            disabled={objectFormState.loading}
            _id={printerProfileId}
            objectType='printerProfile'
            showEndingDivider={true}
          />
        </Space>
      </Flex>

      <ScrollBox>
        <Flex vertical gap='large'>
          <ActionHandler
            actions={actions}
            loading={objectFormState.loading}
            ref={actionHandlerRef}
          >
            <ObjectForm
              id={printerProfileId}
              type='printerProfile'
              ref={objectFormRef}
              setCurrentObject={true}
              onStateChange={(state) =>
                setObjectFormState((current) => ({ ...current, ...state }))
              }
            >
              {({ loading, isEditing, objectData }) => (
                <Flex vertical gap='large'>
                  <InfoCollapse
                    title='Printer Profile Information'
                    icon={<InfoCircleIcon />}
                    active={collapseState.info}
                    onToggle={(expanded) =>
                      updateCollapseState('info', expanded)
                    }
                    collapseKey='info'
                  >
                    <ObjectInfo
                      loading={loading}
                      indicator={<LoadingOutlined />}
                      isEditing={isEditing}
                      type='printerProfile'
                      objectData={objectData}
                      labelWidth='140px'
                      visibleProperties={{
                        _id: true,
                        name: true,
                        _reference: true,
                        printer: true,
                        createdAt: true,
                        updatedAt: true
                      }}
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='Dimensions'
                    icon={<RulerIcon />}
                    active={collapseState.dimensions}
                    onToggle={(expanded) =>
                      updateCollapseState('dimensions', expanded)
                    }
                    collapseKey='dimensions'
                  >
                    <ObjectInfo
                      loading={loading}
                      indicator={<LoadingOutlined />}
                      isEditing={isEditing}
                      type='printerProfile'
                      objectData={objectData}
                      labelWidth='230px'
                      visibleProperties={{
                        printBedWidth: true,
                        printBedHeight: true,
                        originX: true,
                        originY: true,
                        printableHeight: true,
                        supportMultiBedTypes: true,
                        bestObjectPositionX: true,
                        bestObjectPositionY: true,
                        zOffset: true,
                        preferredOrientation: true
                      }}
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='Excluded Bed Area'
                    icon={<ExclamationOctagonIcon />}
                    active={collapseState.bedExcludeArea}
                    onToggle={(expanded) =>
                      updateCollapseState('bedExcludeArea', expanded)
                    }
                    collapseKey='bedExcludeArea'
                  >
                    <ObjectProperty
                      {...getModelProperty('printerProfile', 'bedExcludeArea')}
                      isEditing={isEditing}
                      objectData={objectData}
                      loading={loading}
                      size='medium'
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='Extruders'
                    icon={<HotEndIcon />}
                    active={collapseState.extruders}
                    onToggle={(expanded) =>
                      updateCollapseState('extruders', expanded)
                    }
                    collapseKey='extruders'
                  >
                    <ObjectProperty
                      {...getModelProperty('printerProfile', 'extruders')}
                      isEditing={isEditing}
                      objectData={objectData}
                      loading={loading}
                      size='medium'
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='Motion'
                    icon={<MultiMotionIcon />}
                    active={collapseState.motion}
                    onToggle={(expanded) =>
                      updateCollapseState('motion', expanded)
                    }
                    collapseKey='motion'
                  >
                    <ObjectInfo
                      loading={loading}
                      indicator={<LoadingOutlined />}
                      isEditing={isEditing}
                      type='printerProfile'
                      objectData={objectData}
                      labelWidth='225px'
                      visibleProperties={{
                        machineMaxAccelerationRetracting: true,
                        machineMaxSpeedE: true,
                        machineMaxSpeedX: true,
                        machineMaxSpeedY: true,
                        machineMaxJunctionDeviation: true
                      }}
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='G-Code Settings'
                    icon={<GCodeFileIcon />}
                    active={collapseState.gCodeSettings}
                    onToggle={(expanded) =>
                      updateCollapseState('gCodeSettings', expanded)
                    }
                    collapseKey='gCodeSettings'
                  >
                    <ObjectInfo
                      loading={loading}
                      indicator={<LoadingOutlined />}
                      isEditing={isEditing}
                      type='printerProfile'
                      objectData={objectData}
                      labelWidth='240px'
                      visibleProperties={{
                        machinePauseGcode: true,
                        machineStartGcode: true,
                        machineEndGcode: true,
                        layerChangeGcode: true,
                        beforeLayerChangeGcode: true
                      }}
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='Miscellaneous'
                    icon={<SettingsIcon />}
                    active={collapseState.miscellaneous}
                    onToggle={(expanded) =>
                      updateCollapseState('miscellaneous', expanded)
                    }
                    collapseKey='miscellaneous'
                  >
                    <ObjectInfo
                      loading={loading}
                      indicator={<LoadingOutlined />}
                      isEditing={isEditing}
                      type='printerProfile'
                      objectData={objectData}
                      labelWidth='210px'
                      visibleProperties={{
                        printerNotes: true,
                        scanFirstLayer: true,
                        machineLoadFilamentTime: true,
                        machineUnloadFilamentTime: true,
                        auxiliaryFan: true
                      }}
                    />
                  </InfoCollapse>
                  <InfoCollapse
                    title='Thumbnail Sizes'
                    icon={<PictureIcon />}
                    active={collapseState.thumbnails}
                    onToggle={(expanded) =>
                      updateCollapseState('thumbnails', expanded)
                    }
                    collapseKey='thumbnails'
                  >
                    <ObjectProperty
                      {...getModelProperty('printerProfile', 'thumbnails')}
                      isEditing={isEditing}
                      objectData={objectData}
                      loading={loading}
                      size='medium'
                    />
                  </InfoCollapse>
                </Flex>
              )}
            </ObjectForm>
          </ActionHandler>

          <InfoCollapse
            title='Notes'
            icon={<NoteIcon />}
            active={collapseState.notes}
            onToggle={(expanded) => updateCollapseState('notes', expanded)}
            collapseKey='notes'
          >
            <Card>
              <NotesPanel _id={printerProfileId} type='printerProfile' />
            </Card>
          </InfoCollapse>

          <InfoCollapse
            title='Audit Logs'
            icon={<AuditLogIcon />}
            active={collapseState.auditLogs}
            onToggle={(expanded) => updateCollapseState('auditLogs', expanded)}
            collapseKey='auditLogs'
          >
            {objectFormState.loading ? (
              <InfoCollapsePlaceholder />
            ) : (
              <ObjectTable
                type='auditLog'
                masterFilter={{ 'parent._id': printerProfileId }}
                visibleColumns={{ _id: false, 'parent._id': false }}
              />
            )}
          </InfoCollapse>
        </Flex>
      </ScrollBox>
    </Flex>
  )
}

export default PrinterProfileInfo
