
import { useParams } from 'react-router-dom';
import './index.css';
import * as React from 'react';
import { useEffect } from 'react';
import {
    GanttComponent,
    Inject,
    ColumnDirective,
    ColumnsDirective,
    Edit,
    RowDD,
    Selection,
    Toolbar,
    DayMarkers,
    Filter,
    Sort,
    Resize,
    VirtualScroll,
    CriticalPath,
    HolidaysDirective, HolidayDirective,
    AddDialogFieldsDirective,
    AddDialogFieldDirective,
    EditDialogFieldsDirective,
    EditDialogFieldDirective
} from '@syncfusion/ej2-react-gantt';
import { getDataManagerObj, performGanttOperationsUrl } from '../../services/dataManager';
import { Query } from '@syncfusion/ej2-data';
import {data} from './data'
const Gant = () => {

    const [finalData, setfinalData] = React.useState({});

    // const performGanttOperationsService = getDataManagerObj(performGanttOperationsUrl, processResponseFun);
    const taskFields = {
        id: 'TaskID',
        name: 'TaskName',
        startDate: 'StartDate',
        endDate: 'EndDate',
        duration: 'Duration',
        progress: 'Progress',
        taskType: 'taskTypeId',
        actualStartDate: 'actualStartDate',
        actualEndDate: 'actualEndDate',
        dependency: 'Predecessor',
        child: 'SubTasks',
        notes: 'info',
        resourceInfo: 'resources',
    };
    const splitterSettings = {
        columnIndex: 2,
        position: '40%',
    };

    const dataGrid = React.useRef();

    const timelineSettings = {
        topTier: {
            unit: 'Week',
            format: 'MMM dd, y',
        },
        bottomTier: {
            unit: 'Day',
        },
    };

    const labelSettings = {
        leftLabel: 'TaskName',
        rightLabel: '${Progress}%  ${resources}',
    };


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

    const formatTaskID = (data) => {
        let taskId;

        if (data?.taskData?.TaskDisp) {
            taskId = `${data?.taskData?.TaskDisp}`;
        }
        else {
            const counter = data?.taskData?.TaskID ?? '0';
            taskId = `TSK-${String(counter).padStart(4, '0')}`;
        }

        const itemsLinked = data.taskData?.linkedBoqItems;

        return (
            <div className="flex justify-between items-center">
                <span>{taskId}</span>
                {Array.isArray(itemsLinked) && itemsLinked.length > 0 && <IconComponent cssClass="cursor-pointer" name="details" onClick={(args) => showTaskItems(args, data.taskData)} />}
            </div>
        );
    };

    useEffect(() => {
        if(dataGrid.current)
        {
            const tempData = processResponseFun(data);
            // setfinalData(tempData);
            dataGrid.current.dataSource = tempData; 
        }
    }, [dataGrid.current]);

    function processResponseFun(args) {
        if (args.count && args.result) {
            const finalData = arrangeData(args.result);
            args.result = finalData;
            return args;
        }
        return args;
    }

    function modifyData(data) {
        const tempSet = new Set([...data.resources]);
        const resources = Array.from(tempSet);
        if (data.SubTasks.length) {
            const arrangedData = arrangeData(data.SubTasks);
            data.SubTasks = arrangedData;
        }
        return {
            ...data,
            resources,
            StartDate: data.StartDate ? new Date(data.StartDate) : null,
            EndDate: data.EndDate ? new Date(data.EndDate) : null,
            actualStartDate: data.actualStartDate ? new Date(data.actualStartDate) : null,
            actualEndDate: data.actualEndDate ? new Date(data.actualEndDate) : null,
        };
    };

    function arrangeData(data) {
        const newData = data.map((data) => {
            const modifiedData = modifyData(data);
            return modifiedData;
        });
        return newData;
    };

    const taskTypeTemplate = (args) => (
        // <DropDownListComponent
        //   dataSource={taskTypeService}
        //   fields={{ value: '_id', text: 'name' }}
        //   value={args.taskTypeId}
        //   onChange={(event) => handleTaskTypeChange(event, args)}
        //   query={taskTypeQuery}
        //   showClearButton
        // />
        'sdf'
    );
    const url = useParams();

    // const ganttQuery = new Query().addParams('scheduleId', '668e4fa4e7caa0afb3da4a1b').addParams('projectId', '64fab271224fa87c5f9c3179')
    //     .addParams('spaceId', '65000aa7224fa87c5f26d939');

    const editSettings = {
        allowAdding: !url.contractId,
        allowEditing: !url.contractId,
        allowDeleting: true,
        allowTaskbarEditing: !url.contractId,
        showDeleteConfirmDialog: !url.contractId,
    };

    const gridLines = 'Both';

    const toolbar = [
        ...(!url.contractId) ? ['Add',
            {
                text: 'Import',
                tooltipText: 'Import Excel',
                prefixIcon: 'e-add',
                id: 'excel_import',
            }] : [{
                text: 'Attach Tasks',
                prefixIcon: 'e-link',
                id: 'attach_tasks_contract',
            }],
        ...!url.contractId ? [{
            text: 'Remove',
            prefixIcon: 'e-delete',
            id: 'Editing_delete',
        }, 'Edit', 'Update', 'Cancel', 'Indent', 'Outdent']
            : [{
                text: 'Un-link',
                prefixIcon: 'e-break',
                id: 'un-link-from-contract',
                disabled: true,
            }],
        'ExpandAll', 'CollapseAll', 'ZoomIn', 'ZoomOut', 'ZoomToFit',

        ...(url.contractId) ? [] : [{
            text: 'Add Existing Tasks',
            tooltipText: 'Task Creation',
            prefixIcon: 'e-add',
            id: 'custom_createUnAsTsk',
        }],
        ...(url.contractId) ? [{
            text: 'Link BOQ Items',
            tooltipText: 'Link BOQ Items',
            prefixIcon: 'e-link',
            id: 'link_boq_items',
            disabled: true,
        }] : [],
        // ...(layout.INSPECTION?.ENABLE && url.contractId) ? [{
        //   text: 'Create Inspection',
        //   prefixIcon: 'e-description',
        //   id: 'create_inspection',
        // }] : [],
        // ...(layout.PROGRESS_UPDATES?.ENABLE && url.contractId) ? [{
        //   text: 'Update Site Progress',
        //   prefixIcon: 'e-description',
        //   id: 'create_progressUpdates',
        // }] : [],
        // ...(layout.PROGRESS_UPDATES?.ENABLE && url.contractId) ? [{
        //   text: 'Change Order',
        //   prefixIcon: 'e-description',
        //   id: 'change_order',
        // }] : [],
    ];

    const toolbarClickHandler = async (args) => {
        if (args.item.properties.id === 'custom_createUnAsTsk') {
            setTaskModal(true);
        }
        if (args.item.properties.id === 'attach_tasks_contract') {
            props.attachTaskModalState();
        }
        else if (args.item.properties.id === 'link_boq_items') {
            setShowBoqModal(true);
        }
        else if (args.item.properties.id === 'un-link-from-contract') {
            showWarningModal('unLinkTask');
        }
        else if (args.item.properties.id === 'excel_import') {
            fetchData();
        }
        // else if (args.item.properties.id === 'create_inspection') {
        //   setShowFormFloxwCreationModal({ status: true, category: formCategories.inspection });
        // }
        // else if (args.item.properties.id === 'create_progressUpdates') {
        //   setShowFormFlowCreationModal({ status: true, category: formCategories.progressUpdates });
        // }
        // else if (args.item.properties.id === 'change_order') {
        //   setShowFormFlowCreationModal({ status: true, category: formCategories.changeOrder });
        // }
    };

    const resourceFields = {
        id: '_id',
        name: 'name',
    };


    return (
        <div style={{ height: '100%', overflow: 'auto' }}>
            <GanttComponent
                ref={dataGrid}
                id="SplitTasks"
                dataSource={finalData}
                treeColumnIndex={1}
                labelSettings={labelSettings}
                allowSelection={true}
                highlightWeekends={true}
                // enableVirtualization
                // enableTimelineVirtualization
                taskFields={taskFields}
                splitterSettings={splitterSettings}
                height="100%"
                filterSettings={FilterOption}
                allowUnscheduledTasks={true}
                dayWorkingTime={[{ from: 8, to: 12 },
                { from: 13, to: 17 }]}
                allowRowDragAndDrop
                showColumnMenu={false}
                taskMode="Auto"
                allowResizing
                dateFormat="MMM dd y, hh:mm a"
                loadingIndicator={{ indicatorType: 'Spinner' }}
                allowFiltering
                timelineSettings={timelineSettings}
                editSettings={editSettings}
                gridLines={gridLines}
                selectionSettings={{ enableToggle: true }}
                // includeWeekend
                workWeek={['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Sunday']}
                toolbar={toolbar}
                toolbarClick={toolbarClickHandler}
                resourceFields={resourceFields}
                // query={ganttQuery}
                // autoCalculateDateScheduling={true}
                // enableVirtualMaskRow={false}
            >
                <ColumnsDirective>
                    <ColumnDirective field="TaskID" width="110" isPrimaryKey filter={FilterOption} template={formatTaskID} allowEditing={false} />
                    <ColumnDirective field="TaskName" headerText="Title" width="200" clipMode="EllipsisWithTooltip" />
                    <ColumnDirective field="StartDate" type="date" filter={FilterOption} />
                    <ColumnDirective field="EndDate" type="date" filter={FilterOption} />
                    <ColumnDirective field="Duration" filter={FilterOption} />
                    <ColumnDirective field="actualStartDate" editType="datetimepickeredit" headerText="Actual Start Date" />
                    <ColumnDirective field="actualEndDate" editType="datetimepickeredit" headerText="Actual End Date" />
                    <ColumnDirective field="taskTypeId" template={taskTypeTemplate} allowEditing={false} headerText="Task Type" />
                    <ColumnDirective field="Progress" filter={FilterOption} />
                </ColumnsDirective>
                <AddDialogFieldsDirective>
            <AddDialogFieldDirective type="General" headerText="General" />
            <AddDialogFieldDirective type="Dependency" />
            <AddDialogFieldDirective type="Resources" />
            {/* <AddDialogFieldDirective type="Notes" /> */}
          </AddDialogFieldsDirective>
          <EditDialogFieldsDirective>
            <EditDialogFieldDirective type="General" headerText="General" />
            <EditDialogFieldDirective type="Dependency" />
            <EditDialogFieldDirective type="Resources" />
            {/* <EditDialogFieldDirective type="Notes" /> */}
          </EditDialogFieldsDirective>
                <Inject
                    services={[
                        Edit,
                        RowDD,
                        Selection,
                        Toolbar,
                        DayMarkers,
                        Filter,
                        Sort,
                        Resize,
                        VirtualScroll,
                        CriticalPath,
                    ]}
                />
            </GanttComponent>
        </div>
    );
};
export default Gant;
