import React from 'react'
import { GridRowParams } from '@mui/x-data-grid'

import LinkedTenantsPreview from './LinkedTenantsPreview'
import ListActionsPopover from '../ListActionsPopover'
import { hasPermission } from '../../helpers/userPermissions'
import { OrganizationTenantSummaryMap } from '../../helpers/organizationTenants'

type Params = (id: string) => void

export const loadColumns = async (
  onDelete: Params,
   _entityName: string,
  user,
  linkedTenantSummaries: OrganizationTenantSummaryMap = {},
  canViewTenants = true,
) => {
  const hasUpdatePermission = hasPermission(user, 'UPDATE_ORGANIZATIONS')

  return [
    {
      field: 'name',
      headerName: 'Name',
      flex: 1,
      minWidth: 180,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'linkedTenants',
      headerName: 'Linked tenants',
      flex: 1.2,
      minWidth: 220,
      filterable: false,
      sortable: false,
      editable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      renderCell: (params: any) => (
        <div className='flex min-h-[52px] items-center py-2'>
          <LinkedTenantsPreview
            summary={linkedTenantSummaries[params?.row?.id]}
            compact
            emptyMessage={canViewTenants ? 'Not linked yet' : 'Tenant access restricted'}
          />
        </div>
      ),
    },
    {
      field: 'actions',
      type: 'actions',
      minWidth: 30,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      getActions: (params: GridRowParams) => [
        <div key={params?.row?.id}>
          <ListActionsPopover
            onDelete={onDelete}
            itemId={params?.row?.id}
            pathEdit={`/organizations/organizations-edit/?id=${params?.row?.id}`}
            pathView={`/organizations/organizations-view/?id=${params?.row?.id}`}
            hasUpdatePermission={hasUpdatePermission}
          />
        </div>,
      ],
    },
  ]
}
