import {
    Filter, Sort, ExcelExport, Page, Toolbar, Inject, ColumnChooser, ColumnsDirective, Freeze, ColumnDirective, Resize,
  } from '@syncfusion/ej2-react-treegrid';
  import {
   filesService, reviewsService,
  } from '../../services/dataManager';
  import {TreeGridComponent} from  '@syncfusion/ej2-react-treegrid';
//  import { convertDate } from '../../services/luxonHelper';
import { TooltipComponent } from '@syncfusion/ej2-react-popups';
  import {
    formatBytes, getViewerUrl, getReviewUrl, getProjectFilesPageUrl, getPortalFilesUrl,
  } from '../../services/utils/helpers';
  import {
    useCallback, useEffect, useRef, useState,
  } from 'react';
  import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
//  import ButtonComponent from '@CubeComponents/form/ButtonComponent';
//  import { BUTTON_TYPES } from '@CubeComponents/constants/globalVariable';
  import css from '../Files/Files.module.css';
  import {  useParams } from 'react-router-dom';
//  import ToolTipComponent from '../../cubeComponent/html/tooltip';
//  import UsernameTagComponent from '../../cubeComponent/html/usernameTag';
  import {
   Query, Predicate, DataManager, WebMethodAdaptor,
  } from '@syncfusion/ej2-data';
//  import { conversionStatusTemplate, getNameInitials } from '../../services/utils/helpers';
  import { BiLinkExternal } from 'react-icons/bi';
//  import { getStatusBtnStyle } from '../Reviews/ReviewsHelper';
   import { getFilesGridColumns, getFilesGridToolbar } from '../../services/utils/helpers';
//  import ReviewsIcon from '../../assets/icons/Review.svg';
import { DropDownListComponent as SyncfusionDropDownListComponent, DropDownListModel } from '@syncfusion/ej2-react-dropdowns';
//  import DropDownListComponent from '../../cubeComponent/form/DropdownListComponent';
  // import AutoCompleteComponent from '../../cubeComponent/form/AutoCompleteComponent';
  import { AutoCompleteComponent } from '@syncfusion/ej2-react-dropdowns';
//  import useDebounce from '../Search/useDebounce';
//  import EditIcon from '@Components/StickySidebarViewer/assets/EditIcon';
  import axiosWrapper from '../../services/axiosWrapper';
  import { useDispatch } from 'react-redux';
//  import { showToastNotification } from '../../actions/toast';
//  import { TOAST_TYPE_ERROR } from '../../services/constants';
//  import FileVersion from '@Components/FileVersion/FileVersion';
import { useNavigate, useSearchParams } from 'react-router-dom';
  
  const FilesGrid = ({ showProjectID = false, showMPMRCLColumns = false, projectId = "653a2c15a6b7c9ea70eda04f" }) => {
    //const navigate = useNavigate();
    const initialFilesCount = 10;
    const dispatch = useDispatch();
    const urlParams = new URLSearchParams(location.search);
  
    const pageSettings = { pageSizes: true, pageSize: 10 };
    const filterSettings = { type: 'Menu' };
    const filesGrid = useRef(null);
    const params = useParams();
    const autoCompleteRef = useRef(null);
    const [showProperties, setShowProperties] = useState(false);
    const [selectedFileData, setSelectedFileData] = useState([]);
  
    const [searchParams] = useSearchParams();
  
    const getDefaultQueryValue = () => {
      const query = projectId ? new Query().addParams('projectId', projectId) : new Query();
      return query;
    };
  
    const [userQuery, setUserQuery] = useState(getWhereClause(searchParams.get('search')));
    const [isAutoCompleteCreated, setIsAutoCompleteCreated] = useState(false);
    const [isGridRendered, setIsGridRendered] = useState(true);
  
    const gridCreated = () => {
      setIsGridRendered(true);
    };
  
    function getWhereClause(value) {
      const query = getDefaultQueryValue();
  
      if (value !== null) {
        const predicate = new Predicate('fileName', 'contains', value);
        query.where(predicate);
      }
  
      return query;
    }
  
    const getUrl = (searchValue) => {
      let url = projectId ? getProjectFilesPageUrl(projectId) : getPortalFilesUrl();
  
      if (searchValue !== '') {
        url = url.concat(`&search=${searchValue}`);
      }
  
      return url;
    };
  
    //const debouncedProjectsDataFilter = useDebounce((e) => {
    //  const query = getWhereClause(e.text).take(initialFilesCount);
    //  e.updateData(filesService, query);
  
    //  const filesUrl = getUrl(e.text);
    //  navigate(filesUrl);
    //}, 100);
  
    //const handleSelect = (e) => {
    //  const selectedItem = e.itemData;
    //  const searchParam = selectedItem ? selectedItem.fileName : '';
    //  const filesUrl = getUrl(searchParam);
    //  navigate(filesUrl);
    //};
  
    const onFilteringProjects = (e) => {
      e.preventDefaultAction = true;
      debouncedProjectsDataFilter(e);
    };
  
    const autoCompleteCreated = () => {
      setIsAutoCompleteCreated(true);
    };
  
    const searchTemplate = () => (
      <div>
        <AutoCompleteComponent
          ref={autoCompleteRef}
          id="filesAutocomplete"
          autofill
          created={autoCompleteCreated}
          dataSource={filesService}
          fields={{ value: 'fileName' }}
          placeholder="Search Files"
          filtering={onFilteringProjects}
        //  select={handleSelect}
        />
      </div>
    );
  
    const excelExportTemplate = () => (
  <div className={css.toolbarButtomCustom}>
      <ButtonComponent id="excel_export">
        <span className={css.flexRowStart}>
          {/*<EditIcon size="15" className={css.toolbarBtnImg} />*/}
          Excel Export
        </span>
      </ButtonComponent>
    </div>
  );
  
    const toolbar = getFilesGridToolbar({ searchTemplate, excelExportTemplate });
  
    const treeGridExpanding = (args) => {
      const query = args.row.closest('.e-grid').ej2_instances[0].query;
      const { params } = query;
  
      const findGetReviewsListParam = params.find((param) => param.key === 'getReviewsList');
  
      if (!findGetReviewsListParam) {
        params.push({ key: 'getReviewsList', value: true });
      }
    };
  
    const treeGridAfterExpand = (args) => {
      const query = args.row.closest('.e-grid').ej2_instances[0].query;
      const { params } = query;
  
      const index = params.findIndex((param) => param.key === 'getReviewsList');
  
      if (index !== -1) {
        params.splice(index, 1);
      }
    };
  
    const actionBegin = (args) => {
      console.log(args);
    };
  
    const actionComplete = (args) => {
      console.log(args);
    };
  
    useEffect(() => {
      if (isGridRendered) {
        filesGrid.current.query = userQuery;
  
        if (Array.isArray(filesGrid.current.dataSource) && !filesGrid.current.dataSource.length) {
          filesGrid.current.dataSource = filesService;
        }
      }
    }, [userQuery, isGridRendered]);
  
    //useEffect(() => {
    //  setTimeout(() => {
    //    if (autoCompleteRef.current) {
    //      autoCompleteRef.current.value = searchParams.get('search');
    //      autoCompleteRef.current.setInputValue(searchParams.get('search'));
    //    }
    //  }, 2000);
    //}, []);
  
    //useEffect(() => {
    //  setUserQuery(getWhereClause(searchParams.get('search')));
    //}, [searchParams.get('search')]);
  
    //useEffect(() => {
    //  if (isAutoCompleteCreated && autoCompleteRef.current) {
    //    // autoCompleteRef.current.setInputValue(searchParams.get('search'))
    //  }
    //}, [isAutoCompleteCreated, searchParams.get('search')]);
  
    const formatDate = (params) => {
      if (params.resourceType === 'RESOURCE_TYPE_FILE') {
        //const dateFormat = convertDate(Number(params.createdDate), 'dateForTooltip');
        return (
          <>
            < TooltipComponent position="BottomCenter" >
              {/*{convertDate(Number(params.createdDate), 'dateForText')}*/}
            </ TooltipComponent>
          </>
        );
      }
  
      return '';
    };
  
    const userAvatar = (args) => {
      if (args.resourceType === 'RESOURCE_TYPE_FILE') {
        let profile = null;
        let userInitial = null;
  
        if (args.createdBy.profilePic) {
          profile = `fileSystemServer/getImage/profile/${args.createdBy.userId}`;
        }
  
        else {
        //  userInitial = getNameInitials(args.createdBy);
        }
  
        const fullName = `${args.createdBy.firstName} ${args.createdBy.lastName}`;
  
        //return (
        //  <div>
        //    <UsernameTagComponent
        //      profilePicKey={profile}
        //      nameInitial={userInitial}
        //      isCircle
        //      size="XS"
        //      userName={fullName}
        //      borderRadius="var(--size-14)"
        //      userNameBackground="#f0f5f9"
        //      iconBgColor="var(--system-colour-2)"
        //    />
        //  </div>
        //);
      }
  
      return '';
    };
  
    const fileNameTemplate = (args) => {
      const { fileName } = args;
  
      return (
        < TooltipComponent position="RightCenter" content={fileName}>
          <p>{fileName}</p>
        </ TooltipComponent>
      );
    };
  
    const fileTypeTemplate = (params) => {
      if (params.resourceType === 'RESOURCE_TYPE_FILE') {
        const fileName = params.fileName;
  
        if (fileName.split('.').length == 1) {
          return ('');
        }
  
        const fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
        return (fileType.toUpperCase());
      }
  
      return '';
    };
  
    const versionTemplate = (params) => {
      if (params.resourceType === 'RESOURCE_TYPE_FILE' && params.fileVersionNumber) {
        return `V${params.fileVersionNumber}`;
      }
  
      return '';
    };
  
    const statusInReviewTemplate = (args) => {
      if (!args.statusInReviews?._id) {
        return '-';
      }
  
      const { name, category } = args.statusInReviews;
      const style = ''
      // getStatusBtnStyle(category);
  
      return (
        <p className={css.fileStatusFromReview} style={style}>
          {name}
        </p>
      );
    };
  
    const dropdownItemTemplate = (args) => {
      const style = getStatusBtnStyle(args.category);
  
      return (
        <div className={css.itemTemplateWrapper}>
          <span style={style} className={css.itemTemplateContainer}>
            {args.name}
          </span>
        </div>
      );
    };
  
    const statusInReviewFilterTemplate = (args) => (
      <DropDownListComponent
        dataSource={getPortalLevelStatusListService}
        itemTemplate={dropdownItemTemplate}
        fields={{ value: '_id', text: 'name' }}
        buttonType={BUTTON_TYPES.BACKGROUND_BUTTON}
        value={args.statusInReviews}
      />
    );
  
    const fileIdTemplate = (params) => {
      if (params.resourceType === 'RESOURCE_TYPE_FILE' && params.file?.space?.project?.projectId) {
        return `${params.file?.space?.project?.projectId}-${params.file.indexAtProjectLevel}`;
      }
  
      return '';
    };
  
    const handleFileOpenClick = (params) => {
      const { _id: fileVersionId, file } = params;
      const url = getViewerUrl({ fileVersionId, spaceId: file?.space?.id, projectId });
  
      window.open(url, '_blank');
    };
  
    const handleReviewOpenClick = (args) => {
      const { spaceId, projectId, _id: reviewId } = args;
      const url = getReviewUrl(projectId, spaceId, reviewId);
  
      window.open(url, '_blank');
    };
  
    const openResourceTemplate = (params) => {
      if (params.resourceType === 'RESOURCE_TYPE_FILE') {
        return (
          <div onClick={() => handleFileOpenClick(params)} className={css.fileOpenIcon}>
            <BiLinkExternal />
          </div>
        );
      }
  
      return (
        <div className="justify-center flex cursor-pointer" onClick={() => handleReviewOpenClick(params)}>
          <img src={ReviewsIcon} alt="logo" className={css.reviewIcon} />
        </div>
      );
    };
  
    const fileSizeTemplate = (args) => {
      if (args.resourceType === 'RESOURCE_TYPE_FILE' && args.size) {
        const size = formatBytes(args.size);
        return size;
      }
  
      return '';
    };
  
    const reviewSerialIdTemplate = (args) => {
      const { serialId } = args;
  
      if (serialId === 'Varies' || serialId === '') {
        return serialId;
      }
  
      return <p>{`RE - ${serialId}`}</p>;
    };
  
    const reviewNameTemplate = (args) => {
      const { reviewName } = args;
      return reviewName;
    };
  
    const workflowTemplate = (args) => {
      const { workflow } = args;
  
      if (workflow === 'Varies' || workflow === '') {
        return workflow;
      }
  
      return workflow.name;
    };
  
    const currentReviewLevelSerialTemplate = (args) => {
      const { currentReviewLevel } = args;
  
      if (currentReviewLevel === 'Varies' || currentReviewLevel === '') {
        return currentReviewLevel;
      }
  
      if (currentReviewLevel) {
        return <p>{`Level ${currentReviewLevel.serial}`}</p>;
      }
  
      return '-';
    };
  
    const currentReviewLevelNameTemplate = (args) => {
      const { currentReviewLevel } = args;
  
      if (currentReviewLevel === 'Varies' || currentReviewLevel === '') {
        return currentReviewLevel;
      }
  
      if (currentReviewLevel) {
        return <p>{currentReviewLevel.title}</p>;
      }
  
      return '-';
    };
    let queryClone;
  
    async function toolbarClickHandler(args) {
      if (filesGrid.current && args.item.id.includes('excel_export')) {
        filesGrid.current.toolbarModule.enableItems(['excel_export'], false);
        filesGrid.current.showSpinner();
        //const userQuery = new Query()
        //  .requiresCount(true);
        //if (!urlParams.get('byPortal')) {
        //  userQuery.addParams('projectId', params.projectId);
        //}
  
        // filesGrid.current.query = userQuery;
        //const properties = {
        //  dataSource: filesService,
        //  fileName: 'ABCD.xlsx',
        //  query: userQuery,
        //};
  
        filesGrid.current.query = new Query().addParams('projectId', '653a2c15a6b7c9ea70eda04f')
        filesGrid.current.excelExport();
      }
    }
  
     function excelExportComplete() {
      if (filesGrid.current) {
        filesGrid.current.toolbarModule.enableItems(['excel_export'], true);
        filesGrid.current.hideSpinner();
        filesGrid.current.query = userQuery;
      }
     }
  
    const reviewCreatedDateTemplate = (args) => {
      if (args.reviewCreatedDate === 'Varies' || args.reviewCreatedDate === '') {
        return args.reviewCreatedDate;
      }
  
    //  const dateFormat = convertDate(Number(args.reviewCreatedDate), 'dateForTooltip');
  
      return (
        <>
          < TooltipComponent position="BottomCenter" >
            {/*{convertDate(Number(args.reviewCreatedDate), 'dateForText')}*/}
          </ TooltipComponent>
        </>
      );
    };
  
    const filesGridColumns = getFilesGridColumns({
      openResourceTemplate, fileIdTemplate, fileNameTemplate, fileTypeTemplate, fileSizeTemplate, userAvatar, formatDate,  versionTemplate, statusInReviewTemplate, statusInReviewFilterTemplate, reviewSerialIdTemplate, reviewNameTemplate, workflowTemplate, currentReviewLevelSerialTemplate, currentReviewLevelNameTemplate, reviewCreatedDateTemplate, showProjectID, showMPMRCLColumns,
    });
  
    const rowDeselected = () => {
      setSelectedFileData([]);
      setShowProperties(false);
    };
  
    const rowSelected = async (args) => {
      if (!args.data.hasOwnProperty('parentFileVersionId')) {
        const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/fileOperations/getDirectoryDataOfFile`, {
          value: {
            where: [{
              field: 'fileVersionId',
              value: args.data._id,
            }],
          },
        });
        if (Array.isArray(response.data)) {
          setSelectedFileData(response.data);
          setShowProperties(true);
        }
        else {
        //  dispatch(
        //    showToastNotification({
        //      content: 'Something went wrong',
        //      type: TOAST_TYPE_ERROR,
        //    }),
        //  );
        }
      }
    };
  
    const getFilesGrid = useCallback(() => (
      <TreeGridComponent
        ref={filesGrid}
        pageSettings={pageSettings}
        dataSource={filesService}
        filterSettings={filterSettings}
        toolbar={toolbar}
        allowExcelExport
        toolbarClick={toolbarClickHandler}
        excelExportComplete={excelExportComplete}
        allowFiltering
        allowSorting={false}
        created={gridCreated}
        allowPaging
        rowHeight={68}
        height="100%"
        allowResizing
        rowSelected={rowSelected}
        rowDeselected={rowDeselected}
        query={userQuery}
        idMapping="_id"
        actionBegin={actionBegin}
        actionComplete={actionComplete}
        beforeSend={actionBegin}
        treeColumnIndex={2}
        parentIdMapping="parentFileVersionId"
        hasChildMapping="hasChild"
        expanding={treeGridExpanding}
        expanded={treeGridAfterExpand}
      >
        <ColumnsDirective>
          {filesGridColumns.map((column) => <ColumnDirective key={`columnDirective_${column.field}`} {...column} />)}
        </ColumnsDirective>
  
        <Inject services={[Filter, ExcelExport, Page, Resize, Freeze, Toolbar]} />
      </TreeGridComponent>
    ), []);
  
    return (
      <div className="flex gap-4 h-full">
        {getFilesGrid()}
        {showProperties && (
          <FileVersion
            selectedSpaceTypeInFileManager="this"
            selectedFile={selectedFileData}
          />
        )}
      </div>
    );
  };
  
  export default FilesGrid;
  