import { useContext, useRef, useState , useEffect} from 'react'
import { useLocation } from 'react-router-dom'
import { Card, Flex, message, Space } from 'antd'
import loglevel from 'loglevel'
import config from '../../../../config'
import useCollapseState from '../../hooks/useCollapseState'
import NotesPanel from '../../common/NotesPanel'
import InfoCollapse from '../../common/InfoCollapse'
import ObjectInfo from '../../common/ObjectInfo'
import ViewButton from '../../common/ViewButton'
import InfoCircleIcon from '../../../Icons/InfoCircleIcon.jsx'
import NoteIcon from '../../../Icons/NoteIcon.jsx'
import AuditLogIcon from '../../../Icons/AuditLogIcon.jsx'
import ObjectForm from '../../common/ObjectForm'
import EditButtons from '../../common/EditButtons'
import ObjectTableNavigationButtons from '../../common/ObjectTableNavigationButtons.jsx'
import ActivityIndicator from '../../common/ActivityIndicator.jsx'
import ActionHandler from '../../common/ActionHandler.jsx'
import { useActions } from '../../context/ActionsContext'
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 ScrollBox from '../../common/ScrollBox.jsx'
import { ApiServerContext } from '../../context/ApiServerContext.jsx'
import { ElectronContext } from '../../context/ElectronContext.jsx'
import {
  buildMarketplaceAuthState,
  storeMarketplaceAuthState
} from './authUtils.js'

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

const MarketplaceInfo = () => {
  const location = useLocation()
  const objectFormRef = useRef(null)
  const actionHandlerRef = useRef(null)


  const { setOnModalOk } = useActions()
  useEffect(() => {
    setOnModalOk(() => () => {
      objectFormRef.current?.handleFetchObject?.()
    })
    return () => setOnModalOk(null)
  }, [setOnModalOk])
  const { getMarketplaceAuthUrl, refreshMarketplaceAuth } =
    useContext(ApiServerContext)
  const { openExternalUrl } = useContext(ElectronContext)
  const marketplaceId = new URLSearchParams(location.search).get(
    'marketplaceId'
  )
  const [collapseState, updateCollapseState] = useCollapseState(
    'MarketplaceInfo',
    {
      info: true,
      notes: true,
      auditLogs: false
    }
  )
  const [objectFormState, setEditFormState] = useState({
    isEditing: false,
    editLoading: false,
    formValid: false,
    lock: null,
    loading: false,
    editDisabled: false,
    objectData: {}
  })

  const startAuthorization = async () => {
    const objectData = objectFormState.objectData
    if (!objectData?._id) return

    if (objectFormState.isEditing) {
      message.warning('Save marketplace changes before starting authorization')
      return
    }

    const returnTo = `/dashboard/sales/marketplaces/info?marketplaceId=${objectData._id}`
    const state = buildMarketplaceAuthState({
      marketplaceId: objectData._id,
      returnTo
    })

    storeMarketplaceAuthState(state, {
      marketplaceId: objectData._id,
      returnTo
    })

    const result = await getMarketplaceAuthUrl(objectData._id, state)

    if (!result?.url) {
      message.error('Authorization URL was not returned')
      return
    }

    const openedExternally = openExternalUrl(result.url)
    if (!openedExternally) {
      window.location.assign(result.url)
    }
  }

  const handleRefreshToken = async () => {
    const objectData = objectFormState.objectData
    if (!objectData?._id) return

    const result = await refreshMarketplaceAuth(objectData._id)
    if (!result?.success) {
      message.error(result?.error || 'Token refresh failed')
      return
    }
    message.success('Marketplace token refreshed')
    objectFormRef?.current?.handleFetchObject?.()
  }

  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
    },
    connect: () => {
      startAuthorization()
      return true
    },
    reconnect: () => {
      startAuthorization()
      return true
    },
    refreshToken: () => {
      handleRefreshToken()
      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='marketplace'
                id={marketplaceId}
                disabled={objectFormState.loading}
                objectData={objectFormState.objectData}
              />
              <ViewButton
                disabled={objectFormState.loading}
                items={[
                  { key: 'info', label: 'Marketplace Information' },
                  { key: 'notes', label: 'Notes' },
                  { key: 'auditLogs', label: 'Audit Logs' }
                ]}
                visibleState={collapseState}
                updateVisibleState={updateCollapseState}
              />
              <UserNotifierToggle
                type='marketplace'
                objectData={objectFormState.objectData}
                disabled={objectFormState.loading}
              />
              <DocumentPrintButton
                type='marketplace'
                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={marketplaceId}
              objectType='marketplace'
              showEndingDivider={true}
            />
          </Space>
        </Flex>
        <ScrollBox>
          <Flex vertical gap={'large'}>
            <ActionHandler
              actions={actions}
              loading={objectFormState.loading}
              ref={actionHandlerRef}
            >
              <InfoCollapse
                title='Marketplace Information'
                icon={<InfoCircleIcon />}
                active={collapseState.info}
                onToggle={(expanded) => updateCollapseState('info', expanded)}
                collapseKey='info'
              >
                <ObjectForm
                  id={marketplaceId}
                  type='marketplace'
                  style={{ height: '100%' }}
                  ref={objectFormRef}
                  setCurrentObject={true}
                  onStateChange={(state) => {
                    setEditFormState((prev) => ({ ...prev, ...state }))
                  }}
                >
                  {({ loading, isEditing, objectData }) => (
                    <ObjectInfo
                      loading={loading}
                      isEditing={isEditing}
                      type='marketplace'
                      labelWidth={215}
                      objectData={objectData}
                    />
                  )}
                </ObjectForm>
              </InfoCollapse>
            </ActionHandler>
            <InfoCollapse
              title='Notes'
              icon={<NoteIcon />}
              active={collapseState.notes}
              onToggle={(expanded) => updateCollapseState('notes', expanded)}
              collapseKey='notes'
            >
              <Card>
                <NotesPanel _id={marketplaceId} type='marketplace' />
              </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': marketplaceId }}
                  visibleColumns={{ _id: false, 'parent._id': false }}
                />
              )}
            </InfoCollapse>
          </Flex>
        </ScrollBox>
      </Flex>
  )
}

export default MarketplaceInfo
