import React from 'react'
import axios from 'axios'
import { GridColDef, GridRowParams, GridValueGetterParams } from '@mui/x-data-grid'
import { saveFile } from '../../helpers/fileSaver'
import dataFormatter from '../../helpers/dataFormatter'
import ListActionsPopover from '../ListActionsPopover'
import { hasPermission } from '../../helpers/userPermissions'

type Params = (id: string) => void

export const loadColumns = async (
  onDelete: Params,
  entityName: string,
  user,
): Promise<GridColDef[]> => {
  async function callOptionsApi(entityName: string) {
    if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) {
      return []
    }

    const { data } = await axios(`/${entityName}/autocomplete?limit=100`)
    return data
  }

  const hasUpdatePermission = hasPermission(user, 'UPDATE_QUOTES')

  return [
    {
      field: 'quote_number',
      headerName: 'Quote number',
      flex: 1,
      minWidth: 170,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'account',
      headerName: 'Buyer account',
      flex: 1.2,
      minWidth: 210,
      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('accounts'),
      valueGetter: (params: GridValueGetterParams) => params?.value?.id ?? params?.value,
    },
    {
      field: 'location',
      headerName: 'Ship-to location',
      flex: 1.1,
      minWidth: 200,
      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('locations'),
      valueGetter: (params: GridValueGetterParams) => params?.value?.id ?? params?.value,
    },
    {
      field: 'requested_by',
      headerName: 'Requested by',
      flex: 1,
      minWidth: 180,
      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('users'),
      valueGetter: (params: GridValueGetterParams) => params?.value?.id ?? params?.value,
    },
    {
      field: 'owner',
      headerName: 'Sales owner',
      flex: 1,
      minWidth: 180,
      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('users'),
      valueGetter: (params: GridValueGetterParams) => params?.value?.id ?? params?.value,
    },
    {
      field: 'requested_at',
      headerName: 'Requested at',
      flex: 1,
      minWidth: 170,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
      type: 'dateTime',
      valueGetter: (params: GridValueGetterParams) => new Date(params.row.requested_at),
    },
    {
      field: 'expires_at',
      headerName: 'Expires at',
      flex: 1,
      minWidth: 170,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
      type: 'dateTime',
      valueGetter: (params: GridValueGetterParams) => new Date(params.row.expires_at),
    },
    {
      field: 'quote_status',
      headerName: 'Status',
      flex: 0.9,
      minWidth: 150,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'quote_total',
      headerName: 'Quote total',
      flex: 0.9,
      minWidth: 150,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
      type: 'number',
    },
    {
      field: 'notes',
      headerName: 'Internal notes',
      flex: 1.2,
      minWidth: 220,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: hasUpdatePermission,
    },
    {
      field: 'attachments',
      headerName: 'Attachments',
      flex: 1,
      minWidth: 180,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      editable: false,
      sortable: false,
      renderCell: (params: any) => (
        <>
          {dataFormatter.filesFormatter(params.row.attachments).map((link) => (
            <button key={link.publicUrl} onClick={(e) => saveFile(e, link.publicUrl, link.name)}>
              {link.name}
            </button>
          ))}
        </>
      ),
    },
    {
      field: 'actions',
      type: 'actions',
      minWidth: 56,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      getActions: (params: GridRowParams) => {
        return [
          <div key={params?.row?.id}>
            <ListActionsPopover
              onDelete={onDelete}
              itemId={params?.row?.id}
              pathEdit={`/quotes/quotes-edit/?id=${params?.row?.id}`}
              pathView={`/quotes/quotes-view/?id=${params?.row?.id}`}
              hasUpdatePermission={hasUpdatePermission}
            />
          </div>,
        ]
      },
    },
  ]
}
