import React from 'react'
import axios from 'axios'
import { GridRowParams, GridValueGetterParams } from '@mui/x-data-grid'
import ImageField from '../ImageField'
import dataFormatter from '../../helpers/dataFormatter'
import DataGridMultiSelect from '../DataGridMultiSelect'
import ListActionsPopover from '../ListActionsPopover'
import { hasPermission } from '../../helpers/userPermissions'
import { canManagePlatformUserFields, canManageUserRecord } from '../../helpers/manageableUsers'

type Params = (id: string) => void

export const loadColumns = async (
  onDelete: Params,
  entityName: string,
  user,
) => {
  const canManagePlatformFields = canManagePlatformUserFields(user)

  async function callOptionsApi(targetEntityName: string) {
    if (!hasPermission(user, `READ_${targetEntityName.toUpperCase()}`)) {
      return []
    }

    const params = new URLSearchParams({ limit: '100' })

    if (targetEntityName === 'roles') {
      params.set('assignableOnly', 'true')
      params.set('includeHighTrust', canManagePlatformFields ? 'true' : 'false')
    }

    try {
      const data = await axios(`/${targetEntityName}/autocomplete?${params.toString()}`)
      return data.data
    } catch (error) {
      console.error(`Failed to load ${targetEntityName} options for users grid:`, error)
      return []
    }
  }

  const hasUpdatePermission = hasPermission(user, 'UPDATE_USERS')
  const canEditRecord = (record) => hasUpdatePermission && canManageUserRecord(user, record)

  return [
    {
      field: 'firstName',
      headerName: 'First Name',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'lastName',
      headerName: 'Last Name',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'phoneNumber',
      headerName: 'Phone Number',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'email',
      headerName: 'E-Mail',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'disabled',
      headerName: 'Disabled',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
      type: 'boolean',
    },
    {
      field: 'avatar',
      headerName: 'Avatar',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: false,
      sortable: false,
      renderCell: (params: GridValueGetterParams) => (
        <ImageField
          name={'Avatar'}
          image={params?.row?.avatar}
          className='w-24 h-24 mx-auto lg:w-6 lg:h-6'
        />
      ),
    },
    {
      field: 'app_role',
      headerName: 'App Role',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
      sortable: false,
      type: 'singleSelect',
      getOptionValue: (value: any) => value?.id,
      getOptionLabel: (value: any) => value?.label,
      valueOptions: await callOptionsApi('roles'),
      valueGetter: (params: GridValueGetterParams) => params?.value?.id ?? params?.value,
    },
    {
      field: 'custom_permissions',
      headerName: 'Custom Permissions',
      flex: 1,
      minWidth: 160,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: false,
      sortable: false,
      hide: !canManagePlatformFields,
      type: 'singleSelect',
      valueFormatter: ({ value }) => dataFormatter.permissionsManyListFormatter(value).join(', '),
      renderEditCell: (params) => <DataGridMultiSelect {...params} entityName={'permissions'} />,
    },
    {
      field: 'organizations',
      headerName: 'Organizations',
      flex: 1,
      minWidth: 160,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: canManagePlatformFields && hasUpdatePermission,
      sortable: false,
      hide: !canManagePlatformFields,
      type: 'singleSelect',
      getOptionValue: (value: any) => value?.id,
      getOptionLabel: (value: any) => value?.label,
      valueOptions: canManagePlatformFields ? await callOptionsApi('organizations') : [],
      valueGetter: (params: GridValueGetterParams) => params?.value?.id ?? params?.value,
    },
    {
      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={`/${entityName}/${entityName}-edit/?id=${params?.row?.id}`}
            pathView={`/${entityName}/${entityName}-view/?id=${params?.row?.id}`}
            hasUpdatePermission={canEditRecord(params?.row)}
          />
        </div>,
      ],
    },
  ]
}
