import React from 'react';
import BaseIcon from '../BaseIcon';
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
import axios from 'axios';
import {
    GridActionsCellItem,
    GridRowParams,
    GridValueGetterParams,
} from '@mui/x-data-grid';
import ImageField from '../ImageField';
import {saveFile} from "../../helpers/fileSaver";
import dataFormatter from '../../helpers/dataFormatter'
import DataGridMultiSelect from "../DataGridMultiSelect";
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_TENANTS')
    
    return [
        
        {
            field: 'name',
            headerName: 'Tenantname',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            
        },
        
        {
            field: 'slug',
            headerName: 'Tenantslug',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            
        },
        
        {
            field: 'legal_name',
            headerName: 'Legalname',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            
        },
        
        {
            field: 'primary_domain',
            headerName: 'Primarydomain',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            
        },
        
        {
            field: 'timezone',
            headerName: 'Timezone',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            
        },
        
        {
            field: 'default_currency',
            headerName: 'Defaultcurrency',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            
        },
        
        {
            field: 'is_active',
            headerName: 'Isactive',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            
            editable: hasUpdatePermission,
            
            type: 'boolean',
          
        },
        
        {
            field: 'organizations',
            headerName: 'Linked organizations',
            flex: 1.2,
            minWidth: 220,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            editable: false,
            sortable: false,
            type: 'singleSelect',
            valueFormatter: ({ value }) =>
                dataFormatter.organizationsManyListFormatter(value).join(', '),
            renderCell: (params: any) => {
                const organizations = Array.isArray(params.value) ? params.value : [];

                if (!organizations.length) {
                    return (
                        <div className='py-2 text-sm text-gray-500 dark:text-dark-600'>
                            No linked organizations
                        </div>
                    );
                }

                const preview = organizations.slice(0, 2);
                const remainingCount = organizations.length - preview.length;

                return (
                    <div className='flex min-w-0 flex-wrap items-center gap-1 py-2'>
                        <span className='rounded-full bg-blue-50 px-2 py-1 text-xs font-semibold text-blue-700 dark:bg-blue-950/40 dark:text-blue-100'>
                            {organizations.length} linked
                        </span>
                        {preview.map((organization: any) => (
                            <span
                                key={organization.id || organization.name}
                                className='max-w-full truncate rounded-full bg-gray-100 px-2 py-1 text-xs font-medium text-gray-700 dark:bg-dark-700 dark:text-gray-100'
                                title={organization.name}
                            >
                                {organization.name}
                            </span>
                        ))}
                        {remainingCount > 0 ? (
                            <span className='rounded-full bg-gray-100 px-2 py-1 text-xs font-medium text-gray-700 dark:bg-dark-700 dark:text-gray-100'>
                                +{remainingCount} more
                            </span>
                        ) : null}
                    </div>
                );
            },
            renderEditCell: (params) => (
                <DataGridMultiSelect {...params} entityName={'organizations'}/>
            ),
          
        },
        
        {
            field: 'properties',
            headerName: 'Properties',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            editable: false,
            sortable: false,
            type: 'singleSelect',
            valueFormatter: ({ value }) =>
                dataFormatter.propertiesManyListFormatter(value).join(', '),
            renderEditCell: (params) => (
                <DataGridMultiSelect {...params} entityName={'properties'}/>
            ),
          
        },
        
        {
            field: 'audit_logs',
            headerName: 'Auditlogs',
            flex: 1,
            minWidth: 120,
            filterable: false,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
          
            editable: false,
            sortable: false,
            type: 'singleSelect',
            valueFormatter: ({ value }) =>
                dataFormatter.audit_logsManyListFormatter(value).join(', '),
            renderEditCell: (params) => (
                <DataGridMultiSelect {...params} entityName={'audit_logs'}/>
            ),
          
        },
        
        {
            field: 'actions',
            type: 'actions',
            minWidth: 30,
            headerClassName: 'datagrid--header',
            cellClassName: 'datagrid--cell',
            getActions: (params: GridRowParams) => {
                
               return [
                   <div key={params?.row?.id}>
                      <ListActionsPopover
                      onDelete={onDelete}
                      itemId={params?.row?.id}
                      pathEdit={`/tenants/tenants-edit/?id=${params?.row?.id}`}
                      pathView={`/tenants/tenants-view/?id=${params?.row?.id}`}
                      
                      hasUpdatePermission={hasUpdatePermission}
                      
                    />
                   </div>,
                  ]
            },
        },
    ];
};
