import React, { useEffect, useRef, useState } from 'react'
import { Col, Row, Input, Form, Button, Select, Tooltip } from 'antd'
import commonStyles from '../../../../Utils/Common.less'
import { SaveOutlined } from '@ant-design/icons'
import { useDispatch, connect } from 'react-redux'
import { GetUserList } from '../../../../Services/User'
import { SaveChat } from '../../../../Services/Corporate'
import {
    type OnBoardingIndividualChatStateInterface,
    type OnBoardingIndividualChatInterface,
    type OnBoardingIndividualChatProps,
} from '../../../../Types/Client/OnboardingClients/OnboardingIndividual'

const IndividualChat = (
    props: OnBoardingIndividualChatProps
): React.ReactElement => {
    const { userList, individualId, onCloseModel } = props
    const dispatch = useDispatch()
    const [form] = Form.useForm()
    const [FilteredOptions, setFilteredOptions] = useState(userList)
    const [selectedUserIds, setSelectedUserIds] = useState<string[]>(
        form.getFieldValue('userIds') ?? []
    )
    const hasFetchedOnce = useRef(false)
    useEffect(() => {
        if (!hasFetchedOnce.current) {
            hasFetchedOnce.current = true
            return
        }
        GetUserList(dispatch)
    }, [dispatch, form])

    useEffect(() => {
        setFilteredOptions(userList)
    }, [userList])

    const onFinish = (formData: OnBoardingIndividualChatInterface): void => {
        const dataToSend: any = {
            BusinessTypeId: 0,
            ReferenceId: individualId,
            IsClientCommunication: 0,
            Description: formData.Description,
            userIds: formData.userIds,
        }
        SaveChat(dispatch, dataToSend)
            .then((result) => {
                if (result !== null) {
                    form.resetFields()
                    onCloseModel()
                }
            })
            .catch(() => {})
    }

    const handleSearch = (value: string): void => {
        const currentFilter = form.getFieldValue('userIds') ?? []
        const filteredOptions = userList?.filter(
            (user: { label: string }) =>
                user.label.toLowerCase().includes(value.toLowerCase()) ||
                currentFilter.includes(user.label)
        )
        setFilteredOptions(filteredOptions)
    }

    const handleChange = (selectedUserIds: any): void => {
        setSelectedUserIds(selectedUserIds)
        form.setFieldsValue({ userIds: selectedUserIds })
    }

    const customizeRequiredMark = (
        label: React.ReactNode,
        { required }: { required: boolean }
    ): React.ReactElement => (
        <>
            {label}
            &nbsp;
            {required && <span className={commonStyles.requireIcon}>*</span>}
        </>
    )
    return (
        <div className={commonStyles.formWrapper}>
            <Form
                name="complex-form"
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                initialValues={{ remember: true }}
                layout={'vertical'}
                autoComplete="off"
                form={form}
                onFinish={onFinish}
                size="small"
                requiredMark={customizeRequiredMark}
            >
                <Form.Item<OnBoardingIndividualChatInterface>
                    name="individualId"
                    hidden={true}
                    initialValue={props.individualId ?? ''}
                >
                    <Input />
                </Form.Item>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item<OnBoardingIndividualChatInterface>
                            label="Message"
                            name="Description"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Message',
                                },
                            ]}
                        >
                            <Input.TextArea rows={4} />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item<OnBoardingIndividualChatInterface>
                            label="Message To"
                            name="userIds"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please select at least one User!',
                                },
                            ]}
                        >
                            <Select
                                mode="multiple"
                                allowClear
                                placeholder="Please select"
                                options={FilteredOptions}
                                size="large"
                                optionLabelProp="label"
                                showSearch
                                onSearch={handleSearch}
                                defaultActiveFirstOption
                                filterOption={false}
                                onChange={handleChange}
                                value={selectedUserIds}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col offset={22} span={2}>
                        <Tooltip title="Send Message">
                            <Button
                                type="primary"
                                htmlType="submit"
                                size="middle"
                            >
                                <SaveOutlined />
                            </Button>
                        </Tooltip>
                    </Col>
                </Row>
            </Form>
        </div>
    )
}

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

export default connect(mapStateToProps)(IndividualChat)
