import {
    Col,
    Row,
    Input,
    Form,
    Button,
    Select,
    DatePicker,
    Switch,
    Radio,
    InputNumber,
} from 'antd'
import { connect, useDispatch } from 'react-redux'
import commonStyles from '../../../../Utils/Common.less'
import { SaveOutlined } from '@ant-design/icons'
import React, { useEffect, useRef, useState } from 'react'
import { GetUserList } from '../../../../Services/User'
import {
    GetServiceDropDownList,
    GetPriorityList,
    SaveTask,
} from '../../../../Services/Corporate'
import {
    type CorporateCreateTaskStateInterface,
    type CorporateCreateTaskInterface,
} from '../../../../Types/Client/RegisteredClients/Corporate'
import ActivePremission from '../../../../Utils/premissins'
import { PermissionType } from '../../../../Types/Enum/PermissionType'
type DaysOfWeek =
    | 'IsRepeatOnMon'
    | 'IsRepeatOnTue'
    | 'IsRepeatOnWed'
    | 'IsRepeatOnThu'
    | 'IsRepeatOnFri'
    | 'IsRepeatOnSat'
    | 'IsRepeatOnSun'

const RecurringFrequencyTypeOption = [
    { label: 'Day', value: '1' },
    { label: 'Week', value: '2' },
    { label: 'Month', value: '3' },
    { label: 'Year', value: '4' },
]

const taskTypeOptions = [
    { label: 'Onetime', value: '0' },
    { label: 'Recurring', value: '1' },
]

const reqrutingFrequencyOptions = [
    { label: 'Daily', value: '1' },
    { label: 'Custom', value: '5' },
]

const CorporateCreateTask = (
    props: CorporateCreateTaskInterface
): React.ReactElement => {
    const { serviceDropDownList, userList, priorityDropDownList } = props

    const initialSwitchStates: Record<DaysOfWeek, number> = {
        IsRepeatOnMon: 0,
        IsRepeatOnTue: 0,
        IsRepeatOnWed: 0,
        IsRepeatOnThu: 0,
        IsRepeatOnFri: 0,
        IsRepeatOnSat: 0,
        IsRepeatOnSun: 0,
    }

    const [endsValue, setEndsValue] = useState(0)
    const hasFetchedOnce1 = useRef(false)
    const [form] = Form.useForm()
    const dispatch = useDispatch()
    const hasFetchedOnce = useRef(false)
    useEffect(() => {
        if (!hasFetchedOnce.current) {
            hasFetchedOnce.current = true
            return
        }
        GetUserList(dispatch)
    }, [dispatch, form])

    useEffect(() => {
        if (!hasFetchedOnce1.current) {
            hasFetchedOnce1.current = true
            return
        }
        GetServiceDropDownList(dispatch)
    }, [dispatch, form])

    useEffect(() => {
        GetPriorityList(dispatch)
    }, [dispatch, form])
    const [showInput, setShowInput] = useState(false)

    const handleSelectChange = (value: string): void => {
        if (value === '1') {
            setShowInput(true)
        } else {
            setShowInput(false)
        }
    }
    const [showCustomOptions, setShowCustomOptions] = useState(false)
    const [switchStates, setSwitchStates] = useState(initialSwitchStates)
    const handleRecurringPlanChange = (value: string): void => {
        if (value === '5') {
            setShowCustomOptions(true)
        } else {
            setShowCustomOptions(false)
        }
    }
    const [showToggles, setShowToggles] = useState(false)

    const handleDropdownChange = (value: string): void => {
        if (value === '2') {
            setShowToggles(true)
        } else {
            setShowToggles(false)
        }
    }

    const handleFinish = (): void => {
        const formData = form.getFieldsValue()

        const currentDate = new Date()
        const formattedDate = currentDate.toISOString().split('T')[0]

        const defaultValues = {
            TaskId: 0,
            SortOrder: 0,
            TaskType: 0,
            ClientName: '',
            description: '',
            BusinessType: 1,
            ReferenceId: 4,
            ServiceReferenceId: 0,
            AssignedBy: 1,
            FromDate: formattedDate,
            StatusId: 0,
            NotifyToStatusChange: 0,
            Description: '',
            RecurringFrequency: 0,
            RecurringFrequencyType: 0,
            RecurringFrequencyPeriodId: 0,
            RecurringEnds: 1,
            RecurringOccurrence: 0,
            RecurringEndsOn: '',
            IsRepeatOnSun: 0,
            IsRepeatOnMon: 0,
            IsRepeatOnTue: 0,
            IsRepeatOnWed: 0,
            IsRepeatOnThu: 0,
            IsRepeatOnFri: 0,
            IsRepeatOnSat: 0,
        }

        const dataToSave = {
            ...formData,
            ...defaultValues,
            ...switchStates,
        }

        void SaveTask(dispatch, dataToSave)
        form.resetFields()
        props.onClose()
    }

    const handleSwitchChange = (day: DaysOfWeek, checked: boolean): void => {
        setSwitchStates({ ...switchStates, [day]: checked ? 1 : 0 })
    }

    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: 26 }}
                wrapperCol={{ span: 26 }}
                initialValues={{ remember: true }}
                layout={'vertical'}
                autoComplete="off"
                form={form}
                onFinish={handleFinish}
                requiredMark={customizeRequiredMark}
            >
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item
                            label="Task Name"
                            name="TaskName"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Enter Task Name',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Services" name="ServiceId">
                            <Select
                                allowClear
                                placeholder="Please select"
                                onChange={() => {}}
                                showSearch
                                options={[
                                    { label: 'Please select', value: null },
                                    ...serviceDropDownList?.map((service) => ({
                                        value: service.value,
                                        label: service.label,
                                    })),
                                ]}
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item
                            label="Due Date"
                            name="ToDate"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Enter Due Date!',
                                },
                            ]}
                        >
                            <DatePicker className={commonStyles.dateWidth} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="Priority"
                            name="PriorityId"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Select Priority',
                                },
                            ]}
                        >
                            <Select
                                allowClear
                                placeholder="Please select"
                                onChange={() => {}}
                                showSearch
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                                options={[
                                    { label: 'Please select', value: null },
                                    ...priorityDropDownList?.map((service) => ({
                                        value: service.value,
                                        label: service.label,
                                    })),
                                ]}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item
                            label="Assigned To"
                            name="AssignedTo"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Select Assigned',
                                },
                            ]}
                        >
                            <Select
                                allowClear
                                placeholder="Please select"
                                onChange={() => {}}
                                showSearch
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                                options={[
                                    { label: 'Please select', value: null },
                                    ...userList,
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Description" name="Description">
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item label="Task Type" name="TaskType">
                            <Select
                                onChange={handleSelectChange}
                                showSearch
                                filterOption={(input, option) =>
                                    option?.label
                                        ?.toLowerCase()
                                        .includes(input.toLowerCase()) ?? false
                                }
                                options={taskTypeOptions}
                            />
                        </Form.Item>
                    </Col>
                    {showInput && (
                        <Col span={12}>
                            <Form.Item
                                label="Recurring Plan"
                                name="RecurringFrequencyPeriodId"
                            >
                                <Select
                                    onChange={handleRecurringPlanChange}
                                    showSearch
                                    filterOption={(input, option) =>
                                        option?.label
                                            ?.toLowerCase()
                                            .includes(input.toLowerCase()) ??
                                        false
                                    }
                                    options={reqrutingFrequencyOptions}
                                />
                            </Form.Item>
                        </Col>
                    )}
                    {showCustomOptions && (
                        <>
                            {' '}
                            <Col span={7}>
                                <Form.Item
                                    label="Repeat every"
                                    name="RecurringFrequency"
                                >
                                    <InputNumber
                                        min={0}
                                        max={10}
                                        step={1}
                                        defaultValue={0}
                                        className={commonStyles.repeatWidth}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={15}>
                                <Form.Item
                                    name="RecurringFrequencyType"
                                    label=" "
                                >
                                    <Select
                                        onChange={handleDropdownChange}
                                        showSearch
                                        filterOption={(input, option) =>
                                            option?.label
                                                ?.toLowerCase()
                                                .includes(
                                                    input.toLowerCase()
                                                ) ?? false
                                        }
                                        options={RecurringFrequencyTypeOption}
                                    />
                                </Form.Item>
                            </Col>
                            {showToggles && (
                                <Row gutter={24}>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Mon"
                                            name="IsRepeatOnMon"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnMon ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnMon',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Tue"
                                            name="IsRepeatOnTue"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnTue ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnTue',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Wed"
                                            name="IsRepeatOnWed"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnWed ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnWed',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Thu"
                                            name="IsRepeatOnThu"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnThu ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnThu',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Fri"
                                            name="IsRepeatOnFri"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnFri ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnFri',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Sat"
                                            name="IsRepeatOnSat"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnSat ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnSat',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Sun"
                                            name="IsRepeatOnSun"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.IsRepeatOnSun ===
                                                    1
                                                }
                                                onChange={(checked) => {
                                                    handleSwitchChange(
                                                        'IsRepeatOnSun',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                </Row>
                            )}
                            <Row gutter={24}>
                                <Col span={3}>
                                    <Form.Item
                                        label="Ends"
                                        name="RecurringEnds"
                                    >
                                        <Radio
                                            value="1"
                                            checked={endsValue === 1}
                                            onChange={() => {
                                                setEndsValue(1)
                                            }}
                                        >
                                            never
                                        </Radio>
                                    </Form.Item>
                                </Col>
                                <Col span={3}>
                                    <Form.Item label=" " name="RecurringEnds">
                                        <Radio
                                            value="2"
                                            checked={endsValue === 2}
                                            onChange={() => {
                                                setEndsValue(2)
                                            }}
                                        >
                                            on
                                        </Radio>
                                    </Form.Item>
                                </Col>
                                <Col span={7}>
                                    <Form.Item label=" " name="RecurringEndsOn">
                                        <DatePicker
                                            disabled={endsValue !== 2}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={3}>
                                    <Form.Item label=" " name="RecurringEnds">
                                        <Radio
                                            value="3"
                                            checked={endsValue === 3}
                                            onChange={() => {
                                                setEndsValue(3)
                                            }}
                                        >
                                            After
                                        </Radio>
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Row align="middle">
                                        <Col span={13}>
                                            <Form.Item
                                                name="RecurringOccurrence"
                                                label=" "
                                            >
                                                <InputNumber
                                                    min={0}
                                                    max={10}
                                                    step={1}
                                                    defaultValue={0}
                                                    className={
                                                        commonStyles.recureWidth
                                                    }
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={10}>
                                            <span>Occurrences</span>
                                        </Col>
                                    </Row>
                                </Col>
                            </Row>
                        </>
                    )}
                </Row>
                {ActivePremission('3000', PermissionType.SAVE) ? (
                    <Row gutter={16}>
                        <Col offset={22} span={2}>
                            <Button type="primary" htmlType="submit">
                                <SaveOutlined />
                            </Button>
                        </Col>
                    </Row>
                ) : (
                    <></>
                )}
            </Form>
        </div>
    )
}

const mapStateToProps = (state: any): CorporateCreateTaskStateInterface => {
    return {
        userList: state.user.userList,
        serviceDropDownList: state.initial.serviceDropDownList,
        priorityDropDownList: state.client.priorityDropDownList,
    }
}

export default connect(mapStateToProps)(CorporateCreateTask)
