import {
  useCallback, useEffect, useRef, useState,
} from 'react';
import {
  ColumnsDirective,
  ColumnDirective,
  Page,
  Selection,
  Inject,
  Filter,
  Sort,
  Resize,
  Toolbar,
  ColumnChooser,
  Edit,
  VirtualScroll,
  DetailRow,
  GridComponent
} from '@syncfusion/ej2-react-grids';
import { L10n } from '@syncfusion/ej2-base';
import { DropDownListComponent, DropDownTreeComponent, AutoCompleteComponent } from '@syncfusion/ej2-react-dropdowns';
import { getProjectsStatusesData, saveProjectStatus } from '../../actions/bcfData';
import axiosWrapper from '../../services/axiosWrapper';
import css from './grid-overview.module.css';
import { Query } from '@syncfusion/ej2-data';
import { projectsService } from '../../services/dataManager';
import * as ReactDOM from 'react-dom';
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';

const ProjectsList = (props) => {
  const convertDate = () => ''
  const classificationData = []
  const projectsStatuses = useSelector((state) => Object.keys(state.projectsStatuses).map((value) => {
    const { name } = state.projectsStatuses[value];
    return { name, value };
  }));
  const dispatch = useDispatch();
  const history = useHistory();
  const [openAddProjectModal, setOpenAddProjectModal] = useState(false);
  const [currentSelectedProject, setCurrentSelectedProject] = useState({});
  const [editMode, setEditMode] = useState(false);


  L10n.load({
    'en-US': {
      grid: {
        AddFormTitle: 'Create New Project',
        EditFormTitle: 'Edit Project ',
        CancelButton: 'Discard',
        ConfirmDelete: 'Are you sure you want to Delete Project ?',
      },
    },
  });
  const validationRules = { required: true, regex: '[^ ]' };
  const editSettings = {
    allowEditing: !!props.allowEditing,
    allowAdding: true,
    allowDeleting: true,
    mode: 'Dialog',
    showDeleteConfirmDialog: true,
  };

  const [addProjectData, setAddProjectData] = useState({});

  const filterSettings = {
    type: 'Menu',
  };

  const dateFilter = {
    type: 'Menu',
  };
  const dataGrid = props.forwardedRef ? props.forwardedRef : useRef();
  const pageSettings = { pageSizes: true, pageSize: 10 };

  const toolbarOptions = [
    {
      text: 'Create', prefixIcon: 'e-add', htmlAttributes: { 'data-testid': 'addProjectButton' }, id: 'add_Project',
    },
    { text: 'ColumnChooser', htmlAttributes: { 'data-testid': 'columnChooserProjectButton' } },
  ];
  props.allowEditing ? toolbarOptions.push({ text: 'Edit', htmlAttributes: { 'data-testid': 'editProjectButton' }, id: 'edit_Project' }) : null;

  const empTemplate = (props) => {
    let imageUrl = ''
    return (
      <>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img src={imageUrl} alt="Logo" width="50px" height="40px" />
          <span style={{ paddingLeft: '8px', paddingTop: '8px' }}>{props.description}</span>
        </div>
      </>
  );
};

  const handleChange = (e, props) => {
    dispatch(
      saveProjectStatus({
        id: props.data.id,
        status: e.target.value,
      }),
    );
  };

  const handleChangeProjectStatus = (e) => {
    setAddProjectData({
      ...addProjectData,
      status: e.value,
    });
  };

  const handleClassificationChange = (e) => {
    setAddProjectData({
      ...addProjectData,
      classification: e.value.join(','),
    });
  };

  const statusEditTemplate = () => (
    <DropDownListComponent
      fields={{ text: 'name', value: 'value' }}
      dataSource={projectsStatuses}
      floatLabelType="Always"
      placeholder="Status"
      onChange={handleChangeProjectStatus}
    />
  );

  useEffect(() => {
    dataGrid.current?.toolbarModule?.enableItems(['edit_Project'], false);
    dispatch(getProjectsStatusesData());
  }, []);

  const selectingEvents = (params) => {
    setCurrentSelectedProject({ data: params.data });
    if (dataGrid.current) {
      if (dataGrid.current.getSelectedRowIndexes().length == 1) {
        dataGrid.current.toolbarModule.enableItems(['edit_Project'], true);
      } else {
        dataGrid.current.toolbarModule.enableItems(['edit_Project'], false);
      }
    }
  };

  const toolbarClickHandler = (params) => {
    if (params.item.properties.id === 'custom_deleteProject') {
      const deleteData = {
        projectId: dataGrid.current.getSelectedRecords()[0].id,
      };
      axiosWrapper.post(`https://api.qa.cube.ms/projects/deleteProjectsData`, deleteData).then((res) => {
        deleteRow(dataGrid.current.getSelectedRows()[0]);
      });
    }
    if (params.item.properties.id === 'add_Project') {
      setOpenAddProjectModal(true);
    }
    if (params.item.properties.id === 'edit_Project') {
      setEditMode(true);
      setOpenAddProjectModal(true);
    }
  };

  const actionBegin = async (args) => {
    if (args.requestType == 'filtering' && args.type == 'actionBegin' && args.action == 'filter') {
      args.columns.forEach((column, index) => {
        if (column.properties.field == 'classification') {
          let classifcationId = classificationData.find((classification) => classification.name == column.properties.value);
          classifcationId = classifcationId.id;

          args.columns[index].properties.operator = 'contains';
          args.columns[index].properties.value = classifcationId;
        }
      });
    }

    if (args.requestType === 'filterchoicerequest' || args.requestType === 'filtersearchbegin') {
      args.filterChoiceCount = 10;
    }
  };

  const actionComplete = () => {
    dataGrid.current.columnModel.forEach((val) => {
      if (val.field == 'createdByName' || val.field == 'createdDate' || val.field === 'sharedWith') {
        val.visible = true;
      }
    });
  };

  const formatDate = (props) => {
    const dateFormat = convertDate(Number(props.createdDate), 'dateForTooltip');
    return (
      <div style={{ width: 'fit-content' }}>
        {/* <ToolTipComponent showTipPointer={false} position="BottomCenter" content={dateFormat}>
          <span>
            {' '}
            {convertDate(Number(props.createdDate), 'dateForText')}
            {' '}
          </span>
        </ToolTipComponent> */}
      </div>
    );
  };

  const recordClick = (args) => {
    if (args.rowData) {
      if (args.column && args.cellIndex !== 0 && args.column.field != 'status') {
        if (props.enableProjectRedirectionOnClick) {
          history.push(`/project/${args.rowData.id}/projectdashboard`);
        }
      }
    }
  };

  const classificationTemplate = (args) => (
    <DropDownTreeComponent
      floatLabelType="Always"
      fields={{
        dataSource: classificationData, value: 'id', parentValue: 'pid', text: 'name', hasChildren: 'hasChild',
      }}
      showCheckBox
      mode="Delimiter"
      placeholder="Classification"
      popupHeight="200px"
      change={handleClassificationChange}
      value={args?.classification?.split(',')}
    />
  );

  const classificationViewTemplate = (args) => {
    if (!args.classification) {
      return '';
    }
    return args.classification
      .split(',')
      .map((data) => {
        const filteredData = classificationData.find((classification) => classification.id == data);
        return filteredData?.name;
      })
      .join(',');
  };
  const dialogClose = () => {
    setOpenAddProjectModal(false);
    setEditMode(false);
    dataGrid.current.refresh();
  };

  const classificationFilterTemplate = () => (
    <AutoCompleteComponent
      id="positionAutocomplete"
      autofill
      dataSource={classificationData}
      fields={{ value: 'name' }}
      placeholder="Classification"
    />
  );

  const queryCellInfo = (args) => {
    if (args.column.field === 'status') {
      ReactDOM.render(
        <DropDownListComponent
          fields={{ text: 'name', value: 'value' }}
          value={args.data.statusId}
          dataSource={projectsStatuses}
          onChange={(e) => handleChange(e, args)}
        />,
        args.cell,
      );
    }
  };

  const getGridComponent = () => (
      <GridComponent
        enableStickyHeader
        pageSettings={pageSettings}
        toolbar={toolbarOptions}
        editSettings={editSettings}
        dataSource={projectsService}
        enableHover
        rowHeight={68}
        height="100%"
        toolbarClick={toolbarClickHandler}
        ref={dataGrid}
        filterSettings={filterSettings}
        allowFiltering
        allowSorting
        allowPaging
        rowSelected={selectingEvents}
        rowDeselected={selectingEvents}
        actionBegin={actionBegin}
        actionComplete={actionComplete}
        recordClick={recordClick}
        showDeleteConfirmDialog
        showColumnChooser
        className={css.tableWrapper}
        allowResizing
        childGrid={props.childGrid ? props.childGrid : null}
        query={new Query().addParams('userId', "326f3326-9c5d-4bf2-bcd3-f54bab187265")}
        queryCellInfo={queryCellInfo}
        statelessTemplates={['directiveTemplates']}
      >
        <ColumnsDirective>
          <ColumnDirective type="checkbox" width="50" />
          <ColumnDirective field="projectId" visible headerText="Project ID" validationRules={validationRules} width="130" isPrimaryKey />
          <ColumnDirective
            field="description"
            headerText="Project Name"
            validationRules={validationRules}
            width="230"
            clipMode="EllipsisWithTooltip"
            template={empTemplate}
          />
          <ColumnDirective
            field="createdDate"
            headerText="Created On"
            width="150"
            filter={dateFilter}
            type="date"
            template={formatDate}
          />
          <ColumnDirective field="createdByName" headerText="Created by" />
          <ColumnDirective
            field="status"
            headerText="Status"
            editTemplate={statusEditTemplate}
            filterTemplate={statusEditTemplate}
            width="150"
          />
          <ColumnDirective field="address" headerText="Address" width="150" clipMode="EllipsisWithTooltip" />
          <ColumnDirective field="location" headerText="Location" width="150" filter={{ type: 'Menu' }} clipMode="EllipsisWithTooltip" />
        </ColumnsDirective>
        <Inject services={[Resize, DetailRow, VirtualScroll, Filter, Page, Sort, Toolbar, ColumnChooser, Selection, Edit, ColumnChooser]} />
      </GridComponent>
    )

  return (
    <>
      <div className={`${css.controlPane} ${props.useMargin ? css.marginClass : ''}`}>
        {getGridComponent()}
      </div>
    </>
  );
};

export default ProjectsList;
