import React, { useEffect, useRef, useState } from 'react'
import commonStyles from '../../../Utils/Common.less'
import { Button, Col, Form, Input, Row, Select, Tooltip } from 'antd'
import { SendOutlined } from '@ant-design/icons'
import {
    type DataCHAT,
    type ProcessDetailChat,
    type ProspectChatStateInterface,
} from '../../../Types/Client/ProspectClients/prospectClient'
import { connect, useDispatch } from 'react-redux'
import { GetUserList } from '../../../Services/User'
import chatstyle from '../../Clients/ProspectClients/prosepectClient.less'
import { type StaffCommunicationProps } from '../../../Types/ToDoViewAllList'
import { GetChat, SaveChat } from '../../../Services/ToDoViewAllList'
const StaffCommunication = (
    props: StaffCommunicationProps
): React.ReactElement => {
    const { userList, serviceProcessId } = props
    const [form] = Form.useForm()
    const dispatch = useDispatch()
    const [chatData, setChatData] = useState<DataCHAT | null>(null)
    const hasFetchedOnce = useRef(false)
    const hasFetchedOnce2 = useRef(false)
    const chatdatarefetch = (): void => {
        void GetChat(dispatch, serviceProcessId, 0, (chatdatass: DataCHAT) => {
            setChatData(chatdatass)
        })
    }

    useEffect(() => {
        if (!hasFetchedOnce2.current) {
            hasFetchedOnce2.current = true
            return
        }
        chatdatarefetch()
    }, [serviceProcessId, form])

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

    const onSave = (): void => {
        void onSaveChat()
    }
    const onSaveChat = async (): Promise<void> => {
        try {
            await form.validateFields()

            const formData = form.getFieldsValue()

            const dataToSave = {
                chatId: 0,
                msgType: 1,
                msgReferenceId: serviceProcessId,
                isPinned: 0,
                businessTypeId: 0,
                description: formData.message,
                userIds: formData.userIds,
            }

            await SaveChat(dispatch, dataToSave)
            chatdatarefetch()
            form.resetFields(['message', 'userIds'])
        } catch (error) {
            console.error('Error:', error)
        }
    }

    const customizeRequiredMark = (
        label: React.ReactNode,
        { required }: { required: boolean }
    ): React.ReactElement => (
        <>
            {label}
            &nbsp;
            {required && <span className={commonStyles.requireIcon}>*</span>}
        </>
    )

    const chatUserData = chatData?.processDetailChatList

    return (
        <div className={chatstyle.main}>
            <div className={chatstyle.scrollContainer}>
                {chatUserData != null && chatUserData?.length > 0 ? (
                    chatUserData?.map((item: ProcessDetailChat) => (
                        <div className={chatstyle.contener} key={item.chatId}>
                            <div className={chatstyle.imagemain}>
                                <img
                                    src={item.imageUrl}
                                    alt="Your Image"
                                    className={chatstyle.image}
                                />
                            </div>
                            <div className={chatstyle.chattextMain}>
                                <p className={chatstyle.chatheding}>
                                    {item.description}
                                </p>
                                <p className={chatstyle.chatsubheading}>
                                    By {item.createdBy}, {item.dateInfo} <br />
                                    {item.userList}
                                </p>
                            </div>
                        </div>
                    ))
                ) : (
                    <p className={chatstyle.chatheding}>No Records Found</p>
                )}
            </div>
            <div className={chatstyle.formspace}>
                <div className={commonStyles.formWrapper}>
                    <Form
                        name="complex-form"
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                        initialValues={{ remember: true }}
                        layout={'vertical'}
                        autoComplete="off"
                        form={form}
                        size="small"
                        requiredMark={customizeRequiredMark}
                    >
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    label="Message"
                                    name="message"
                                    rules={[
                                        {
                                            required: true,
                                            message:
                                                'Please input your Message',
                                        },
                                    ]}
                                >
                                    <Input.TextArea
                                        rows={4}
                                        placeholder="Type your message here..."
                                    />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    label="Message To"
                                    name="userIds"
                                    rules={[
                                        {
                                            required: true,
                                            message:
                                                'Please select at least one User!',
                                        },
                                    ]}
                                >
                                    <Select
                                        mode="multiple"
                                        allowClear
                                        placeholder="Please select"
                                        options={userList}
                                        size="large"
                                        showSearch
                                        filterOption={(input, option) =>
                                            option?.label
                                                ?.toLowerCase()
                                                .includes(
                                                    input.toLowerCase()
                                                ) ?? false
                                        }
                                        onChange={() => {}}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row gutter={16}>
                            <Col offset={21} span={2}>
                                <Tooltip title="Save Chat">
                                    <Button
                                        type="primary"
                                        size="large"
                                        onClick={onSave}
                                    >
                                        <SendOutlined
                                            className={
                                                chatstyle.buttonimageIcon
                                            }
                                        />
                                    </Button>
                                </Tooltip>
                            </Col>
                        </Row>
                    </Form>
                </div>
            </div>
        </div>
    )
}

const mapStateToProps = (state: any): ProspectChatStateInterface => {
    return {
        userList: state.user.userList,
    }
}

export default connect(mapStateToProps)(StaffCommunication)
