import PropTypes from 'prop-types'
import {
  useState,
  useEffect,
  useContext,
  useCallback,
  useMemo,
  useRef
} from 'react'
// import { getModelByName } from '../../../database/ObjectModels'
import DocumentPrinterIcon from '../../Icons/DocumentPrinterIcon'
import { Button, Dropdown, Modal } from 'antd'
import { ApiServerContext } from '../context/ApiServerContext'
import DocumentTemplateIcon from '../../Icons/DocumentTemplateIcon'
import NewDocumentJob from '../Management/DocumentJobs/NewDocumentJob'
import { AuthContext } from '../context/AuthContext'

const DocumentPrintButton = ({
  type,
  objectData,
  disabled = false,
  ...buttonProps
}) => {
  const { fetchObjects } = useContext(ApiServerContext)
  const fetchObjectsRef = useRef(fetchObjects)
  fetchObjectsRef.current = fetchObjects

  const [documentTemplates, setDocumentTemplates] = useState([])
  const [currentDocumentTemplate, setCurrentDocumentTemplate] = useState(null)
  const [loading, setLoading] = useState(false)
  const [newDocumentJobOpen, setNewDocumentJobOpen] = useState(false)

  const { token } = useContext(AuthContext)

  // Get the model by name
  //const model = getModelByName(type)

  const loadDocumentTemplates = useCallback(async () => {
    if (!type || token == null) return

    setLoading(true)
    try {
      const result = await fetchObjectsRef.current('documentTemplate', {
        filter: {
          objectType: type,
          global: false,
          active: true
        },
        limit: 100 // Get more templates to show in dropdown
      })

      if (result && result.data) {
        setDocumentTemplates(result.data)
      }
    } catch (error) {
      console.error('Error fetching document templates:', error)
    } finally {
      setLoading(false)
    }
  }, [type, token])

  // Stable key from objectData._id (excludes _isEditing so toggling edit mode doesn't trigger template reload)
  const objectKey = useMemo(() => {
    if (!objectData) return null
    return objectData._id ?? objectData.id ?? null
  }, [objectData])

  // Fetch document templates when component mounts or objectData, type or token changes
  useEffect(() => {
    loadDocumentTemplates()
  }, [objectKey, token, type, loadDocumentTemplates])

  // Handle template selection
  const handleTemplateSelect = (template) => {
    setCurrentDocumentTemplate(template)
    setNewDocumentJobOpen(true)
    // TODO: Implement the actual printing logic here
    // This could open a print dialog, navigate to a print page, etc.
  }

  // Create dropdown menu items
  const menuItems = documentTemplates.map((template) => ({
    key: template._id,
    label: template.name,
    icon: <DocumentTemplateIcon />,
    onClick: () => handleTemplateSelect(template)
  }))

  // If no templates available, show disabled state
  if (documentTemplates.length === 0 && !loading) {
    return (
      <Button
        {...buttonProps}
        icon={<DocumentPrinterIcon />}
        disabled={true}
        title='No document templates available for this object type'
      />
    )
  }

  return (
    <>
      <Dropdown
        menu={{
          items: menuItems,
          loading: loading
        }}
        trigger={['hover']}
        disabled={disabled || loading}
      >
        <Button
          {...buttonProps}
          icon={<DocumentPrinterIcon />}
          disabled={disabled || loading}
          loading={loading}
          title={loading ? 'Loading templates...' : 'Print document'}
        />
      </Dropdown>
      <Modal
        open={newDocumentJobOpen}
        onCancel={() => setNewDocumentJobOpen(false)}
        footer={null}
        destroyOnHidden={true}
        width={{
          xs: '100%',
          sm: '100%',
          md: '100%',
          lg: '90%',
          xl: '80%',
          xxl: '80%'
        }}
      >
        <NewDocumentJob
          onOk={() => {
            setNewDocumentJobOpen(false)
          }}
          reset={!newDocumentJobOpen}
          defaultValues={{
            objectType: type,
            object: objectData,
            documentTemplate: currentDocumentTemplate
          }}
        />
      </Modal>
    </>
  )
}

DocumentPrintButton.propTypes = {
  type: PropTypes.string.isRequired,
  disabled: PropTypes.bool,
  objectData: PropTypes.object.isRequired
}

export default DocumentPrintButton
