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 { connect, useDispatch } from 'react-redux'
import {
    type PortfolioFormStateInterface,
    type PortfolioDetailsFormInterface,
} from '../../../Types/Client/RegisteredClients/Portfolio'
import { GetCategoryDropDownList } from '../../../Services/GroupAndPartners'
import { GetUserList } from '../../../Services/User'
import { type ListFrontEndInterface } from '../../../Types/CommonType'
import { SavePorAccountManger } from '../../../Services/Portfolio'

const { TextArea } = Input
const PorfolioForm = (
    props: PortfolioDetailsFormInterface
): React.ReactElement => {
    const { categoryDropDownList, userList, onSave, editData } = props
    const dispatch = useDispatch()
    const [form] = Form.useForm()
    const [selectedId, setSelectedId] = useState(0)
    const hasFetchedOnce = useRef(false)
    useEffect(() => {
        const userData = userList?.find(
            (data: ListFrontEndInterface) => data.value === editData.managerId
        )
        const newData = {
            ...editData,
            managerId: userData?.value ?? '',
        }
        form.setFieldsValue(newData)
    }, [editData, userList])

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

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

    const handleSelectChange = (value: string | number): void => {
        setSelectedId(value === 'all' ? 0 : Number(value))
    }

    const resetForm = (): void => {
        form.resetFields()
    }

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

    const saveAccountmanger = (): void => {
        if (editData.portfolioId !== 0) {
            const accountmanagerId = form.getFieldValue('accountmanagerId')
            const data = {
                portfolioId: editData.portfolioId,
                businessTypeId: 0,
                referenceId: 0,
                accountsManagerId: accountmanagerId,
            }
            void SavePorAccountManger(dispatch, data)
        }
    }
    return (
        <div className={commonStyles.formWrapper}>
            <Form
                name="complex-form"
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                initialValues={{ remember: true }}
                layout={'vertical'}
                autoComplete="off"
                onFinish={(data) => {
                    onSave(data, resetForm)
                }}
                form={form}
                requiredMark={customizeRequiredMark}
            >
                <Form.Item name="portfolioId" hidden={true}>
                    <Input />
                </Form.Item>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item
                            label="Client Category"
                            name="clientCategoryId"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please select Client Category!',
                                },
                            ]}
                        >
                            <Select
                                placeholder="Please select"
                                onChange={handleSelectChange}
                                value={selectedId === 0 ? 'all' : selectedId}
                                options={[
                                    { value: 0, label: 'All' },
                                    ...categoryDropDownList,
                                ]}
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                                allowClear
                                showSearch
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item label="Porfolio Number" name="number">
                            <Input
                                disabled
                                placeholder="This is Auto Generated"
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item
                            label="Porfolio Name"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Porfolio Name!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item
                            label="Manager Name"
                            name="managerId"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please select Manager Name!',
                                },
                            ]}
                        >
                            <Select
                                showSearch
                                placeholder="Please select"
                                options={[
                                    { label: 'Please select', value: null },
                                    ...userList,
                                ]}
                                allowClear
                                onChange={() => {}}
                                filterOption={(input, option) =>
                                    (option?.label ?? '')
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item label="Remarks" name="remarks">
                            <TextArea />
                        </Form.Item>
                    </Col>
                </Row>
                {editData.portfolioId !== 0 && (
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                label="Account Manager Name"
                                name="accountmanagerId"
                                // rules={[
                                //     {
                                //         required: true,
                                //         message: 'Please select Manager Name!',
                                //     },
                                // ]}
                            >
                                <Select
                                    showSearch
                                    placeholder="Please select"
                                    options={[
                                        { label: 'Please select', value: null },
                                        ...userList,
                                    ]}
                                    allowClear
                                    onChange={() => {}}
                                    filterOption={(input, option) =>
                                        (option?.label ?? '')
                                            .toLowerCase()
                                            .includes(input.toLowerCase())
                                    }
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                )}
                <Row gutter={16}>
                    <Col offset={22} span={2}>
                        <Tooltip title="Save Portfolio">
                            <Button
                                type="primary"
                                htmlType="submit"
                                onClick={saveAccountmanger}
                            >
                                <SaveOutlined />
                            </Button>
                        </Tooltip>
                    </Col>
                </Row>
            </Form>
        </div>
    )
}
const mapStateToProps = (state: any): PortfolioFormStateInterface => {
    return {
        categoryDropDownList: state.initial.categoryDropDownList,
        userList: state.user.userList,
    }
}
export default connect(mapStateToProps)(PorfolioForm)
