import React, { useEffect, useState } from 'react'
import {
    Form,
    Input,
    Button,
    Switch,
    Row,
    Col,
    Space,
    DatePicker,
    Select,
    type DatePickerProps,
} from 'antd'
import { SaveOutlined } from '@ant-design/icons'
import commonStyles from '../../../../../../Utils/Common.less'
import { connect, useDispatch } from 'react-redux'
import { GetCountryList } from '../../../../../../Services/Common'
import Partnerless from '../Partnershipserviceless.less'
import {
    type TogilleAddress,
    type VatpageStateProp,
    type vatFormInterface,
} from '../../../../../../Types/Client/RegisteredClients/SoleTrader'
import { type ListFrontEndInterface } from '../../../../../../Types/CommonType'
import dayjs from 'dayjs'
import moment from 'moment'
import { GetAddress, SaveVatData } from '../../../../../../Services/SoleTrader'
import ActivePremission from '../../../../../../Utils/premissins'
import { PermissionType } from '../../../../../../Types/Enum/PermissionType'
const { Option } = Select
const VATEditForm = (props: vatFormInterface): React.ReactElement => {
    const { countryList, soletrderId, vateditdata, handleChildFormSave } = props

    const dispatch = useDispatch()
    const [form] = Form.useForm()
    const [VatRegiDate, setVatRegiDate] = useState<string>('')
    const [VatEffictiDate, setVatEffictiDate] = useState<string>('')
    const [EndingDate, setEndingDate] = useState<string>('')
    const [servicesEnabled, setServicesEnabled] = useState(false)
    const [switchStates, setSwitchStates] = useState<{
        1: boolean
        2: boolean
        3: boolean
    }>({
        1: false,
        2: false,
        3: false,
    })
    const [addressDatas, setAddressData] = useState<TogilleAddress | null>(null)
    useEffect(() => {
        if (countryList !== null && vateditdata !== null) {
            const countryData = countryList.find(
                (data: ListFrontEndInterface) =>
                    data.label === vateditdata.country
            )
            const newData = {
                ...vateditdata,
                country: countryData?.label ?? 'Please Select',
            }
            form.setFieldsValue(newData)
            setServicesEnabled(vateditdata.status === 'Active')
        }
    }, [vateditdata, countryList])

    useEffect(() => {
        GetCountryList(dispatch)
    }, [dispatch])

    useEffect(() => {
        form.setFieldsValue(vateditdata)
        if (vateditdata !== null) {
            const vatRegistrationDate = moment(
                vateditdata.vatRegistrationDate,
                'M/D/YYYY h:mm:ss A'
            )
            const formaVatReg = vatRegistrationDate.format('MM/DD/YYYY')
            setVatRegiDate(formaVatReg)

            const effectiveDate = moment(
                vateditdata.effectiveDate,
                'M/D/YYYY h:mm:ss A'
            )
            const formatEffctive = effectiveDate.format('MM/DD/YYYY')
            setVatEffictiDate(formatEffctive)

            const endingDate = moment(
                vateditdata.endingDate,
                'M/D/YYYY h:mm:ss A'
            )
            const formattedDate = endingDate.format('MM/DD/YYYY')
            setEndingDate(formattedDate)
        }
    }, [vateditdata])

    useEffect(() => {
        form.setFieldValue('vatRegistrationDate', VatRegiDate)
        form.setFieldValue('effectiveDate', VatEffictiDate)
        form.setFieldValue('endingDate', EndingDate)
    }, [VatRegiDate, VatEffictiDate, EndingDate])

    const onChangeVR = (
        deadlineDate: DatePickerProps['value'],
        dateString: string | string[]
    ): void => {
        if (deadlineDate != null) {
            const isoDate = deadlineDate.toISOString()
            setVatRegiDate(isoDate)
        }
    }

    const onChangeEF = (
        deadlineDate: DatePickerProps['value'],
        dateString: string | string[]
    ): void => {
        if (deadlineDate != null) {
            const isoDate = deadlineDate.toISOString()
            setVatEffictiDate(isoDate)
        }
    }

    const onChangeED = (
        deadlineDate: DatePickerProps['value'],
        dateString: string | string[]
    ): void => {
        if (deadlineDate != null) {
            const isoDate = deadlineDate.toISOString()
            setEndingDate(isoDate)
        }
    }
    const handleServiceSwitchChange = (checked: boolean): void => {
        setServicesEnabled(checked)
    }

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

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

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

    const handleSave = (): void => {
        void handleSaveData()
    }
    const handleSaveData = async (): Promise<void> => {
        try {
            await form.validateFields()
            const formdata = form.getFieldsValue()

            const vatFrequencyName = formdata.vatFrequencyName
            let vatFrequencynum: number

            if (vatFrequencyName === 'QUATARY') {
                vatFrequencynum = 1
            } else {
                vatFrequencynum = 2
            }

            const dataToSave = {
                vatId: vateditdata.vatId,
                companyType: 2,
                referenceId: soletrderId,
                vatNumber: formdata.vatNumber,
                vatScheme: formdata.vatScheme,
                vatRegistrationDate: moment(
                    formdata.vatRegistrationDate
                ).format('DD/MM/YYYY'),
                addressLineOne: formdata.addressLineOne,
                addressLineTwo: formdata.addressLineTwo,
                town: formdata.town,
                country: formdata.country,
                postCode: formdata.postCode,
                effectiveDate: moment(formdata.effectiveDate).format(
                    'DD/MM/YYYY'
                ),
                endingDate: moment(formdata.endingDate).format('DD/MM/YYYY'),
                dataInput: formdata.dataInput,
                status: servicesEnabled ? 'Active' : 'Inactive',
                hmrcGatewayId: formdata.hmrcGatewayId,
                hmrcPassword: formdata.hmrcPassword,
                vatFrequency: vatFrequencynum ?? 0,
                vatFrequencyName: formdata.vatFrequencyName,
            }
            void SaveVatData(dispatch, dataToSave)
            handleChildFormSave()
        } 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
                form={form}
                name="vat-form"
                layout={'vertical'}
                autoComplete="off"
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                requiredMark={customizeRequiredMark}
            >
                <Row gutter={24} className={Partnerless.services}>
                    <Col span={8}>
                        <Form.Item
                            label="Same as Office"
                            wrapperCol={{ span: 12 }}
                        >
                            <Switch
                                id="1"
                                checked={switchStates[1]}
                                onChange={() => {
                                    handleSwitchChange(1)
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            label="Same as Business"
                            wrapperCol={{ span: 12 }}
                        >
                            <Switch
                                id="2"
                                checked={switchStates[2]}
                                onChange={() => {
                                    handleSwitchChange(2)
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            label="Same as Correspondence"
                            wrapperCol={{ span: 12 }}
                        >
                            <Switch
                                id="3"
                                checked={switchStates[3]}
                                onChange={() => {
                                    handleSwitchChange(3)
                                }}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item
                            name="vatNumber"
                            label="VAT Number"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your VAT Number!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="addressLineOne"
                            label="Address 1"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Address 1!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item label="VAT Scheme" name="vatScheme">
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    typeof option?.children === 'string' && // Ensure option.children is a string
                                    (option.children as string)
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                            >
                                <Option value="STANDARD">STANDARD</Option>
                                <Option value="FLAT RATE">FLAT RATE</Option>
                                <Option value="ANNUAL">ANNUAL</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Address 2" name="addressLineTwo">
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item
                            label="VAT Registration Date"
                            name="vatRegistrationDate"
                        >
                            <Space direction="vertical" size={12}>
                                <DatePicker
                                    className={commonStyles.dateWidth}
                                    onChange={(date, dateString) => {
                                        onChangeVR(date, dateString)
                                    }}
                                    value={
                                        VatRegiDate.length > 0
                                            ? dayjs(VatRegiDate)
                                            : null
                                    }
                                />
                            </Space>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="town"
                            label="Town"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Town!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item
                            label="VAT Effective Date"
                            name="effectiveDate"
                        >
                            <Space direction="vertical" size={12}>
                                <DatePicker
                                    className={commonStyles.dateWidth}
                                    format="MM/DD/YYYY"
                                    onChange={(date, dateString) => {
                                        onChangeEF(date, dateString)
                                    }}
                                    value={
                                        VatEffictiDate.length > 0
                                            ? dayjs(VatEffictiDate)
                                            : null
                                    }
                                />
                            </Space>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Country " name="country">
                            <Select
                                allowClear
                                placeholder="Please select"
                                showSearch
                                onChange={() => {}}
                                options={countryList?.map((country) => ({
                                    value: country.label,
                                    label: country.label,
                                }))}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item
                            label="First Period Ending Date"
                            rules={[
                                {
                                    required: true,
                                    message:
                                        'Please input yourFirst Period Ending Date!',
                                },
                            ]}
                            name="endingDate"
                        >
                            <Space direction="vertical" size={12}>
                                <DatePicker
                                    className={commonStyles.dateWidth}
                                    format="MM/DD/YYYY"
                                    onChange={(date, dateString) => {
                                        onChangeED(date, dateString)
                                    }}
                                    value={
                                        EndingDate.length > 0
                                            ? dayjs(EndingDate)
                                            : null
                                    }
                                />
                            </Space>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="Post Code"
                            name="postCode"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your Post Code!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item label="HMRC Gateway ID" name="hmrcGatewayId">
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Password" name="hmrcPassword">
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16} className={Partnerless.services}>
                    <Col span={12}>
                        <Form.Item
                            label="VAT Frequency"
                            name="vatFrequencyName"
                        >
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    typeof option?.children === 'string' && // Ensure option.children is a string
                                    (option.children as string)
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                            >
                                <Option value="ANNUALY">ANNUALY</Option>
                                <Option value="QUATARY">QUATARY</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Data Input" name="dataInput">
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    typeof option?.children === 'string' && // Ensure option.children is a string
                                    (option.children as string)
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                            >
                                <Option value="ANNUALY">RECEIPT BANK</Option>
                                <Option value="BY POST">BY POST</Option>
                                <Option value="NIL">NIL</Option>
                                <Option value="NOT REQUIRED">
                                    NOT REQUIRED
                                </Option>
                                <Option value="MANUAL PROCESS">
                                    MANUAL PROCESS
                                </Option>
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item
                            label="Enable/Disable Services"
                            name="status"
                            labelCol={{ span: 16 }}
                            wrapperCol={{ span: 8 }}
                        >
                            <Switch
                                onChange={handleServiceSwitchChange}
                                checked={servicesEnabled}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                {ActivePremission('3000', PermissionType.SAVE) && (
                    <Row gutter={16}>
                        <Col offset={22} span={2}>
                            <Button type="primary" onClick={handleSave}>
                                <SaveOutlined />
                            </Button>
                        </Col>
                    </Row>
                )}
            </Form>
        </div>
    )
}

const mapStateToProps = (state: any): VatpageStateProp => {
    return {
        countryList: state.common.countryList,
    }
}
export default connect(mapStateToProps)(VATEditForm)
