Untitled

 avatar
unknown
plain_text
a month ago
40 kB
5
Indexable
import { DeleteOutlined, EditOutlined, MoreOutlined } from '@ant-design/icons';
import SearchIcon from '@mui/icons-material/Search';
import { CircularProgress, Button as MuiButton, Tooltip, Zoom } from '@mui/material';
import Button from '@mui/material/Button';
import Pagination from '@mui/material/Pagination';
import ThemeProvider from '@mui/material/styles/ThemeProvider';
import { DataGridPro } from '@mui/x-data-grid-pro';
import { Input, Popconfirm, Select, Dropdown, Menu } from 'antd';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import { secureApi } from '../../Config/api';
import theme1 from '../../themes/theme1';
import TabContext from '@mui/lab/TabContext';
import TabList from '@mui/lab/TabList';
import TabPanel from '@mui/lab/TabPanel';
import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import { Form } from 'antd';
import Grid from '@mui/material/Grid';
import './Projects.css';
import { FiFileText } from 'react-icons/fi';
import { LuUsers } from 'react-icons/lu';
import { VscLiveShare } from 'react-icons/vsc';
import { styled } from '@mui/material/styles';
import { tooltipClasses } from '@mui/material/Tooltip';
import { useNavigate } from 'react-router-dom';
import { capitalizeName, diTimeFormat, errorMessage, successMessage, stringToBoolean } from '../../utils/helpers';
import { allPaths, TOOLTIP_DELAY, TOOLTIPS } from '../../utils/constants';
import { X, Check, Globe, Lock } from 'lucide-react';
import ShareProjectModal from '../../Components/CustomInstructionsModal/ShareProjectModal';
import { GET } from '../../utils/apis';
import { HiDotsVertical } from "react-icons/hi";
import { IoArchiveOutline } from "react-icons/io5";
import { RxCross2 } from "react-icons/rx";
import DataTable from '@aretec-inc/di-table';


// import { VscLiveShare } from 'react-icons/vsc';

const CreateProjectModal = ({ isOpen, onClose, user_id, handleNewProjectAdd, selectedInstruction }) => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const formRef = useRef(null);
  const { TextArea } = Input;
  const [visibility, setVisibility] = useState('private');
  const [tags, setTags] = useState([]);
  const [newTagName, setNewTagName] = useState('');
  const [isAddingTag, setIsAddingTag] = useState(false);
  const DI_PROJECT_URL = useSelector((state) => state?.appReducer?.DI_PROJECT_URL);
  const IS_INDIVIDUAL = useSelector((state) => state?.appReducer?.IS_INDIVIDUAL);
  const [approvedUser, setApprovedUser] = useState([]);

  const getallTags = useCallback(() => {
    secureApi
      .get(`${DI_PROJECT_URL}/api/v1.0/tag/get`, { withCredentials: true })
      .then((data) => {
        if (data?.success) {
          setTags(data?.result);
        } else {
          errorMessage(data?.message);
        }
      })
      .catch(() => {
        errorMessage('Failed to fetch tags');
      });
  }, [DI_PROJECT_URL]);

  const getAllGuestAccounts = () => {
    secureApi
      .get(`${GET?.GET_ALL_GUEST_ACCOUNTS}`, { withCredentials: true })
      .then((data) => {
        if (data?.success) {
          console.log('data?.accounts', data?.accounts);

          setApprovedUser(data?.accounts || []);
        }
      })
      .catch((err) => {
        errorMessage(err?.response?.data?.message);
      });
  };

  useEffect(() => {
    getAllGuestAccounts();
  }, []);

  useEffect(() => {
    getallTags();
  }, [getallTags]);

  useEffect(() => {
    form.setFieldsValue({
      name: selectedInstruction?.name,
      description: selectedInstruction?.description,
      org_id: IS_INDIVIDUAL ? selectedInstruction?.user_id : '',
    });
    const updatedTags = tags?.map((tag) => {
      const isActive = selectedInstruction?.tags?.some((selectedTag) => selectedTag.tag_id === tag.id);
      return { ...tag, active: isActive };
    });
    setTags(updatedTags);

    setVisibility(IS_INDIVIDUAL ? 'public' : selectedInstruction?.visibility ? 'public' : 'private');
  }, [selectedInstruction, IS_INDIVIDUAL]);

  const onSubmit = (val) => {
    const body = {
      ...val,
      tags: tags.filter((tag) => tag.active).map((tag) => tag.name),
      visibility: visibility === 'private' ? false : true,
      user_id: IS_INDIVIDUAL ? (val?.org_id ?? user_id) : user_id,
    };
    delete body.org_id;
    setLoading(true);
    const apiEndpoint = selectedInstruction?.id ? 'update' : 'create';
    const apiUrl = `${DI_PROJECT_URL}/api/v1.0/project/${apiEndpoint}`;
    if (selectedInstruction?.id) {
      body.id = selectedInstruction.id;
    }

    secureApi
      .post(apiUrl, body, { withCredentials: true })
      .then((data) => {
        if (data?.success) {
          successMessage(data?.message);
          handleNewProjectAdd();
          form.resetFields();
          setVisibility('private');
          getallTags();
          onClose();
        } else {
          errorMessage(data?.message);
        }
      })
      .catch(() => {
        errorMessage('Project submission failed');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const toggleTag = (id) => {
    setTags(tags.map((tag) => (tag.id === id ? { ...tag, active: !tag.active } : tag)));
  };

  const addNewTag = () => {
    if (newTagName.trim() !== '') {
      setTags([...tags, { id: tags.length + 1, name: newTagName.trim(), active: true, custom: true }]);
      setNewTagName('');
      setIsAddingTag(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      addNewTag();
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setVisibility('private');
    onClose();
    getallTags();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center modal_zIndex">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-lg mx-6 sm:max-w-md md:max-w-lg lg:max-w-xl">
        <div className="px-6 pt-3 pb-3 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900 mb-0" id="modal-title">
              {selectedInstruction?.id ? 'Edit Project' : 'Create New Project'}
            </h2>
            <span onClick={onClose} className="text-gray-400 hover:text-gray-500 focus:outline-none">
              <X className="h-5 w-5" />
            </span>
          </div>
          <p className="mt-1 mb-0 text-sm text-gray-600">Set up a new project workspace for collaboration</p>
        </div>
        <div className="px-2">
          <div className="domain_form mt-0">
            <div className="w-100 px-3">
              <Form name="Custom" layout="vertical" encType="multipart/form-data" requiredMark form={form} onFinish={onSubmit} ref={formRef}>
                <Grid container spacing={1}>
                  <Grid item xs={12}>
                    <Form.Item
                      className='projact_error'
                      style={{ width: '100%' }}
                      name="name"
                      hasFeedback
                      label="Project Name"
                      rules={[{ required: true, message: 'Project Name is required' }]}
                    >
                      <Input className="login-input mb-0 pw-input antd-input-border-customize" />
                    </Form.Item>
                  </Grid>
                  <Grid className="text-area-error" item xs={12}>
                    <Form.Item label="Enter your Description" name="description">
                      <TextArea className="inst_box cus-ins" rows={3} />
                    </Form.Item>
                  </Grid>
                  {!selectedInstruction?.id &&
                    <Grid item xs={12}>
                      <div className="w-100">
                        <label className="block text-sm font-medium text-gray-700 mb-2">Project Visibility</label>
                        <div className="grid grid-cols-2 gap-3">
                          {!IS_INDIVIDUAL && (
                            <div
                              className={`border rounded-md p-3 cursor-pointer transition-colors duration-150 ${visibility === 'private' ? 'border-blue-500 bg-blue-50' : 'border-gray-200'}`}
                              onClick={() => setVisibility('private')}
                            >
                              <div className="flex items-center">
                                <div
                                  className={`h-4 w-4 rounded-full flex-none flex items-center justify-center ${visibility === 'private' ? 'bg-blue-600' : 'border border-gray-300'}`}
                                >
                                  {visibility === 'private' && <Check className="h-2.5 w-2.5 text-white" />}
                                </div>
                                <div className="ml-2 flex items-center">
                                  <Lock className="h-3.5 w-3.5 text-gray-500 mr-1" />
                                  <span className="text-sm font-medium text-gray-900">Private</span>
                                </div>
                              </div>
                            </div>
                          )}
                          <div
                            className={`border rounded-md p-3 cursor-pointer transition-colors duration-150 ${visibility === 'public' ? 'border-blue-500 bg-blue-50' : 'border-gray-200'}`}
                            onClick={() => setVisibility('public')}
                          >
                            <div className="flex items-center">
                              <div
                                className={`h-4 w-4 rounded-full flex-none flex items-center justify-center ${visibility === 'public' ? 'bg-blue-600' : 'border border-gray-300'}`}
                              >
                                {visibility === 'public' && <Check className="h-2.5 w-2.5 text-white" />}
                              </div>
                              <div className="ml-2 flex items-center">
                                <Globe className="h-3.5 w-3.5 text-gray-500 mr-1" />
                                <span className="text-sm font-medium text-gray-900">Public</span>
                              </div>
                            </div>
                          </div>
                          {IS_INDIVIDUAL && (
                            <div className="viewselection w-full pl-0">
                              <Form.Item label="" name="org_id">
                                <Select
                                  placeholder="Preferred Organization"
                                  className="projact_org"
                                  optionFilterProp="children"
                                  name="org_id"
                                  style={{ width: '100%' }}
                                  filterOption={(input, option) => (option?.organization_name ?? '')?.toLowerCase()?.includes(input?.toLowerCase())}
                                >
                                  {approvedUser?.map((account) => (
                                    <Option key={account?.guest_id} value={account?.guest_id}>
                                      {account?.organization_name}
                                    </Option>
                                  ))}
                                </Select>
                              </Form.Item>
                            </div>
                          )}
                        </div>

                      </div>
                    </Grid>
                  }
                  <Grid item xs={12}>
                    <div className="w-full">
                      <div className="flex">
                        <label className="block text-sm font-medium text-gray-700 mb-2">Project Tags</label>
                        <span className="text-gray-400 text-sm"> (Optional)</span>
                      </div>
                      <div className="flex flex-wrap gap-2 mb-2">
                        {tags?.map((tag) => (
                          <div
                            key={tag?.id}
                            className={`pl-3 pr-2 py-1 inline-flex items-center justify-between rounded-full text-sm cursor-pointer border ${tag?.active ? 'bg-blue-100 border-blue-300 text-blue-800' : 'bg-gray-100 border-gray-200 text-gray-600 hover:bg-gray-200'}`}
                            onClick={() => toggleTag(tag?.id)}
                          >
                            <span className='pr-2'>{tag?.name}</span>
                            {/* <RxCross2 /> */}

                          </div>
                        ))}
                        {!isAddingTag && (
                          <div
                            className="px-3 py-1 rounded-full text-sm cursor-pointer border border-dashed border-gray-300 text-gray-500 hover:bg-gray-50"
                            onClick={() => setIsAddingTag(true)}
                          >
                            + Add Tag
                          </div>
                        )}
                      </div>
                      {isAddingTag && (
                        <div className="flex items-center gap-2">
                          <input
                            type="text"
                            className="px-3 py-1 border rounded-full text-sm focus:outline-none focus:ring-1 focus:ring-blue-300"
                            placeholder="New tag name"
                            value={newTagName}
                            onChange={(e) => setNewTagName(e.target.value)}
                            onKeyPress={handleKeyPress}
                            autoFocus
                          />
                          <button className="px-3 py-1 blueAddbutton text-white rounded-full text-sm hover:bg-blue-600" onClick={addNewTag}>
                            Add
                          </button>
                          <button
                            className="px-2 py-1 cancelButon text-gray-500 rounded-full text-sm hover:text-gray-700"
                            onClick={() => {
                              setIsAddingTag(false);
                              setNewTagName('');
                            }}
                          >
                            Cancel
                          </button>
                        </div>
                      )}
                    </div>
                  </Grid>
                  <Grid item xs={12}>
                    <div className="button-list mt-2">
                      <Button
                        type="primary"
                        htmlType="submit"
                        className="domain-btn uploadbtndes mui_btn upl_btn_icon retention-history-button"
                        variant="contained"
                        block
                        size="large"
                        ghost
                        onClick={handleCancel}
                      >
                        Cancel
                      </Button>
                      <Button
                        type="primary"
                        className={`domain-btn uploadbtndes mui_btn upl_btn_icon retention-history-button adddatadomain`}
                        variant="contained"
                        block
                        loading={loading}
                        size="large"
                        ghost
                      >
                        {loading ? (
                          <>
                            <CircularProgress size={24} color="inherit" /> &nbsp; Save
                          </>
                        ) : (
                          'Confirm'
                        )}
                      </Button>
                    </div>
                  </Grid>
                </Grid>
              </Form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const Projects = () => {
  const navigate = useNavigate();
  const user = useSelector((state) => state?.authReducer?.user);
  const guest = useSelector((state) => state?.authReducer?.guest);
  const owner_id = guest?.owner_id || user?.user_id;
  const user_id = owner_id || guest?.id;
  const DI_PROJECT_URL = useSelector((state) => state?.appReducer?.DI_PROJECT_URL);
  let IS_CITATION_VIEW = useSelector((state) => state?.appReducer?.IS_CITATION_VIEW);
  IS_CITATION_VIEW = stringToBoolean(IS_CITATION_VIEW);
  const [listProjects, setListProjects] = useState([]);
  const [projectFilter, setProjectFilter] = useState({
    user_id: user_id,
    type: 'me',
    search: '',
    tags: [],
    page: 1,
    limit: 10,
    sort_by: 'created_at',
    sort_order: 'desc',
    is_archived: false,
    is_pagination: false,
    is_new_add: false,
  });
  const [loading, setLoading] = useState(false);
  const [pageNo, setPageNo] = useState(1);
  const [totalPageNo, setTotalPageNo] = useState(null);
  const [innerWidth, setInnerWidth] = useState(window.innerWidth);
  const [valueTab, setValueTab] = useState('1');
  const [noOfRows, setNoOfRows] = useState(10);
  const [search, setSearch] = useState('');
  const [rowSelectionModel, setRowSelectionModel] = useState([]);
  const [multiDeleleLoading, setMultiDeleteLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const FullDisplay = ({ data }) => <div>{Array.isArray(data) ? data?.join(', ') : String(data)}</div>;
  const [openShareModal, setOpenShareModal] = useState(false);
  const [selectedInstruction, setSelectedInstruction] = useState({});

  const columns = useMemo(
    () => [
      {
        field: 'name',
        header: 'Name',
        sortable: true,
        flex: 1,
        minWidth: 250,
        cell: ({ row }) => (
          <span onClick={!row?.is_archived ? () => handleOpen(row?.id) : undefined}
            style={{ cursor: !row?.is_archived ? 'pointer' : 'default' }}>
            <Tooltip title={row?.name} enterDelay={TOOLTIP_DELAY} enterNextDelay={TOOLTIP_DELAY} leaveDelay={0}>
              <p style={{ color: '#1890ff', margin: 0 }}>{row?.name?.length <= 50 ? row?.name : row?.name?.slice(0, 50) + '...'}</p>
            </Tooltip>
          </span>
        ),
      },
      {
        field: 'files',
        header: 'Total Files',
        flex: 0.5,
        minWidth: 100,
        cell: ({ row }) => (
          <div className="projectIcons">
            <FiFileText /> <span>{row?.files?.length || 0}</span>
          </div>
        ),
      },
      // {
      //   field: 'token_capacity',
      //   header: 'Capacity',
      //   flex: 1,
      //   minWidth: 150,
      //   cell: ({ row }) => (
      //     <div className="capacity-container">
      //       <div
      //         className="progress-bar"
      //         style={{
      //           width: ` ${row?.capacity || 0}%`,
      //           backgroundColor: '#1c7dff',
      //         }}
      //       ></div>
      //       <span>{row?.token_capacity || 0}%</span>
      //     </div>
      //   ),
      // },
      {
        field: 'owner',
        header: 'Owner',
        flex: 1,
        minWidth: 150,
        cell: ({ row }) => <div>{row?.owner?.name || ''}</div>,
      },
      {
        field: 'projectUsers',
        header: 'Shared With',
        flex: 0.5,
        minWidth: 100,
        cell: ({ row }) => (
          <div className="projectIcons">
            <LuUsers />
            <span>{row?.projectUsers.length || 0}</span>
          </div>
        ),
      },
      {
        field: 'tags',
        header: 'Tags',
        flex: 1,
        minWidth: 200,
        cell: (params) => {
          return !!params?.row?.tags?.length ? (
            params?.row?.tags?.length >= 4 ? (
              <>
                {params?.row?.tags?.slice(0, 2)?.map((v) => (
                  <div className="resp_width">
                    <CustomWidthTooltip arrow TransitionComponent={Zoom} title={<FullDisplay data={capitalizeName(v?.tag?.name)} />} interactive>
                      <span>{capitalizeName(v?.tag?.name)}</span>
                    </CustomWidthTooltip>
                  </div>
                ))}

                <div style={{ display: 'flex' }}>
                  <CustomWidthTooltip
                    arrow
                    TransitionComponent={Zoom}
                    title={<FullDisplay data={params.row?.tags?.slice(2).map((v) => v?.tag?.name)} />}
                    interactive
                  >
                    <span className="hover-underline marginbandt">{`+ ${params?.row?.tags?.length - 2} more`}</span>
                  </CustomWidthTooltip>
                </div>
              </>
            ) : (
              params?.row?.tags?.map(
                (v) =>
                  v &&
                  v !== null &&
                  v !== '' && (
                    <div className="resp_width">
                      <span>{v?.tag?.name?.toUpperCase()}</span>
                    </div>
                  ),
              )
            )
          ) : (
            <div className="resp_width">
              <span>{`N/A`}</span>
            </div>
          );
        },
      },
      {
        field: 'created_at',
        header: 'Last Updated',
        sortable: true,
        flex: 1,
        minWidth: 150,
        cell: (params) => diTimeFormat(params?.row?.created_at),
      },
      {
        field: 'action',
        header: 'Actions',
        minWidth: 60,
        sortable: false,
        flex: 1,
        resizable: false,
        cell: (params) => (
          <span
            style={{
              display: 'flex',
              justifyContent: 'start',
              alignItems: 'center',
            }}
            className="delete_domain_message"
          >
            <Dropdown
              overlay={
                <Menu>
                  {!params?.row?.is_archived &&
                    <>
                      <Menu.Item key="edit" onClick={() => handleEditProject(params?.row)}>
                        <EditOutlined /> Edit
                      </Menu.Item>
                      <Menu.Item key="delete">
                        <Popconfirm
                          title="Are you sure You want to delete this Project?"
                          okText="Yes"
                          cancelText="No"
                          onConfirm={() => handleDelete(params?.row?.id)}
                          okButtonProps={{
                            style: {
                              borderRadius: 5,
                            },
                          }}
                          cancelButtonProps={{
                            style: {
                              borderRadius: 5,
                            },
                          }}
                        >
                          <DeleteOutlined /> Delete
                        </Popconfirm>
                      </Menu.Item>
                      <Menu.Item key="share" onClick={() => shareModal(params?.row)}>
                        <VscLiveShare /> Share
                      </Menu.Item>
                    </>
                  }
                  <Menu.Item key="archive" onClick={() => handleArchive(params?.row?.id, params?.row?.is_archived)}>
                    <IoArchiveOutline /> {params?.row?.is_archived ? "UnArchive" : "Archive"}
                  </Menu.Item>

                </Menu>
              }
              trigger={['click']}
            >
              <Button type="default" style={{ border: 'none' }} >
                <HiDotsVertical />
              </Button>
            </Dropdown>
          </span>
        ),
      }
    ],
    [projectFilter],
  );

  useEffect(() => {
    window.addEventListener('resize', resizeWindow);

    return window.removeEventListener('resize', resizeWindow);
  }, []);

  const handleOpen = async (id) => {
    const path = allPaths?.PROJECT_OVERVIEW.replace(':id', id);
    navigate(path);
  };

  const getProjects = () => {
    setLoading(true);
    secureApi
      .get(
        `${DI_PROJECT_URL}/api/v1.0/project/get-projects?user_id=${user_id}&type=${projectFilter?.type}&search=${projectFilter?.search}&tags=${projectFilter?.tags}&page=${projectFilter?.page}&limit=${projectFilter?.limit}&sort_by=${projectFilter?.sort_by}&sort_order=${projectFilter?.sort_order}&is_archived=${projectFilter?.is_archived}&is_pagination=${projectFilter?.is_pagination}`,
        { withCredentials: true }
      )
      .then((data) => {
        if (data?.success) {
          setTotalPageNo(data.totalCount)
          setListProjects(data?.result);
        } else {
          errorMessage(data?.message);
        }
        setLoading(false);
      })
      .catch((e) => {
        errorMessage('Project submission failed');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    getProjects();
  }, [projectFilter]);

  const CustomWidthTooltip = styled(({ className, ...props }) => <Tooltip {...props} classes={{ popper: className }} placement="top" />)({
    [`& .${tooltipClasses.tooltip}`]: {
      maxWidth: 500,
      minWidth: 100,
      fontSize: 14,
    },
  });

  const resizeWindow = () => {
    setInnerWidth(window.innerWidth);
    setInnerWidth(window.innerHeight);
  };

  const getPage = (pageNumber) => {
    setPageNo(pageNumber);
    setProjectFilter({
      ...projectFilter,
      page: pageNumber,
    });
  };

  const handleChangeRowsPerPage = (value) => {
    setProjectFilter({
      ...projectFilter,
      limit: value,
      page: 1,
      limit: value,
    });
    setNoOfRows(value);
  };

  const handleDelete = (id) => {
    secureApi.delete(`${DI_PROJECT_URL}/api/v1.0/project/delete`, { project_ids: [id] }, { withCredentials: true }).then((data) => {
      if (data?.success) {
        setProjectFilter({
          ...projectFilter,
          page: 1,
        });
      } else {
        errorMessage(data?.message);
      }
    });
  };

  const handleArchive = (id, is_archived) => {
    setLoading(true);
    secureApi
      .post(`${DI_PROJECT_URL}/api/v1.0/project/update`, { id, is_archived: !is_archived }, { withCredentials: true })
      .then((data) => {
        if (data?.success) {
          successMessage(`Project ${!is_archived ? 'archived' : 'unarchived'} successfully`);
          setProjectFilter({
            ...projectFilter,
            page: 1,
          });
        } else {
          errorMessage(data?.message);
        }
      })
      .catch(() => {
        errorMessage('Project Archive failed');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const deleteMultipleProjects = () => {
    setMultiDeleteLoading(true);
    secureApi
      .delete(`${DI_PROJECT_URL}/api/v1.0/project/delete`, { project_ids: rowSelectionModel }, { withCredentials: true })
      .then((data) => {
        if (data?.success) {
          setProjectFilter({
            ...projectFilter,
            page: 1,
          });
        } else {
          errorMessage(data?.message);
        }
      })
      .finally(() => {
        setMultiDeleteLoading(false);
      });
  };

  const handleChangeTabs = (event, newValue) => {
    setValueTab(newValue);
    setProjectFilter({
      ...projectFilter,
      type: newValue === '1' ? 'me' : newValue === '2' ? 'all' : 'all',
      is_archived: newValue === '3' ? true : false,
      page: 1,
      search: '',
    });
  };

  const handleSearch = () => {
    setProjectFilter({
      ...projectFilter,
      search: search,
      page: 1,
    });
  };

  const handleNewProjectAdd = useCallback(() => {
    setProjectFilter({
      ...projectFilter,
      is_new_add: !projectFilter.is_new_add,
    });
    setSelectedInstruction({});
  }, []);

  const shareModal = (row) => {
    setSelectedInstruction(row);
    setOpenShareModal(true);
  };

  const handleEditProject = (row) => {
    setIsModalOpen(true);
    setSelectedInstruction(row);
  };

  const handleProjectModelClose = () => {
    setIsModalOpen(false);
    setSelectedInstruction({});
  };

  const handleShareProjectClose = (row) => {
    setSelectedInstruction({});
    setOpenShareModal(false);
  };


  return (
    <div className="">
      <div className="main_bg">
        <div style={{ paddingRight: '16px' }}>
          <div className="search_result_topProject">
            <div className="pdf_file_cont">
              <div style={{ marginTop: 0 }} className="searchContainer-setting">
                <div style={{ display: 'flex', flex: 1 }}>
                  {user?.role === 'admin' ?
                    <div
                      className="button-list"
                      style={{
                        justifyContent: 'start',
                        marginLeft: '10px',
                        marginTop: '0px',
                      }}
                    >
                      <Button
                        type="primary"
                        className={`domain-btn uploadbtndes mui_btn upl_btn_icon retention-history-button adddatadomain`}
                        variant="contained"
                        block
                        loading={false}
                        size="large"
                        ghost
                        data-testid={'next-or-register-btn'}
                        onClick={() => setIsModalOpen(true)}
                      >
                        Create Project
                      </Button>
                    </div>
                    : <></>
                  }
                  {rowSelectionModel && rowSelectionModel?.length > 0 ? (
                    <div className="selecteddelete">
                      <Popconfirm
                        title="Are you sure you want to delete the selected History?"
                        okText="Yes"
                        placement="topRight"
                        cancelText="No"
                        onConfirm={deleteMultipleProjects}
                        okButtonProps={{
                          style: {
                            borderRadius: 5,
                          },
                        }}
                        cancelButtonProps={{
                          style: {
                            borderRadius: 5,
                          },
                        }}
                      >
                        <MuiButton>
                          {!multiDeleleLoading ? (
                            <>
                              <DeleteOutlined style={{ marginRight: '5px' }} /> Delete
                            </>
                          ) : (
                            <>
                              <CircularProgress size={20} style={{ marginRight: '5px', color: 'black' }} /> Delete
                            </>
                          )}
                        </MuiButton>
                      </Popconfirm>
                    </div>
                  ) : null}
                </div>
                <Tooltip
                  title={TOOLTIPS?.history_search_bar}
                  enterDelay={TOOLTIP_DELAY}
                  enterNextDelay={TOOLTIP_DELAY}
                  leaveDelay={0}
                  placement="top"
                  arrow
                >
                  <div style={{ display: 'flex', justifyContent: 'end' }}>
                    <Input
                      type="text"
                      placeholder="Search"
                      className="login-input pw-input antd-input-border-customize"
                      value={search}
                      onChange={(e) => setSearch(e?.target?.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          handleSearch();
                        }
                      }}
                      allowClear
                      suffix={
                        <SearchIcon
                          style={{ cursor: 'pointer' }}
                          onClick={() => {
                            handleSearch();
                          }}
                        />
                      }
                    />
                  </div>
                </Tooltip>
              </div>
              <div className="">
                <Box sx={{ width: '100%', typography: 'body1' }}>
                  <TabContext value={valueTab}>
                    <Box
                      sx={{
                        borderBottom: 1,
                        borderColor: 'divider',
                        display: 'flex',
                        justifyContent: 'space-between',
                      }}
                    >
                      <TabList onChange={handleChangeTabs} aria-label="lab API tabs example">
                        <Tab className="topsettingtab" label="Your projects" value="1" />
                        <Tab className="topsettingtab" label="All projects" value="2" />
                        <Tab className="topsettingtab" label="Archived" value="3" />
                      </TabList>
                    </Box>
                    <TabPanel className="tabpanel-main" style={{ height: 'calc(100vh - 233px)' }} value={valueTab}>
                      <div className="tab-section-dtl">
                        {/* <ThemeProvider theme={theme1}> */}
                        <div className="doc_table hist-dynaminc hist-dynamincHeight">
                          <div style={{ background: '#fff', width: '100%', minHeight: 520, overflow: 'hidden' }}>
                            <DataTable
                              data={listProjects}
                              columns={columns}
                              totalRows={totalPageNo || 0}
                              // Features
                              loading={loading}
                              enableRowSelection={true}
                              enableSorting={true}
                              enablePagination={true}
                              // Pagination
                              pageSizeOptions={[
                                { value: 10, label: '10' },
                                { value: 20, label: '20' },
                                { value: 50, label: '50' },
                              ]}
                              showPageSizeSelector={true}
                              // Event handlers
                              onPageChange={getPage}
                              onPageSizeChange={handleChangeRowsPerPage}

                              onRowSelectionChange={(selectedIds) => {
                                const newSelection = {};
                                selectedIds.forEach((id) => {
                                  newSelection[id] = true;
                                });
                                setRowSelectionModel(selectedIds);
                              }}
                              // State
                              page={pageNo}
                              pageSize={noOfRows}
                              selectedRows={rowSelectionModel.reduce((acc, id) => {
                                acc[id] = true;
                                return acc;
                              }, {})}

                              // UI customization
                              className="data-contracts-datatable"
                              minHeight="400px"
                              emptyStateMessage="No Projects found"

                              variant="surface"
                            />
                          </div>
                          {/* <Grid container spacing={1}>   
                              <DataTable
                                data={listProjects}
                                columns={columns}
                                loading={loading}
                                localeText={{ noRowsLabel: 'No Projects Found' }}
                                onRowSelectionModelChange={(newRowSelectionModel) => {
                                  setRowSelectionModel(newRowSelectionModel);
                                }}
                                className="documentpage-width"
                                style={{
                                  background: '#fff',
                                  width: '100%',
                                  minHeight: 520,
                                  overflow: 'hidden',
                                }}
                              />
                            </Grid>
                            {projectFilter?.is_pagination && (
                              <div className="pagination-list pagination-list-end">
                                <Pagination
                                  color="primary"
                                  variant="outlined"
                                  shape="rounded"
                                  count={Math.ceil(totalPageNo / noOfRows)}
                                  page={pageNo}
                                  onChange={getPage}
                                />
                                <span className="rowsPerPage">
                                  <div>
                                    <p>Rows per page:</p>
                                  </div>
                                  <Select
                                    style={{
                                      width: 70,
                                      marginLeft: 5,
                                    }}
                                    value={noOfRows}
                                    optionFilterProp="children"
                                    onChange={handleChangeRowsPerPage}
                                    options={[
                                      {
                                        value: 10,
                                        label: 10,
                                      },
                                      {
                                        value: 20,
                                        label: 20,
                                      },
                                      {
                                        value: 50,
                                        label: 50,
                                      },
                                    ]}
                                  />
                                </span>
                              </div>
                            )} */}
                        </div>
                        {/* </ThemeProvider> */}
                      </div>
                    </TabPanel>
                  </TabContext>
                </Box>
              </div>
            </div>
          </div>
        </div>
      </div>
      <CreateProjectModal
        user_id={user_id}
        isOpen={isModalOpen}
        onClose={handleProjectModelClose}
        handleNewProjectAdd={handleNewProjectAdd}
        selectedInstruction={selectedInstruction}
      />
      <ShareProjectModal
        open={openShareModal}
        setOpen={handleShareProjectClose}
        name={selectedInstruction?.name}
        id={selectedInstruction?.id}
        instruction={selectedInstruction}
        getProjects={handleNewProjectAdd}
      />
    </div>
  );
};

export default Projects;
Editor is loading...
Leave a Comment