import React, { useEffect, useRef } from 'react'
import { Col, Row, Input, Form, Button, Select } from 'antd'
import { connect, useDispatch } from 'react-redux'
import commonStyles from '../../../../Utils/Common.less'
import { SaveOutlined } from '@ant-design/icons'
import {
    type ProjectManagmentStateInterface,
    type FirstPagePropss,
    type ProjectManagmentSatusFormDataInterface,
} from '../../../../Types/ProjectMangement'
import { GetUserList } from '../../../../Services/User'
import {
    AddStausDetails,
    CheckProjectSatusExist,
} from '../../../../Services/ProjectManagement'
import { ProjectItemDefaultData } from './Status'

const ProjectForm = (
    props: FirstPagePropss & { projectId: string }
): React.ReactElement => {
    const { onSave, editData, projectId, userList } = props
    const [form] = Form.useForm()
    const dispatch = useDispatch()
    const hasFetchedOnce = useRef(false)
    let timeout: any
    useEffect(() => {
        form.setFieldsValue(editData)
    }, [editData])

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

    const customizeRequiredMark = (
        label: React.ReactNode,
        { required }: { required: boolean }
    ): React.ReactElement => (
        <>
            {label}
            &nbsp;
            {required && <span className={commonStyles.requireIcon}>*</span>}
        </>
    )
    const resetForm = (): void => {
        form.setFieldsValue({
            ProjectItemDefaultData,
            projectStatusId: '0',
            projectId: '',
            projectStatusName: '',
            defaultAssigneeUserId: 0,
            colorCode: '#000000',
        })
    }
    const saveuserInformationData = (): void => {
        const values = form.getFieldsValue()
        const formattedValues = {
            projectId,
            projectStatusId: values.projectStatusId,
            projectStatusName: values.projectStatusName,
            defaultAssigneeUserId: values.defaultAssigneeUserId,
            colorCode: values.colorCode,
            sortingOrder: values.sortingOrder,
            defaultAssigneeUser: values.defaultAssigneeUser,
        }
        void saveUserInfoData(formattedValues)
    }
    const saveUserInfoData = async (
        data: ProjectManagmentSatusFormDataInterface
    ): Promise<void> => {
        await AddStausDetails(dispatch, data)
            .then((result) => {
                if (result !== null && result !== undefined) {
                    onSave(resetForm)
                }
            })
            .catch(() => {})
    }
    const onNamechange = (event: any): void => {
        const projectStatusName =
            form.getFieldValue('projectStatusName') ?? null

        clearTimeout(timeout)
        timeout = setTimeout(() => {
            CheckProjectSatusExist(
                dispatch,
                editData?.projectId,
                editData?.projectStatusId,

                projectStatusName
            )
        }, 1000)
    }

    return (
        <div className={commonStyles.formWrapper}>
            <Form
                name="complex-form"
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                initialValues={{ remember: true }}
                layout="vertical"
                autoComplete="off"
                form={form}
                requiredMark={customizeRequiredMark}
            >
                <Form.Item name="projectStatusId" hidden={true}>
                    <Input />
                </Form.Item>

                <Row gutter={24}>
                    {editData.projectStatusId === '0' && (
                        <Col span={12}>
                            <Form.Item<ProjectManagmentSatusFormDataInterface>
                                label="Staus"
                                name="projectStatusName"
                            >
                                <Input onChange={onNamechange} />
                            </Form.Item>
                        </Col>
                    )}

                    <Col span={12}>
                        <Form.Item<ProjectManagmentSatusFormDataInterface>
                            label="Project Prefix"
                            name="colorCode"
                        >
                            <Input type="color" />
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item<ProjectManagmentSatusFormDataInterface>
                            label="Assign To"
                            name="defaultAssigneeUserId"
                        >
                            <Select
                                allowClear
                                placeholder="Please select"
                                options={userList}
                                size="large"
                                showSearch
                            />
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={16}>
                    <Col offset={22} span={2}>
                        <Button
                            type="primary"
                            onClick={saveuserInformationData}
                        >
                            <SaveOutlined />
                        </Button>
                    </Col>
                </Row>
            </Form>
        </div>
    )
}

const mapStateToProps = (state: any): ProjectManagmentStateInterface => {
    return {
        categoryDropDownList: state.initial.categoryDropDownList,
        departmentDropDownList: state.initial.departmentDropDownList,
        userList: state.user.userList,
    }
}

export default connect(mapStateToProps)(ProjectForm)
