import React, { useEffect, useRef, useState } from 'react'
import {
    Avatar,
    Card,
    Drawer,
    Dropdown,
    Flex,
    Menu,
    Modal,
    Tooltip,
} from 'antd'
import TodoStyles from './backLogList.less'
import {
    FormOutlined,
    UsergroupDeleteOutlined,
    FieldTimeOutlined,
    UnorderedListOutlined,
    PaperClipOutlined,
    WechatOutlined,
} from '@ant-design/icons'
import {
    type todoSatteInterface,
    type GetSprintTaskListInterfaceType,
    type todoForminterface,
    type User,
} from '../../Types/Backlog/Backlog'
import { connect, useDispatch } from 'react-redux'
import { getusersdroplist } from '../../Services/Helpdesk/Backlog'
import CreateTaskForm from '../HelpDesk/createTask/CreateTaskForm'
import CreateFollowersModal from '../HelpDesk/createTask/CreateFoolwers'
import CreateHours from '../HelpDesk/createTask/CreateHours'
import CreateattachmentModal from '../HelpDesk/createTask/Attachment'
import CreatesubtaskModal from '../HelpDesk/createTask/Tabs'
import ChatClient from '../HelpDesk/createTask/chatClient'
import { type setTasks } from '../../Types/HelpDesk/Cretetask'
import { GetTaskData } from '../../Services/Helpdesk/CreteTask'

export const TaskdefaultData = {
    taskId: 0,
    taskNo: '',
    taskName: '',
    priorityId: 0,
    sortOrder: 0,
    taskType: 0,
    businessType: 0,
    referenceId: 0,
    serviceId: 0,
    serviceReferenceId: 0,
    assignedBy: 0,
    assignedTo: 0,
    fromDate: '',
    toDate: '',
    statusId: 0,
    notifyToStatusChange: 0,
    description: '',
    clientName: '',
    recurringFrequency: 0,
    recurringFrequencyType: 0,
    recurringFrequencyPeriodId: 0,
    recurringEnds: 0,
    recurringOccurrence: 0,
    recurringEndsOn: '',
    isRepeatOnSun: 0,
    isRepeatOnMon: 0,
    isRepeatOnTue: 0,
    isRepeatOnWed: 0,
    isRepeatOnThu: 0,
    isRepeatOnFri: 0,
    isRepeatOnSat: 0,
    projectTierId: 0,
    projectId: 0,
    departmentId: 0,
    sprintId: 0,
}

export const TaskItemDefaultData = {
    taskId: '',
    taskNo: 0,
    taskName: '',
    priorityName: '',
    priorityColourCode: '',
    taskTypeName: '',
    sortOrder: 0,
    businessTypeName: '',
    clientName: '',
    serviceName: '',
    description: '',
    assignedByName: '',
    assignedToName: '',
    fromDate: '',
    toDate: '',
    daysCount: 0,
    daysColourCode: '',
    status: '',
    statusColourCode: '',
    notifyToStatusChange: 0,
    subTaskViews: [],
    taskFollowerViews: [] as [],
    subTaskStatus: 0,
    isNewChatExist: 0,
    projectTierInfo: '',
    projectStatusId: 0,
    projectStatusLbl: '',
    userStatusId: 0,
    userStatusLbl: '',
}

const QA = (props: todoForminterface): React.ReactElement => {
    const [modalTitleCreate, setModalTitleCreate] = useState('Add Dates')
    const [modalVisibleCreate, setModalVisibleCreate] = useState(false)
    const [modalVisibleCreateHours, setModalVisibleCreateHours] =
        useState(false)
    const [modalVisibleCreateAttachment, setModalVisibleCreateAttachment] =
        useState(false)
    const [attachmentTaskId, setAttachmentTaskId] = useState('0')
    const { sprintTaskList, userimageList } = props
    const [selectedTaskId, setSelectedTaskId] = useState<string>('')
    const [createEditModalStatus, setCreateEditModalStatus] = useState(false)
    const [editData, setEditData] = useState<setTasks>(TaskdefaultData)
    const [selectedUsers, setSelectedUsers] = useState<number[]>([])
    const [modalVisibleCreateFollowers, setModalVisibleCreateFollowers] =
        useState(false)
    const [getTask, setTask] =
        useState<GetSprintTaskListInterfaceType>(TaskItemDefaultData)
    const [modalVisibleCreateSubTask, setModalVisibleCreateSubTask] =
        useState(false)
    const [modalVisibleCreateChat, setModalVisibleCreateChat] = useState(false)
    const hasFetchedOnce = useRef(false)
    const dispatch = useDispatch()
    const [restData, setResetData] = useState('false')
    const handleModalOpenCreate = (taskId: string): void => {
        setModalVisibleCreate(true)
        setAttachmentTaskId(taskId)
        setModalTitleCreate('Add Dates')
    }

    const handleModalOpenCreateHours = (taskId: any): void => {
        setModalVisibleCreateHours(true)
        setAttachmentTaskId(taskId)
        setModalTitleCreate('Add Dates')
    }

    const handleModalOpenCreateFollowers = (taskId: string): void => {
        setModalVisibleCreateFollowers(true)
        setAttachmentTaskId(taskId)
        setModalTitleCreate('Add Followers')
    }

    const onChat = (taskId: string): void => {
        setModalVisibleCreateChat(true)
        setAttachmentTaskId(taskId)
        setModalTitleCreate('Staff Communication')
    }

    const handleModalClose = (): void => {
        setModalVisibleCreate(false)
        setModalVisibleCreateAttachment(false)
        setModalVisibleCreateHours(false)
        setModalVisibleCreateFollowers(false)
        setModalVisibleCreateSubTask(false)
        setModalVisibleCreateChat(false)
    }

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

    const onAttachment = (taskId: string): void => {
        setModalVisibleCreateAttachment(true)
        setAttachmentTaskId(taskId)
        setModalTitleCreate('Add Attachment')
    }

    const onSaveTask = (callBack: CallableFunction): void => {
        changeCreateEditModalStatus()
        callBack()
    }

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

    const handleAssignByMenuClick = (
        taskId: string,
        statusProjectId: string
    ): void => {
        setSelectedTaskId(taskId)
    }

    const handleProgressChange = async (
        value: number,
        projectStatusName: string
    ): Promise<void> => {}

    const openEditModal = (id: string): void => {
        void openEditData(id)
    }

    const openEditData = async (id: string): Promise<void> => {
        // const data = taskDetailsList.find((data: TaskData) => {
        //     return data.taskId === id
        // })
        try {
            const data = await GetTaskData(dispatch, id)
            setEditData(data ?? TaskdefaultData)
        } catch (err) {}
    }

    const handleModalOpenSubTasks = (
        task: GetSprintTaskListInterfaceType
    ): void => {
        setModalVisibleCreateSubTask(true)
        setAttachmentTaskId(task.taskId)
        setTask(task)
        setModalTitleCreate('Add SubTask')
    }

    return (
        <div>
            {sprintTaskList.length === 0 ? (
                <Card className={TodoStyles.todoCard} title="TO-DO">
                    <div>No records available</div>
                </Card>
            ) : (
                <Card className={TodoStyles.todoCard} title="TO-DO">
                    {sprintTaskList
                        .filter((task) => task.userStatusId === 2)
                        .map((task: GetSprintTaskListInterfaceType) => (
                            <Card
                                key={task.taskId}
                                className={TodoStyles.todoItem}
                            >
                                <div className={TodoStyles.tasknameStyles}>
                                    <div>{task.taskName}</div>
                                    <div className={TodoStyles.taskAndColor}>
                                        <div>
                                            <Dropdown
                                                overlay={
                                                    <Menu
                                                        onClick={({ key }) => {
                                                            handleAssignByMenuClick(
                                                                task.taskId,
                                                                key
                                                            )
                                                        }}
                                                    >
                                                        <>
                                                            <Menu.Item
                                                                key="todo"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        1,
                                                                        'To-Do'
                                                                    )
                                                                }}
                                                            >
                                                                To Do
                                                            </Menu.Item>
                                                            <Menu.Item
                                                                key="inprogress"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        2,
                                                                        'In-Progress'
                                                                    )
                                                                }}
                                                            >
                                                                In Progress
                                                            </Menu.Item>
                                                            <Menu.Item
                                                                key="completed"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        3,
                                                                        'Complete'
                                                                    )
                                                                }}
                                                            >
                                                                Complete
                                                            </Menu.Item>
                                                            <Menu.Item
                                                                key="QA"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        1,
                                                                        'QA'
                                                                    )
                                                                }}
                                                            >
                                                                QA
                                                            </Menu.Item>
                                                        </>
                                                        ) : (
                                                        <>
                                                            <Menu.Item
                                                                key="todo"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        1,
                                                                        'QA'
                                                                    )
                                                                }}
                                                            >
                                                                To Do
                                                            </Menu.Item>
                                                            <Menu.Item
                                                                key="inprogress"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        2,
                                                                        'QA'
                                                                    )
                                                                }}
                                                            >
                                                                In Progress
                                                            </Menu.Item>
                                                            <Menu.Item
                                                                key="completed"
                                                                onClick={() => {
                                                                    void handleProgressChange(
                                                                        3,
                                                                        'Complete'
                                                                    )
                                                                }}
                                                            >
                                                                Complete
                                                            </Menu.Item>
                                                        </>
                                                    </Menu>
                                                }
                                                open={
                                                    selectedTaskId ===
                                                    task.taskId
                                                }
                                                onVisibleChange={(visible) => {
                                                    if (!visible) {
                                                        setSelectedTaskId('')
                                                    }
                                                }}
                                            >
                                                <a
                                                    className="ant-dropdown-link"
                                                    onClick={(e) => {
                                                        e.preventDefault()
                                                        setSelectedTaskId(
                                                            task.taskId
                                                        )
                                                    }}
                                                >
                                                    To-Do
                                                </a>
                                            </Dropdown>
                                        </div>
                                        <div
                                            className={TodoStyles.circle}
                                            style={{
                                                backgroundColor:
                                                    task.daysColourCode,
                                            }}
                                        ></div>
                                    </div>
                                </div>
                                <Flex justify="space-between">
                                    <div className={TodoStyles.iconContainer}>
                                        <Tooltip title="Edit Task">
                                            <FormOutlined
                                                className={TodoStyles.todoIcons}
                                                onClick={() => {
                                                    handleModalOpenCreate(
                                                        task.taskId
                                                    )
                                                    openEditModal(task.taskId)
                                                }}
                                            />
                                        </Tooltip>
                                        <Tooltip title="Add Followers">
                                            <UsergroupDeleteOutlined
                                                className={TodoStyles.todoIcons}
                                                onClick={() => {
                                                    handleModalOpenCreateFollowers(
                                                        task.taskId
                                                    )
                                                }}
                                            />
                                        </Tooltip>
                                        <Tooltip title="Add Hours">
                                            <FieldTimeOutlined
                                                className={TodoStyles.todoIcons}
                                                onClick={() => {
                                                    handleModalOpenCreateHours(
                                                        task.taskId
                                                    )
                                                }}
                                            />
                                        </Tooltip>
                                        <Tooltip title="Add subtask">
                                            <UnorderedListOutlined
                                                className={TodoStyles.todoIcons}
                                                onClick={() => {
                                                    handleModalOpenSubTasks(
                                                        task
                                                    )
                                                }}
                                            />
                                        </Tooltip>
                                        <Tooltip title="Add Attachment">
                                            <PaperClipOutlined
                                                className={TodoStyles.todoIcons}
                                                onClick={() => {
                                                    onAttachment(task.taskId)
                                                }}
                                            />
                                        </Tooltip>
                                        <Tooltip title="Staff Communication">
                                            <WechatOutlined
                                                className={TodoStyles.todoIcons}
                                                onClick={() => {
                                                    onChat(task.taskId)
                                                }}
                                            />
                                        </Tooltip>
                                    </div>
                                    <div>
                                        {userimageList.map((user: any) => {
                                            if (
                                                user.userName ===
                                                task.assignedByName
                                            ) {
                                                return (
                                                    <div
                                                        key={task.taskId}
                                                        className={
                                                            TodoStyles.todoAssignAvatar
                                                        }
                                                    >
                                                        <div
                                                            className={
                                                                TodoStyles.todotaskassignedname
                                                            }
                                                        >
                                                            {
                                                                task.assignedByName
                                                            }
                                                        </div>
                                                        <Avatar
                                                            key={user.userName}
                                                            size={30}
                                                            src={user.imageUrl}
                                                        />
                                                    </div>
                                                )
                                            }
                                            return null
                                        })}

                                        {userimageList.map((user: User) => {
                                            if (
                                                user.userName ===
                                                task.assignedToName
                                            ) {
                                                return (
                                                    <div
                                                        key={task.taskId}
                                                        className={
                                                            TodoStyles.todoAssignAvatar
                                                        }
                                                    >
                                                        <div
                                                            className={
                                                                TodoStyles.todotaskassignedname
                                                            }
                                                        >
                                                            {
                                                                task.assignedToName
                                                            }
                                                        </div>
                                                        <Avatar
                                                            key={user.userName}
                                                            size={30}
                                                            src={user.imageUrl}
                                                        />
                                                    </div>
                                                )
                                            }
                                            return null
                                        })}
                                    </div>
                                </Flex>
                            </Card>
                        ))}
                </Card>
            )}
            {/* </Spin> */}
            <Modal
                title={modalTitleCreate}
                open={modalVisibleCreate}
                onCancel={handleModalClose}
                footer={null}
                width={1500}
            >
                <CreateTaskForm
                    taskId={attachmentTaskId.toString()}
                    onSave={onSaveTask}
                    editData={editData}
                    setResetData={setResetData}
                    resetdata={restData}
                />
            </Modal>
            <Modal
                title={modalTitleCreate}
                open={modalVisibleCreateAttachment}
                onCancel={handleModalClose}
                footer={null}
                width={'50%'}
            >
                <CreateattachmentModal taskId={attachmentTaskId} />
            </Modal>
            <Modal
                title={modalTitleCreate}
                open={modalVisibleCreateHours}
                onCancel={handleModalClose}
                footer={null}
                width={'50%'}
            >
                <CreateHours taskid={attachmentTaskId} />
            </Modal>
            <Modal
                title={modalTitleCreate}
                open={modalVisibleCreateFollowers}
                onCancel={handleModalClose}
                footer={null}
                width={'50%'}
            >
                <CreateFollowersModal
                    onSave={onSaveTask}
                    taskid={attachmentTaskId.toString()}
                    selectedUsers={selectedUsers}
                    setSelectedUsers={setSelectedUsers}
                />
            </Modal>
            <Modal
                title={modalTitleCreate}
                open={modalVisibleCreateSubTask}
                onCancel={handleModalClose}
                footer={null}
                width={'50%'}
            >
                <CreatesubtaskModal
                    taskId={attachmentTaskId}
                    getTask={getTask}
                />
            </Modal>
            <Drawer
                title={
                    <span style={{ color: 'white' }}>{modalTitleCreate}</span>
                }
                open={modalVisibleCreateChat}
                onClose={handleModalClose}
                footer={null}
                width={550}
                styles={{
                    header: {
                        backgroundColor: '#085394',
                        padding: '20px',
                        marginBottom: '0',
                        color: 'white',
                    },
                    content: { padding: '0' },
                    body: { backgroundColor: 'yello' },
                }}
            >
                <ChatClient
                    taskId={Number(attachmentTaskId)}
                    messageTypeId={2}
                    referenceId={0}
                    businessId={0}
                />
            </Drawer>
        </div>
    )
}

const mapStateToProps = (state: any): todoSatteInterface => {
    return {
        userimageList: state.backlog.userimageList,
    }
}

export default connect(mapStateToProps)(QA)
