import React from 'react';
import axios from 'axios';
import { GridColDef, GridRowParams } from '@mui/x-data-grid';
import ListActionsPopover from '../ListActionsPopover';

import { hasPermission } from '../../helpers/userPermissions';
import { logger } from '../../lib/logger';

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

export const loadColumns = async (
  onDelete: Params,
  entityName: string,

  user: unknown,
): Promise<GridColDef[]> => {
  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) {
      logger.error(
        'Failed to fetch options',
        error instanceof Error ? error : { error },
      );
      return [];
    }
  }

  const hasUpdatePermission = hasPermission(
    user,
    'UPDATE_PRESIGNED_URL_REQUESTS',
  );

  return [
    {
      field: 'project',
      headerName: 'Project',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,

      sortable: false,
      type: 'singleSelect' as const,
      getOptionValue: (value: any) => value?.id,
      getOptionLabel: (value: any) => value?.label,
      valueOptions: await callOptionsApi('projects'),
      valueGetter: (value: { id?: string } | string | null) =>
        (typeof value === 'object' && value !== null ? value?.id : value) ??
        value,
    },

    {
      field: 'user',
      headerName: 'User',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,

      sortable: false,
      type: 'singleSelect' as const,
      getOptionValue: (value: any) => value?.id,
      getOptionLabel: (value: any) => value?.label,
      valueOptions: await callOptionsApi('users'),
      valueGetter: (value: { id?: string } | string | null) =>
        (typeof value === 'object' && value !== null ? value?.id : value) ??
        value,
    },

    {
      field: 'purpose',
      headerName: 'Purpose',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,
    },

    {
      field: 'asset_type',
      headerName: 'Assettype',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,
    },

    {
      field: 'requested_key',
      headerName: 'Requestedkey',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,
    },

    {
      field: 'mime_type',
      headerName: 'MIMEtype',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,
    },

    {
      field: 'requested_size_mb',
      headerName: 'Requestedsize(MB)',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,

      type: 'number',
    },

    {
      field: 'expires_at',
      headerName: 'Expiresat',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,

      type: 'dateTime' as const,
      valueGetter: (_value, row) => new Date(row.expires_at),
    },

    {
      field: 'status',
      headerName: 'Status',
      flex: 1,
      minWidth: 120,
      filterable: false,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',

      editable: hasUpdatePermission,
    },

    {
      field: 'actions',
      type: 'actions' as const,
      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={`/presigned_url_requests/presigned_url_requests-edit/?id=${params?.row?.id}`}
              pathView={`/presigned_url_requests/presigned_url_requests-view/?id=${params?.row?.id}`}
              hasUpdatePermission={hasUpdatePermission}
            />
          </div>,
        ];
      },
    },
  ];
};
