import {
    Button,
    Col,
    Input,
    Form,
    Row,
    Switch,
    DatePicker,
    Space,
    type DatePickerProps,
    Select,
    Tooltip,
} from 'antd'
import commonStyles from '../../../../../../Utils/Common.less'
import React, { useEffect, useState } from 'react'
import { SaveOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { connect, useDispatch } from 'react-redux'
import {
    GetCountryList,
    GetInduvidualList,
} from '../../../../../../Services/Common'
import {
    type PartnerTogilleAddress,
    type PartnerTapData,
    type PartnersDataFormInterface,
    type PartnersDataInterface,
    type IndividualData,
} from '../../../../../../Types/Client/RegisteredClients/Partnership'
import {
    GetInduvidualInfo,
    GetPartnerAddress,
    SavePartner,
    getClientCompanyDetails,
} from '../../../../../../Services/Parnership'
import moment from 'moment'
import ActivePremission from '../../../../../../Utils/premissins'
import { PermissionType } from '../../../../../../Types/Enum/PermissionType'
const Partners = (props: PartnersDataFormInterface): React.ReactElement => {
    const { countryList, partnershipId, InduvidualMemberList } = props

    const [form] = Form.useForm()
    const dispatch = useDispatch()
    const [selectedDate, setSelectedDate] = useState<string>('')
    const [addressDatas, setAddressData] =
        useState<PartnerTogilleAddress | null>(null)
    const [switchStates, setSwitchStates] = useState<{
        1: boolean
        2: boolean
        3: boolean
    }>({
        1: false,
        2: false,
        3: false,
    })
    const [induvidualInfo, setInduvidualInfo] = useState<IndividualData | null>(
        null
    )
    useEffect(() => {
        GetCountryList(dispatch)
        GetInduvidualList(dispatch)
    }, [dispatch])

    const onChange = (dateOfBirth: DatePickerProps['value']): void => {
        if (dateOfBirth != null) {
            const isoDate = dateOfBirth.toISOString()
            setSelectedDate(isoDate)
        }
    }

    useEffect(() => {
        form.setFieldValue('dateOfBirth', selectedDate)
    }, [selectedDate])

    const handleSwitchChange = (switchId: 1 | 2 | 3): void => {
        const newSwitchStates = {
            1: false,
            2: false,
            3: false,
        }
        if (!switchStates[switchId]) {
            newSwitchStates[switchId] = true
            void GetPartnerAddress(
                dispatch,
                partnershipId,
                switchId,
                (addressData: PartnerTogilleAddress) => {
                    setAddressData(addressData)
                }
            )
        }
        setSwitchStates(newSwitchStates)
    }

    useEffect(() => {
        if (addressDatas !== null && typeof addressDatas === 'object') {
            const newFieldValues = {
                partnerAddressOne: addressDatas?.addressLineOne,
                partnerAddressTwo: addressDatas?.addressLineTwo,
                partnerTown: addressDatas?.town,
                partnerCountry: addressDatas?.country,
                partnerPostCode: addressDatas?.postCode,
            }

            form.setFieldsValue(newFieldValues)
        }
    }, [addressDatas])

    const handleIndividualChange = (value: number): void => {
        void GetInduvidualInfo(
            dispatch,
            value,
            (induviduaInformation: IndividualData) => {
                setInduvidualInfo(induviduaInformation)
            }
        )
    }
    useEffect(() => {
        if (induvidualInfo !== null && typeof induvidualInfo === 'object') {
            const newValues = {
                individualId: induvidualInfo?.individualId,
                title: induvidualInfo?.title,
                firstName: induvidualInfo?.firstName,
                middleName: induvidualInfo?.middleName,
                surName: induvidualInfo?.surName,
                dateOfBirth: induvidualInfo?.dateOfBirth,
                partnerAddressOne: induvidualInfo?.addressOne,
                partnerAddressTwo: induvidualInfo?.addressTwo,
                partnerTown: induvidualInfo?.town,
                partnerCountry: induvidualInfo?.country,
                partnerPostCode: induvidualInfo?.postCode,
                mobileNumber: induvidualInfo?.mobileNumber,
                homeNumber: induvidualInfo?.homeNumber,
                workNumber: induvidualInfo?.workNumber,
                emailAddress: induvidualInfo?.emailAddress,
                alternativeEmailAddress:
                    induvidualInfo?.alternativeEmailAddress,
                individualUTR: induvidualInfo?.individualUTR,
                niNumber: induvidualInfo?.niNumber,
                isActive: 'Active',
                isDelete: 'Inactive',
            }
            form.setFieldsValue(newValues)
        }
    }, [induvidualInfo])
    const onPartnerEditData = (): void => {
        void onSaveData()
    }

    const onSaveData = async (): Promise<void> => {
        try {
            await form.validateFields()
            const formdata = form.getFieldsValue()
            const dataToSave = {
                partnerId: 0,
                partnershipId,
                individualId: formdata.individualId,
                tagIndividualId: 0,
                individualClientNumber: '',
                title: formdata.title ?? '',
                firstName: formdata.firstName,
                middleName: formdata.middleName ?? '',
                surName: formdata.surName,
                dateOfBirth:
                    moment(formdata.dateOfBirth).format('DD/MM/YYYY') ?? '',
                partnerAddressOne: formdata.partnerAddressOne,
                partnerAddressTwo: formdata.partnerAddressTwo ?? '',
                partnerTown: formdata.partnerTown,
                partnerCountry: formdata.partnerCountry ?? '',
                partnerPostCode: formdata.partnerPostCode,
                mobileNumber: formdata.mobileNumber,
                homeNumber: formdata.homeNumber ?? '',
                workNumber: formdata.workNumber ?? '',
                emailAddress: formdata.emailAddress,
                alternativeEmailAddress: formdata.alternativeEmailAddress ?? '',
                individualUTR: formdata.individualUTR ?? '',
                niNumber: formdata.niNumber ?? '',
                isActive: 'Active',
                isDelete: 'Inactive',
            }

            await SavePartner(dispatch, dataToSave)
            form.resetFields()
            void getClientCompanyDetails(dispatch, 4, partnershipId, 8)
        } catch (error) {}
    }

    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}
                requiredMark={customizeRequiredMark}
            >
                <Row gutter={16} className={commonStyles.officerButtonMargin}>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Same as Business"
                            labelCol={{ span: 12 }}
                            wrapperCol={{ span: 12 }}
                        >
                            <Switch
                                id="2"
                                checked={switchStates[2]}
                                onChange={() => {
                                    handleSwitchChange(2)
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Same as Correspondance"
                            labelCol={{ span: 12 }}
                            wrapperCol={{ span: 12 }}
                        >
                            <Switch
                                id="3"
                                checked={switchStates[3]}
                                onChange={() => {
                                    handleSwitchChange(3)
                                }}
                            />
                        </Form.Item>
                    </Col>
                </Row>

                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Individual Member"
                            name="individualId"
                        >
                            <Select
                                allowClear
                                placeholder="Please select"
                                onChange={handleIndividualChange}
                                options={InduvidualMemberList}
                                showSearch
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Date of Birth"
                            name="dateOfBirth"
                        >
                            <Space direction="vertical" size={12}>
                                <DatePicker
                                    onChange={onChange}
                                    value={
                                        selectedDate.length > 0
                                            ? dayjs(selectedDate)
                                            : null
                                    }
                                    format="DD/MM/YYYY"
                                    className={commonStyles.dateWidth}
                                />
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData> label="Title" name="title">
                            <Select
                                allowClear
                                placeholder="Please select"
                                onChange={() => {}}
                                defaultValue={'UNKNOWN'}
                                filterOption={(input, option) =>
                                    typeof option?.children === 'string' &&
                                    (option.children as string)
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                                showSearch
                            >
                                <Select.Option value="UNKNOWN">
                                    Unknown
                                </Select.Option>
                                <Select.Option value="MR.">MR.</Select.Option>
                                <Select.Option value="MISS.">
                                    MISS.
                                </Select.Option>
                                <Select.Option value="MRS.">MRS.</Select.Option>
                                <Select.Option value="MS.">MS.</Select.Option>
                                <Select.Option value="DR.">DR.</Select.Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Mobile Number"
                            name="mobileNumber"
                            rules={[
                                {
                                    pattern: /^\d{10,15}$/,
                                    message: 'please enter valid mobile number',
                                },
                                {
                                    required: true,
                                    message: 'Please input your mobile number!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="First Name "
                            name="firstName"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your First Name!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Home Number"
                            name="homeNumber"
                            rules={[
                                {
                                    pattern: /^\d{14}$/,
                                    message: 'please enter valid mobile number',
                                },
                                {
                                    message: 'Please input your mobile number!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Middle Name"
                            name="middleName"
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Work Number"
                            name="workNumber"
                            rules={[
                                {
                                    pattern: /^\d{14}$/,
                                    message: 'please enter valid Work Number',
                                },
                                {
                                    message: 'Please input your Work Number!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="SurName"
                            name="surName"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your SurName!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Email"
                            name="emailAddress"
                            rules={[
                                {
                                    type: 'email',
                                    required: true,
                                    message: 'Please input your email!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Address 1"
                            name="partnerAddressOne"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Address One!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Alternative Email Address"
                            name="alternativeEmailAddress"
                            rules={[
                                {
                                    type: 'email',
                                    message:
                                        'Please input your Alternative Email Address!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Address 2"
                            name="partnerAddressTwo"
                        >
                            <Input />
                        </Form.Item>
                    </Col>

                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="NI Number"
                            name="niNumber"
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>

                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Town"
                            name="partnerTown"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Town!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Individual UTR"
                            name="individualUTR"
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="Country"
                            name="partnerCountry"
                        >
                            <Select
                                allowClear
                                placeholder="Please select"
                                onChange={() => {}}
                                options={countryList?.map((country) => ({
                                    value: country.label,
                                    label: country.label,
                                }))}
                                showSearch
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row
                    gutter={[16, 48]}
                    className={commonStyles.officerButtonMargin}
                >
                    <Col span={12}>
                        <Form.Item<PartnerTapData>
                            label="PostCode"
                            name="partnerPostCode"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your PostCode!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                {ActivePremission('3000', PermissionType.SAVE) && (
                    <Row gutter={[16, 48]}>
                        <Col offset={22} span={2}>
                            <Tooltip title="Save Partner">
                                <Button
                                    type="primary"
                                    onClick={onPartnerEditData}
                                >
                                    <SaveOutlined />
                                </Button>
                            </Tooltip>
                        </Col>
                    </Row>
                )}
            </Form>
        </div>
    )
}
const mapStateToProps = (state: any): PartnersDataInterface => {
    return {
        countryList: state.common.countryList,
        partnershipTaps: state.client.partnershipTaps,
        InduvidualMemberList: state.common.InduvidualMemberList,
    }
}
export default connect(mapStateToProps)(Partners)
