import React from 'react';
import axios from 'axios';
import {
    GridRowParams,
    GridValueGetterParams,
} from '@mui/x-data-grid';
import ListActionsPopover from '../ListActionsPopover';
import {hasPermission} from "../../helpers/userPermissions";

type Params = (id: string) => void;

export const loadColumns = async (
    onDelete: Params,
    entityName: string,
    user
) => {
    async function callOptionsApi(entityName: string) {
        if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
        try {
            const data = await axios(`/${entityName}/autocomplete?limit=100`);
            return data.data;
        } catch (error) {
            console.log(error);
            return [];
        }
    }
    
    const hasUpdatePermission = hasPermission(user, 'UPDATE_PROFILES')
    
    return [
        {
            field: 'name',
            headerName: 'Persona Name',
            flex: 1,
            minWidth: 150,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
            editable: hasUpdatePermission,
        },
        {
            field: 'occupation',
            headerName: 'Occupation',
            flex: 1,
            minWidth: 150,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
            valueGetter: (params: GridValueGetterParams) => 
                params.row.persona_data?.occupation || 'N/A',
        },
        {
            field: 'age',
            headerName: 'Age',
            flex: 0.5,
            minWidth: 80,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
            valueGetter: (params: GridValueGetterParams) => 
                params.row.persona_data?.age || '-',
        },
        {
            field: 'description',
            headerName: 'Summary',
            flex: 1.5,
            minWidth: 200,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
            editable: hasUpdatePermission,
        },
        {
            field: 'actions',
            type: 'actions',
            minWidth: 50,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
            getActions: (params: GridRowParams) => {
               return [
                   <div key={params?.row?.id}>
                      <ListActionsPopover
                        onDelete={onDelete}
                        itemId={params?.row?.id}
                        pathEdit={`/profiles/profiles-edit/?id=${params?.row?.id}`}
                        pathView={`/profiles/profiles-view/?id=${params?.row?.id}`}
                        hasUpdatePermission={hasUpdatePermission}
                      />
                   </div>,
                  ]
            },
        },
    ];
};