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_AUDIO_FILES');

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

      editable: hasUpdatePermission,
    },

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

      editable: false,
      sortable: false,
      renderCell: (params: GridValueGetterParams) => (
        <>
          {dataFormatter
            .filesFormatter(params.row.original_file)
            .map((link) => (
              <button
                key={link.publicUrl}
                onClick={(e) => saveFile(e, link.publicUrl, link.name)}
              >
                {link.name}
              </button>
            ))}
        </>
      ),
    },

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

      editable: false,
      sortable: false,
      renderCell: (params: GridValueGetterParams) => (
        <>
          {dataFormatter
            .filesFormatter(params.row.processed_file)
            .map((link) => (
              <button
                key={link.publicUrl}
                onClick={(e) => saveFile(e, link.publicUrl, link.name)}
              >
                {link.name}
              </button>
            ))}
        </>
      ),
    },

    {
      field: 'user',
      headerName: 'User',
      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('users'),
      valueGetter: (params: GridValueGetterParams) =>
        params?.value?.id ?? params?.value,
    },

    {
      field: 'organization',
      headerName: 'Organization',
      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('organizations'),
      valueGetter: (params: GridValueGetterParams) =>
        params?.value?.id ?? params?.value,
    },

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

      editable: hasUpdatePermission,

      type: 'dateTime',
      valueGetter: (params: GridValueGetterParams) =>
        new Date(params.row.uploaded_at),
    },

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

      editable: hasUpdatePermission,

      type: 'dateTime',
      valueGetter: (params: GridValueGetterParams) =>
        new Date(params.row.processed_at),
    },

    {
      field: 'actions',
      type: 'actions',
      minWidth: 30,
      headerClassName: 'datagrid--header',
      cellClassName: 'datagrid--cell',
      getActions: (params: GridRowParams) => {
        return [
          <ListActionsPopover
            onDelete={onDelete}
            itemId={params?.row?.id}
            pathEdit={`/audio_files/audio_files-edit/?id=${params?.row?.id}`}
            pathView={`/audio_files/audio_files-view/?id=${params?.row?.id}`}
            key={1}
            hasUpdatePermission={hasUpdatePermission}
          />,
        ];
      },
    },
  ];
};
