import { createElement, lazy } from 'react'

const OrderItemInfo = lazy(
  () => import('../../components/Dashboard/Inventory/OrderItems/OrderItemInfo')
)
import OrderItemIcon from '../../components/Icons/OrderItemIcon'
import InfoCircleIcon from '../../components/Icons/InfoCircleIcon'
import EditIcon from '../../components/Icons/EditIcon'
import CheckIcon from '../../components/Icons/CheckIcon'
import XMarkIcon from '../../components/Icons/XMarkIcon'
import BinIcon from '../../components/Icons/BinIcon'

export const OrderItem = {
  name: 'orderItem',
  label: 'Order Item',
  labelPlural: 'Order Items',
  url: '/dashboard/inventory/orderitems',
  prefix: 'ODI',
  icon: OrderItemIcon,
  actions: [
    {
      name: 'info',
      type: 'page',
      pageName: 'info',
      label: 'Info',
      default: true,
      row: true,
      icon: InfoCircleIcon
    },
    {
      name: 'edit',
      type: 'page',
      pageName: 'info',
      label: 'Edit',
      row: true,
      icon: EditIcon,
      visible: (objectData) => {
        return !(objectData?._isEditing && objectData?._isEditing == true)
      },
      disabled: (objectData) => {
        return objectData?.state?.type != 'draft'
      }
    },
    {
      name: 'cancelEdit',
      label: 'Cancel Edits',
      type: 'page',
      pageName: 'info',
      icon: XMarkIcon,
      visible: (objectData) => {
        return objectData?._isEditing && objectData?._isEditing == true
      }
    },
    {
      name: 'finishEdit',
      label: 'Save Edits',
      type: 'page',
      pageName: 'info',
      icon: CheckIcon,
      visible: (objectData) => {
        return objectData?._isEditing && objectData?._isEditing == true
      }
    },
    {
      name: 'delete',
      type: 'page',
      pageName: 'info',
      label: 'Delete',
      icon: BinIcon,
      danger: true,
      visible: (objectData) => {
        return !(objectData?._isEditing && objectData?._isEditing == true)
      },
      disabled: (objectData) => {
        return objectData?.state?.type != 'draft'
      }
    }
  ],
  pages: [
    {
      name: 'info',
      content: () => createElement(OrderItemInfo)
    }
  ],
  group: [],
  filters: [
    'name',
    'itemType',
    'item',
    'item._id',
    'order',
    'order._id',
    'orderType',
    'shipment',
    'shipment._id',
    'state',
    'createdAt',
    'updatedAt',
    '_reference'
  ],
  sorters: [
    'createdAt',
    'updatedAt',
    'itemAmount',
    'quantity',
    'state',
    'name'
  ],
  columns: [
    '_reference',
    'name',
    'state',
    'itemType',
    'item',
    'sku',
    'itemAmount',
    'quantity',
    'totalAmount',
    'taxRate',
    'totalAmountWithTax',
    'order',
    'shipment',
    'invoicedAmount',
    'invoicedAmountWithTax',
    'invoicedQuantity',
    'invoicedAmountRemaining',
    'invoicedAmountWithTaxRemaining',
    'invoicedQuantityRemaining',
    'orderedAt',
    'receivedAt',
    'createdAt',
    'updatedAt'
  ],
  properties: [
    {
      name: '_id',
      label: 'ID',
      type: 'id',
      columnFixed: 'left',
      objectType: 'orderItem',
      columnWidth: 140,
      showCopy: true
    },
    {
      name: 'createdAt',
      label: 'Created At',
      type: 'dateTime',
      readOnly: true,
      columnWidth: 175
    },
    {
      name: '_reference',
      label: 'Reference',
      type: 'reference',
      columnFixed: 'left',
      objectType: 'orderItem',
      showCopy: true,
      readOnly: true,
      columnWidth: 180
    },
    {
      name: 'updatedAt',
      label: 'Updated At',
      type: 'dateTime',
      readOnly: true,
      columnWidth: 175
    },
    {
      name: 'name',
      label: 'Name',
      type: 'text',
      readOnly: true,
      columnWidth: 200,
      columnFixed: 'left',
      value: (objectData) => {
        return objectData?.sku?.name ?? objectData?.item?.name
      }
    },
    {
      name: 'orderedAt',
      label: 'Ordered At',
      type: 'dateTime',
      required: false,
      readOnly: true,
      columnWidth: 175
    },
    {
      name: 'state',
      label: 'State',
      type: 'state',
      readOnly: true,
      columnWidth: 260
    },
    {
      name: 'receivedAt',
      label: 'Received At',
      type: 'dateTime',
      required: false,
      readOnly: true,
      columnWidth: 175
    },
    {
      name: 'orderType',
      label: 'Order Type',
      type: 'objectType',
      masterFilter: ['purchaseOrder', 'salesOrder'],
      required: true
    },

    {
      name: 'order',
      label: 'Order',
      type: 'object',
      showHyperlink: true,
      objectType: (objectData) => {
        return objectData?.orderType
      },
      required: true,
      columnWidth: 200
    },
    {
      name: 'shipment',
      label: 'Shipment',
      type: 'object',
      objectType: 'shipment',
      showHyperlink: true,
      required: false,
      columnWidth: 250,
      readOnly: (objectData) => {
        return objectData?.state?.type != 'draft'
      },
      masterFilter: (objectData) => {
        return {
          order: objectData?.order?._id
        }
      }
    },
    {
      name: 'itemType',
      label: 'Item Type',
      type: 'objectType',
      masterFilter: ['part', 'packaging', 'filament', 'product'],
      required: true,
      columnWidth: 175
    },
    {
      name: 'item',
      label: 'Item',
      type: 'object',
      objectType: (objectData) => {
        return objectData?.itemType
      },
      required: true,
      showHyperlink: true,
      columnWidth: 300
    },
    {
      name: 'sku',
      label: 'Item SKU',
      type: 'object',
      objectType: (objectData) => {
        if (objectData?.itemType === 'filament') return 'filamentSku'
        if (objectData?.itemType === 'part') return 'partSku'
        if (objectData?.itemType === 'product') return 'productSku'
        return undefined
      },
      required: true,
      showHyperlink: true,
      columnWidth: 300,
      masterFilter: (objectData) => {
        if (objectData?.itemType === 'filament' && objectData?.item?._id) {
          return { filament: objectData.item._id }
        }
        if (objectData?.itemType === 'part' && objectData?.item?._id) {
          return { part: objectData.item._id }
        }
        if (objectData?.itemType === 'product' && objectData?.item?._id) {
          return { product: objectData.item._id }
        }
        return undefined
      }
    },
    {
      name: 'syncAmount',
      label: 'Sync Amount',
      type: 'select',
      columnWidth: 150,
      options: [
        { label: 'Item Cost', value: 'itemCost' },
        { label: 'Item Price', value: 'itemPrice' },
        { label: 'None', value: null }
      ],
      required: false
    },
    {
      name: 'itemAmount',
      label: 'Item Amount',
      type: 'number',
      required: true,
      prefix: '£',
      min: 0,
      step: 0.01,
      fixedNumber: 2,
      readOnly: (objectData) => {
        return objectData?.syncAmount != null
      },
      columnWidth: 150,
      value: (objectData) => {
        const sku = objectData?.sku
        const item = objectData?.item
        if (objectData?.syncAmount == 'itemCost') {
          const cost =
            sku && sku.overrideCost ? sku.cost : (item?.cost ?? sku?.cost)
          return cost ?? objectData?.itemAmount
        }
        if (objectData?.syncAmount == 'itemPrice') {
          if (sku && sku.overridePrice) {
            return sku.price ?? objectData?.itemAmount
          }
          const priceMode = item?.priceMode ?? sku?.priceMode
          const margin = item?.margin ?? sku?.margin
          const cost = item?.cost ?? sku?.cost
          if (priceMode == 'margin' && margin != null && cost != null) {
            return cost * (1 + margin / 100)
          }
          return item?.price ?? sku?.price ?? objectData?.itemAmount
        }
        return objectData?.itemAmount || undefined
      }
    },
    {
      name: 'quantity',
      label: 'Quantity',
      type: 'number',
      required: true,
      columnWidth: 150
    },
    {
      name: 'totalAmount',
      label: 'Total Amount',
      type: 'number',
      required: true,
      prefix: '£',
      min: 0,
      step: 0.01,
      columnWidth: 150,
      fixedNumber: 2,
      readOnly: true,
      value: (objectData) => {
        if (objectData?.itemAmount && objectData?.quantity) {
          return (
            (objectData?.itemAmount || 0) * (objectData?.quantity || 0)
          ).toFixed(2)
        } else {
          return 0
        }
      }
    },
    {
      name: 'taxRate',
      label: 'Tax Rate',
      type: 'object',
      objectType: 'taxRate',
      showHyperlink: true,
      columnWidth: 150,
      value: (objectData) => {
        const sku = objectData?.sku
        const item = objectData?.item
        if (objectData?.syncAmount == 'itemCost') {
          const source = sku && sku.overrideCost ? sku : item
          return source?.costTaxRate ?? sku?.costTaxRate ?? objectData?.taxRate
        }
        if (objectData?.syncAmount == 'itemPrice') {
          const source = sku && sku.overridePrice ? sku : item
          return (
            source?.priceTaxRate ?? sku?.priceTaxRate ?? objectData?.taxRate
          )
        }
        return objectData?.taxRate || undefined
      },
      readOnly: (objectData) => {
        return objectData?.syncAmount != null
      }
    },
    {
      name: 'totalAmountWithTax',
      label: 'Total Amount w/ Tax',
      type: 'number',
      required: true,
      fixedNumber: 2,
      readOnly: true,
      prefix: '£',
      min: 0,
      step: 0.01,
      columnWidth: 175,
      value: (objectData) => {
        const totalAmount = objectData?.itemAmount * objectData?.quantity || 0
        if (!totalAmount) return 0
        if (objectData?.taxRate?.rateType == 'percentage') {
          return (
            (totalAmount * (1 + objectData?.taxRate?.rate / 100)).toFixed(2) ||
            0
          )
        } else if (objectData?.taxRate?.rateType == 'amount') {
          return (totalAmount + objectData?.taxRate?.rate).toFixed(2) || 0
        }
        return totalAmount
      }
    },
    {
      name: 'invoicedAmount',
      label: 'Invoiced Amount',
      type: 'number',
      required: false,
      readOnly: true,
      prefix: '£',
      fixedNumber: 2,
      min: 0,
      step: 0.01,
      columnWidth: 150
    },
    {
      name: 'invoicedAmountWithTax',
      label: 'Invoiced Amount w/ Tax',
      type: 'number',
      required: false,
      readOnly: true,
      prefix: '£',
      fixedNumber: 2,
      min: 0,
      step: 0.01,
      columnWidth: 200
    },
    {
      name: 'invoicedQuantity',
      label: 'Invoiced Quantity',
      type: 'number',
      required: false,
      readOnly: true,
      columnWidth: 150
    },
    {
      name: 'invoicedAmountRemaining',
      label: 'Remaining Invoiced Amount',
      type: 'number',
      required: false,
      readOnly: true,
      prefix: '£',
      min: 0,
      step: 0.01,
      columnWidth: 225,
      fixedNumber: 2
    },
    {
      name: 'invoicedAmountWithTaxRemaining',
      label: 'Remaining Invoiced Amount w/ Tax',
      type: 'number',
      required: false,
      readOnly: true,
      prefix: '£',
      min: 0,
      fixedNumber: 2,
      step: 0.01,
      columnWidth: 275
    },
    {
      name: 'invoicedQuantityRemaining',
      label: 'Remaining Invoiced Quantity',
      type: 'number',
      required: false,
      readOnly: true,
      columnWidth: 225
    }
  ]
}
