import React, { useEffect, useState, useCallback, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { connect, useDispatch } from 'react-redux'
import { Card, Table, Space, Modal, Switch, Tooltip } from 'antd'
import commonStyles from '../../../Utils/Common.less'
import AddNewButton from '../../../Components/AddNewButton'
import SearchInput from '../../../Components/SearchInput'
import type { ColumnsType, TableProps } from 'antd/es/table'
import {
    GetWorkflowList,
    GetWorkflowTypeList,
    SaveWorkflow,
    ActiveInactiveWorkflow,
    DeleteWorkflow,
} from '../../../Services/Workflow'
import type { TableParamsInterface } from '../../../Types/CommonType'
import {
    commonTableParams,
    setCommonTableParamsData,
} from '../../../Utils/CommontTable'
import FullWidthModal from '../../../Components/FullWidthModal'
import { ReactComponent as DeleteIcon } from '../../../Assest/Svg/DeleteIcon.svg'
import { ReactComponent as EditIcon } from '../../../Assest/Svg/EditIcon.svg'
import type {
    WorkflowListInterface,
    WorkflowFormDataInterface,
    WorkflowListDataTypeInterface,
} from '../../../Types/Workflow'
import { GetCategoryDropDownList } from '../../../Services/GroupAndPartners'
import WorkflowForm from './WorkflowForm'
import { EyeOutlined } from '@ant-design/icons'
import calculatePagination from '../../../Utils/Pagination'
import ActivePremission from '../../../Utils/premissins'
import { PermissionType } from '../../../Types/Enum/PermissionType'

export const WorkflowItemDefaultData = {
    clientCategoryName: '',
    clientCategoryId: 0,
    departmentName: '',
    departmentId: 0,
    workflowFor: 0,
    workflowForName: '',
    activeStatus: '',
    workflowId: '0',
    workflowName: '',
}

const WorkflowList = (props: WorkflowListInterface): React.ReactElement => {
    const navigate = useNavigate()
    const dispatch = useDispatch()
    const { workflowList, workflowListCount } = props
    const [tableParams, setTableParams] =
        useState<TableParamsInterface>(commonTableParams)
    const [deleteModalStatus, setDeleteModalStatus] = useState(false)
    const [createEditModalStatus, setCreateEditModalStatus] = useState(false)
    const [workflowId, setWorkflowId] = useState('')
    const [editModalTittle, setEditModalTittle] = useState('Create Workflow')
    const [editData, setEditData] = useState<WorkflowFormDataInterface>(
        WorkflowItemDefaultData
    )
    const [activeInactiveModalStatus, setActiveInactiveModalStatus] =
        useState(false)
    const [activeInactiveStatusLabel, setActiveInactiveStatusLabel] =
        useState('')
    const [currentPage, setCurrentPage] = useState(1)
    const [itemsPerPage, setItemsPerPage] = useState(10)
    const [isLoadingModal, setIsLoadingModal] = useState(false)
    const hasFetchedOnce2 = useRef(false)
    useEffect(() => {
        if (!hasFetchedOnce2.current) {
            hasFetchedOnce2.current = true
            return
        }
        GetCategoryDropDownList(dispatch)
        GetWorkflowTypeList(dispatch)
    }, [])
    const hasFetchedOnce = useRef(false)
    const getTableData = useCallback(() => {
        const { pageSize, pageNo, sortOrderList, searchCriteriaList } =
            setCommonTableParamsData(tableParams)
        GetWorkflowList(dispatch, {
            pageNo,
            pageSize,
            searchCriteriaList,
            sortOrderList,
        })
    }, [
        tableParams?.sorter,
        tableParams.pagination?.current,
        tableParams?.filter,
    ])

    useEffect(() => {
        if (!hasFetchedOnce.current) {
            hasFetchedOnce.current = true
            return
        }
        getTableData()
    }, [getTableData])

    const handleDataCountChange = useCallback(() => {
        setTableParams({
            ...tableParams,
            pagination: {
                ...tableParams.pagination,
                total: workflowListCount,
            },
        })
    }, [workflowListCount])

    useEffect(() => {
        handleDataCountChange()
    }, [handleDataCountChange])

    const viewWorkflowDetails = (id: string): void => {
        navigate(`/system-configuration/work-flow-details?id=${id}`)
    }

    const handlePageChange = (pageNo: number, pageSize: number): void => {
        window.scrollTo(0, 0)
        setCurrentPage(pageNo)
        setItemsPerPage(pageSize)
    }
    const handlePageSizeChange = (pageSize: number): void => {
        setItemsPerPage(pageSize)
        setCurrentPage(1) // Reset to first page when page size changes
    }
    const pagination = calculatePagination(
        currentPage,
        workflowListCount,
        itemsPerPage,
        handlePageSizeChange
    )

    const columns: ColumnsType<WorkflowListDataTypeInterface> = [
        {
            title: 'Company Group',
            dataIndex: 'clientCategoryName',
        },
        {
            title: 'Department',
            dataIndex: 'departmentName',
        },
        {
            title: 'Workflow Type',
            dataIndex: 'workflowForName',
        },
        {
            title: 'Workflow',
            dataIndex: 'workflowName',
            sorter: true,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: 'Action',
            key: 'action',
            render: (_, record: WorkflowListDataTypeInterface) => {
                return (
                    <Space size="middle">
                        {ActivePremission('1007', PermissionType.UPDATE) && (
                            <Tooltip title="Edit WorkFlow">
                                <EditIcon
                                    onClick={() => {
                                        openEditModal(record?.workflowId)
                                    }}
                                    className={commonStyles.clickableIcon}
                                />
                            </Tooltip>
                        )}

                        <Tooltip title="View WorkFlow">
                            <EyeOutlined
                                onClick={() => {
                                    viewWorkflowDetails(record?.workflowId)
                                }}
                                className={commonStyles.viewIcon}
                            />
                        </Tooltip>
                        <Tooltip
                            title={
                                record.activeStatus === 'Active'
                                    ? 'Active'
                                    : 'Inactive'
                            }
                        >
                            <Switch
                                checked={record.activeStatus === 'Active'}
                                onClick={() => {
                                    activeInactiveModalFunction(
                                        record?.workflowId,
                                        record.activeStatus
                                    )
                                }}
                            />
                        </Tooltip>
                        {ActivePremission('1007', PermissionType.DELETE) && (
                            <Tooltip title="Delete">
                                <DeleteIcon
                                    onClick={() => {
                                        deleteModalFunction(record?.workflowId)
                                    }}
                                    className={commonStyles.clickableIcon}
                                />
                            </Tooltip>
                        )}
                    </Space>
                )
            },
        },
    ]

    const onChangeTableParams: TableProps<WorkflowListDataTypeInterface>['onChange'] =
        (pagination, filters, sorter: any, extra) => {
            handlePageChange(pagination.current ?? 1, pagination.pageSize ?? 10)
            setTableParams({
                ...tableParams,
                pagination,
                sorter: {
                    field: sorter?.field ?? '',
                    order: sorter?.order ?? '',
                },
            })
        }

    const onChangeText = (data: React.ChangeEvent<HTMLInputElement>): void => {
        const searchText = data.target.value.trim().toLowerCase()
        onChangeFilter(searchText)
    }

    const onChangeFilter = (data: string): void => {
        setTableParams({
            ...tableParams,
            filter: {
                fieldName: 'workflowName',
                searchOperator: 10,
                fieldValue1: data,
                fieldValue2: '',
            },
        })
    }

    const deleteModalFunction = (id: string): void => {
        setDeleteModalStatus(!deleteModalStatus)
        let workflowId = ''
        if (!deleteModalStatus) {
            workflowId = id
        }
        setWorkflowId(workflowId)
    }

    const deleteWorkflow = (): void => {
        DeleteWorkflow(dispatch, workflowId, getTableData)
        deleteModalFunction('')
    }

    const openEditModal = (id: string): void => {
        const data = workflowList.find((data: WorkflowFormDataInterface) => {
            return data.workflowId === id
        })

        let tittle = 'Create Workflow'
        if (id !== null && id !== undefined && id !== '') {
            tittle = 'Edit Workflow'
        }

        setEditModalTittle(tittle)
        setEditData(data ?? WorkflowItemDefaultData)
        changeCreateEditModalStatus()
    }

    const changeCreateEditModalStatus = (): void => {
        setCreateEditModalStatus(!createEditModalStatus)
    }

    const activeInactiveModalFunction = (
        id: string,
        activeStatus: string
    ): void => {
        setActiveInactiveModalStatus(!activeInactiveModalStatus)
        let workflowId = ''
        if (!activeInactiveModalStatus) {
            workflowId = id
        }
        let label = 'Active'
        if (activeStatus === 'Active') {
            label = 'Inactive'
        }
        setActiveInactiveStatusLabel(label)
        setWorkflowId(workflowId)
    }

    const updateActiveInactiveWorkflow = (): void => {
        let status = 'Active'
        if (activeInactiveStatusLabel === 'Inactive') status = 'Inactive'
        ActiveInactiveWorkflow(dispatch, workflowId, status, getTableData)
        activeInactiveModalFunction('', '')
    }

    const onSaveWorkflow = (
        data: WorkflowFormDataInterface,
        callBack: CallableFunction
    ): void => {
        void saveWorkflowData(data, callBack)
    }

    const saveWorkflowData = async (
        data: WorkflowFormDataInterface,
        callBack: CallableFunction
    ): Promise<void> => {
        setIsLoadingModal(true)
        await SaveWorkflow(dispatch, data)
            .then((result) => {
                if (result !== null && result !== undefined) {
                    changeCreateEditModalStatus()
                    getTableData()
                    callBack()
                    setIsLoadingModal(false)
                }
            })
            .catch(() => {})
    }

    return (
        <>
            <Card
                title="Workflow"
                extra={
                    <AddNewButton
                        name="Add New"
                        clickAction={() => {
                            openEditModal('')
                        }}
                    />
                }
                className={commonStyles.card}
            >
                <SearchInput
                    placeHolder={'Search Workflow by keywords'}
                    onSearch={onChangeFilter}
                    onChange={onChangeText}
                    width="478"
                />
                <div className={commonStyles.table}>
                    <Table
                        columns={columns}
                        dataSource={workflowList}
                        onChange={onChangeTableParams}
                        pagination={pagination}
                    />
                </div>
                <FullWidthModal
                    modalStatus={deleteModalStatus}
                    closeModal={deleteModalFunction}
                    tittle="You are about to delete this workflow. Click 'Yes' to continue."
                    smallTittle="Warning: This action cannot be undone!"
                    yesButtonFunction={deleteWorkflow}
                />
                <FullWidthModal
                    modalStatus={activeInactiveModalStatus}
                    closeModal={() => {
                        activeInactiveModalFunction('', '')
                    }}
                    tittle={`You are about to ${activeInactiveStatusLabel} this workflow. Click 'Yes' to continue.`}
                    smallTittle=""
                    yesButtonFunction={updateActiveInactiveWorkflow}
                />
                <Modal
                    footer={null}
                    onCancel={changeCreateEditModalStatus}
                    width={'40%'}
                    title={editModalTittle}
                    open={createEditModalStatus}
                >
                    <WorkflowForm
                        onSave={onSaveWorkflow}
                        editData={editData}
                        isLoadingModal={isLoadingModal}
                    />
                </Modal>
            </Card>
        </>
    )
}

const mapStateToProps = (state: any): WorkflowListInterface => {
    return {
        workflowList: state.initial.workflowList,
        workflowListCount: state.initial.workflowListCount,
    }
}

export default connect(mapStateToProps)(WorkflowList)
