import { useContext, useRef, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { Card, Flex, Space } from 'antd'
import loglevel from 'loglevel'
import config from '../../../../config.js'
import useCollapseState from '../../hooks/useCollapseState.jsx'
import NotesPanel from '../../common/NotesPanel.jsx'
import InfoCollapse from '../../common/InfoCollapse.jsx'
import ObjectInfo from '../../common/ObjectInfo.jsx'
import ViewButton from '../../common/ViewButton.jsx'
import InfoCircleIcon from '../../../Icons/InfoCircleIcon.jsx'
import NoteIcon from '../../../Icons/NoteIcon.jsx'
import AuditLogIcon from '../../../Icons/AuditLogIcon.jsx'
import ObjectForm from '../../common/ObjectForm.jsx'
import EditButtons from '../../common/EditButtons.jsx'
import ObjectTableNavigationButtons from '../../common/ObjectTableNavigationButtons.jsx'
import ActivityIndicator from '../../common/ActivityIndicator.jsx'
import ActionHandler from '../../common/ActionHandler.jsx'
import ObjectActions from '../../common/ObjectActions.jsx'
import ObjectTable from '../../common/ObjectTable.jsx'
import InfoCollapsePlaceholder from '../../common/InfoCollapsePlaceholder.jsx'
import DocumentPrintButton from '../../common/DocumentPrintButton.jsx'
import UserNotifierToggle from '../../common/UserNotifierToggle.jsx'
import FileIcon from '../../../Icons/FileIcon.jsx'
import FilePreview from '../../common/FilePreview.jsx'
import MissingPlaceholder from '../../common/MissingPlaceholder.jsx'
import { ApiServerContext } from '../../context/ApiServerContext.jsx'
import ScrollBox from '../../common/ScrollBox.jsx'
import JsonObjectIcon from '../../../Icons/JsonObjectIcon.jsx'
import ObjectProperty from '../../common/ObjectProperty.jsx'
import { getModelProperty } from '../../../../database/ObjectModels.js'

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

const FileInfo = () => {
  const location = useLocation()
  const objectFormRef = useRef(null)
  const actionHandlerRef = useRef(null)
  const fileId = new URLSearchParams(location.search).get('fileId')
  const [collapseState, updateCollapseState] = useCollapseState('FileInfo', {
    info: true,
    notes: true,
    auditLogs: false
  })
  const [objectFormState, setEditFormState] = useState({
    isEditing: false,
    editLoading: false,
    formValid: false,
    lock: null,
    loading: true,
    editDisabled: false,
    objectData: {
      _id: fileId
    }
  })
  const { fetchFileContent } = useContext(ApiServerContext)

  const actions = {
    edit: () => {
      objectFormRef?.current?.startEditing?.()
      return false
    },
    cancelEdit: () => {
      objectFormRef?.current?.cancelEditing?.()
      return true
    },
    finishEdit: () => {
      objectFormRef?.current?.handleUpdate?.()
      return true
    },
    download: () => {
      fetchFileContent(objectFormState?.objectData, true)
      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='file'
                id={fileId}
                disabled={objectFormState.loading}
                objectData={objectFormState.objectData}
              />
              <ViewButton
                disabled={objectFormState.loading}
                items={[
                  { key: 'info', label: 'File Information' },
                  { key: 'preview', label: 'Preview' },
                  { key: 'metaData', label: 'Meta Data' },
                  { key: 'notes', label: 'Notes' },
                  { key: 'auditLogs', label: 'Audit Logs' }
                ]}
                visibleState={collapseState}
                updateVisibleState={updateCollapseState}
              />
              <UserNotifierToggle
                type='file'
                objectData={objectFormState.objectData}
                disabled={objectFormState.loading}
              />
              <DocumentPrintButton
                type='file'
                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 || objectFormState.isEditing}
              _id={fileId}
              objectType='file'
              showEndingDivider={true}
            />
          </Space>
        </Flex>
        <ScrollBox>
          <Flex vertical gap={'large'}>
            <ActionHandler
              actions={actions}
              loading={objectFormState.loading}
              ref={actionHandlerRef}
            >
              <InfoCollapse
                title='File Information'
                icon={<InfoCircleIcon />}
                active={collapseState.info}
                onToggle={(expanded) => updateCollapseState('info', expanded)}
                collapseKey='info'
              >
                <ObjectForm
                  id={fileId}
                  type='file'
                  style={{ height: '100%' }}
                  ref={objectFormRef}
                  setCurrentObject={true}
                  onStateChange={(state) => {
                    setEditFormState((prev) => ({ ...prev, ...state }))
                  }}
                >
                  {({ loading, isEditing, objectData }) => (
                    <ObjectInfo
                      loading={loading}
                      isEditing={isEditing}
                      type='file'
                      labelWidth={170}
                      visibleProperties={{ metaData: false }}
                      objectData={objectData}
                    />
                  )}
                </ObjectForm>
              </InfoCollapse>
            </ActionHandler>
            <InfoCollapse
              title='Preview'
              icon={<FileIcon />}
              active={collapseState.preview}
              onToggle={(expanded) => updateCollapseState('preview', expanded)}
              collapseKey='preview'
            >
              {objectFormState?.objectData?._id ? (
                <Card>
                  <FilePreview
                    file={objectFormState?.objectData}
                    style={{ width: '100%', height: '100%' }}
                  />
                </Card>
              ) : (
                <MissingPlaceholder message={'No file.'} />
              )}
            </InfoCollapse>
            <InfoCollapse
              title='Meta Data'
              icon={<JsonObjectIcon />}
              active={collapseState.metaData}
              onToggle={(expanded) => updateCollapseState('metaData', expanded)}
              collapseKey='metaData'
            >
              {objectFormState?.objectData?._id ? (
                <Card>
                  <ObjectProperty
                    {...getModelProperty('file', 'metaData')}
                    objectData={objectFormState?.objectData}
                  />
                </Card>
              ) : (
                <MissingPlaceholder message={'No file meta data.'} />
              )}
            </InfoCollapse>
            <InfoCollapse
              title='Notes'
              icon={<NoteIcon />}
              active={collapseState.notes}
              onToggle={(expanded) => updateCollapseState('notes', expanded)}
              collapseKey='notes'
            >
              <Card>
                <NotesPanel _id={fileId} type='file' />
              </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': fileId }}
                  visibleColumns={{ _id: false, 'parent._id': false }}
                />
              )}
            </InfoCollapse>
          </Flex>
        </ScrollBox>
      </Flex>
    </>
  )
}

export default FileInfo
