import {
    Col,
    Row,
    Input,
    Form,
    Button,
    Select,
    DatePicker,
    Switch,
    Radio,
    InputNumber,
    type DatePickerProps,
    Space,
    type SelectProps,
    Tooltip,
} from 'antd'
import { connect, useDispatch } from 'react-redux'
import commonStyles from '../Utils/Common.less'
import { SaveOutlined } from '@ant-design/icons'
import styles from '../Layouts/Less/style.less'
import React, { useEffect, useRef, useState } from 'react'
import { GetUserList } from '../Services/User'
import axios from '../Config/AxiosConfig'

import {
    SaveTask,
    getAllDepartment,
    getProjectlist,
} from '../Services/Helpdesk/CreteTask'
import dayjs from 'dayjs'
import { GetTierList } from '../Services/ProjectManagement'
import { type ListFrontEndInterface } from '../Types/CommonType'
import { ErrorMessage } from '../Utils/Notification'

import { type taskstate } from '../Types/HelpDesk/Cretetask'
import { GetPriorityList } from '../Services/Corporate'
import {
    type ProjectManagmentFormDataInterface,
    type ProjectManagmentTierListDataTypeInterface,
} from '../Types/ProjectMangement'
import { type CorporateEntity } from '../Types/Globelserch'
import moment from 'moment'

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' },
]

export interface tasksatestateIn {
    userList: ListFrontEndInterface[]
    priorityDropDownList: ListFrontEndInterface[]
    clientDropDownList: CorporateEntity[]
    ProjectManagmentList: ProjectManagmentFormDataInterface[]
    projectDropDownList: ListFrontEndInterface[]
    allDepartmentList: ListFrontEndInterface[]
    ProjectManagmentTierList: ProjectManagmentTierListDataTypeInterface[]
    onClose: () => void
    resetdata: string
    setResetData: React.Dispatch<React.SetStateAction<string>>
}
const CreateTask = (props: tasksatestateIn): React.ReactElement => {
    const {
        userList,
        priorityDropDownList,
        projectDropDownList,
        allDepartmentList,
        ProjectManagmentTierList,
        onClose,
        resetdata,
        setResetData,
    } = props

    const [data, setData] = useState<SelectProps['options']>([])
    const [selectedDate, setSelectedDate] = useState<string>('')
    const [isLoading, setLoading] = useState<boolean>(false)
    const [searchValue, setSearchValue] = useState<string>('')
    const initialSwitchStates: Record<DaysOfWeek, number> = {
        isRepeatOnMon: 0,
        isRepeatOnTue: 0,
        isRepeatOnWed: 0,
        isRepeatOnThu: 0,
        isRepeatOnFri: 0,
        isRepeatOnSat: 0,
        isRepeatOnSun: 0,
    }
    const [endsValue, setEndsValue] = useState(1)
    const [form] = Form.useForm()
    const dispatch = useDispatch()
    const [showInput, setShowInput] = useState(false)
    const [showCustomOptions, setShowCustomOptions] = useState(false)
    const [switchStates, setSwitchStates] = useState(initialSwitchStates)
    const [showToggles, setShowToggles] = useState(false)

    const [selectedDepartment, setSelectedDepartment] = useState<number>(1)
    const [selectedProjectID, setSelectedProjectID] = useState<number>(1)
    const [selectedTierID, setSelectedTierID] = useState<number>(1)
    const user = localStorage.getItem('user')
    const userId = user !== null ? JSON.parse(user)?.userId : ''
    const hasFetchedOnce = useRef(false)
    const [clientNumber, setClientNumber] = useState('')
    useEffect(() => {
        if (!hasFetchedOnce.current) {
            hasFetchedOnce.current = true
            return
        }
        GetUserList(dispatch)
        getAllDepartment(dispatch)
        GetPriorityList(dispatch)
    }, [dispatch, form])

    useEffect(() => {
        if (resetdata === 'true') {
            form.resetFields()
        }

        setResetData('false')
    }, [resetdata])
    useEffect(() => {
        getProjectlist(dispatch, selectedDepartment)
    }, [selectedDepartment])

    useEffect(() => {
        GetTierList(dispatch, selectedProjectID.toString())
    }, [selectedProjectID])

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

    const onChange = (
        date: DatePickerProps['value'],
        dateString: string | string[]
    ): void => {
        if (date !== null && date !== undefined) {
            const isoDate = date.toISOString()
            setSelectedDate(isoDate)
        }
    }

    const handleSelectChange = (value: string): void => {
        if (value === '1') {
            setShowInput(true)
        } else {
            setShowInput(false)
        }
    }

    const handleRecurringPlanChange = (value: string): void => {
        if (value === '5') {
            setShowCustomOptions(true)
        } else {
            setShowCustomOptions(false)
        }
    }

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

    const customizeRequiredMark = (
        label: React.ReactNode,
        { required }: { required: boolean }
    ): React.ReactElement => (
        <>
            {label}
            &nbsp;
            {required && <span className={commonStyles.requireIcon}>*</span>}
        </>
    )
    const GetStandardListingTwo = async (search: string): Promise<void> => {
        setLoading(true)
        await axios
            .get(`api/GetStandardListingTwo/1/${search}`)
            .then((response: any) => {
                if (response.status === 200) {
                    const clients = response?.data?.data

                    const newData = clients?.map((client: any) => {
                        return {
                            label: client.displayName,
                            value: client.id,
                            desc: (
                                <div>
                                    <div
                                        className={styles.clintDropdownListDiv}
                                    >
                                        <span>{client.displayName}</span>
                                    </div>
                                    <div>
                                        <span>
                                            {client.additionalDataTwo}-
                                            {client.additionalDataOne}
                                        </span>
                                    </div>
                                    <div>
                                        <span
                                            className={
                                                styles.clientDropdownListSpan
                                            }
                                        >
                                            Name-{client.additionalDataThree}
                                        </span>
                                        <span
                                            className={
                                                styles.clientDropdownListSpan2
                                            }
                                        ></span>
                                        <span
                                            className={
                                                styles.clientDropdownListSpan
                                            }
                                        >
                                            ContactNo-
                                            {client.additionalDataFour}
                                        </span>
                                    </div>
                                    <div>
                                        <span>
                                            Email-{client.additionalDataFive}
                                        </span>
                                    </div>
                                </div>
                            ),
                        }
                    })
                    setData(newData)
                    setLoading(false)
                } else {
                    setLoading(false)
                    ErrorMessage('Record Not Found')
                }
            })
            .catch(() => {
                setLoading(false)
                //
            })
    }
    useEffect(() => {
        if (
            searchValue !== null &&
            searchValue !== undefined &&
            searchValue !== '' &&
            searchValue?.length > 2
        ) {
            void GetStandardListingTwo(searchValue)
        }
    }, [searchValue])

    const handleFinish = (): void => {
        void handleFinishData()
    }
    const handleFinishData = async (): Promise<void> => {
        try {
            await form.validateFields()
            const formData = form.getFieldsValue()
            const formattoDateEnd = dayjs(formData.recurringEndsOn).format(
                'DD/MM/YYYY'
            )
            const formattoDate = dayjs(formData.toDate).format('DD/MM/YYYY')
            const formatfromDate = dayjs(formData.fromDate).format('DD/MM/YYYY')
            const clientName = data?.find(
                (client) => client.value === formData.clientName
            )
            const namepart = clientNumber.split('-')
            let referenceId = 0
            if (namepart[1] !== null && namepart[1] !== undefined) {
                referenceId = Number(namepart[1])
            } else {
                referenceId = 0
            }
            const datatosave = {
                taskId: 0,
                taskNo: formData.taskNo ?? '',
                taskName: formData.taskName ?? '',
                sortOrder: formData.sortOrder ?? 0,
                taskType: formData.taskType ?? 0,
                clientName: clientName?.label?.toString() ?? '',
                priorityId: formData.priorityId ?? 0,
                businessType: namepart[0] === '' ? 0 : Number(namepart[0]),
                referenceId: referenceId ?? 0,
                serviceReferenceId: formData.serviceReferenceId ?? 0,
                assignedBy: userId ?? 0,
                fromDate: formatfromDate ?? '',
                statusId: formData.statusId ?? 0,
                notifyToStatusChange: formData.notifyToStatusChange ?? 0,
                description: formData.description ?? '',
                recurringFrequency: formData.recurringFrequency ?? 0,
                recurringFrequencyType: formData.recurringFrequencyType ?? 0,
                recurringFrequencyPeriodId:
                    formData.recurringFrequencyPeriodId ?? 0,
                recurringEnds: formData.recurringEnds ?? 0,
                recurringOccurrence: formData.recurringOccurrence ?? 0,
                recurringEndsOn: formattoDateEnd ?? '',
                serviceId: formData.serviceId ?? 0,
                assignedTo: formData.assignedTo ?? 0,
                toDate: formattoDate ?? '',
                projectId: formData.projectId ?? 0,
                departmentId: formData.departmentId ?? 0,
                projectTierId: selectedTierID,
                sprintId: 0,
                ...switchStates,
            }

            void SaveTask(dispatch, datatosave)
            onClose()
        } catch {}
    }

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

    const handleDepartmentChange = (value: number): void => {
        setSelectedDepartment(value)
    }

    const handleProjectChange = (value: number): void => {
        setSelectedProjectID(value)
    }

    const handleTierChange = (value: number): void => {
        setSelectedTierID(value)
    }
    const handleClientChange = (value: string): void => {
        setClientNumber(value)
    }

    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}
            >
                <Form.Item name="TaskId" hidden={true}>
                    <Input />
                </Form.Item>
                <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="Client"
                            name="clientName"
                            // rules={[
                            //     {
                            //         required: true,
                            //         message: 'Please input your clientName!',
                            //     },
                            // ]}
                        >
                            <Select
                                loading={isLoading}
                                showSearch
                                placeholder="To filter the clients by number /name"
                                onSearch={(value) => {
                                    setSearchValue(value)
                                }}
                                onChange={(value) => {
                                    handleClientChange(value)
                                }}
                                filterOption={false}
                                allowClear
                                onClear={() => {
                                    setData([])
                                }}
                                optionLabelProp="label"
                                options={data}
                                optionRender={(option) => (
                                    <>{option.data.desc}</>
                                )}
                                notFoundContent={null}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item
                            label="Due Date"
                            name="toDate"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Select Due Date!',
                                },
                            ]}
                        >
                            <Space>
                                <DatePicker
                                    format="DD/MM/YYYY"
                                    onChange={(date, dateString) => {
                                        onChange(date, dateString)
                                    }}
                                    value={
                                        selectedDate?.length > 0
                                            ? dayjs(selectedDate)
                                            : null
                                    }
                                    disabledDate={(current) =>
                                        current !== null &&
                                        current < moment().startOf('day')
                                    }
                                    className={commonStyles.dateWidth}
                                    placeholder="Select due date"
                                />
                            </Space>
                        </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: 0 },
                                    ...priorityDropDownList?.map(
                                        (service: ListFrontEndInterface) => ({
                                            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: 0 },
                                    ...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="Department"
                            name="departmentId"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Enter Department Name',
                                },
                            ]}
                        >
                            <Select
                                showSearch
                                allowClear
                                placeholder="Please Select"
                                onChange={handleDepartmentChange}
                                filterOption={(input, option) =>
                                    !(option == null) &&
                                    option.label
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                                options={[
                                    { label: 'Please Select', value: 0 },
                                    ...allDepartmentList.map((item) => ({
                                        label: item.label,
                                        value: item.value,
                                    })),
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="Project"
                            name="projectId"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please Enter Project Name',
                                },
                            ]}
                        >
                            <Select
                                showSearch
                                allowClear
                                placeholder="Please Select"
                                onChange={handleProjectChange}
                                filterOption={(input, option) =>
                                    !(option == null) &&
                                    option.label
                                        .toLowerCase()
                                        .includes(input.toLowerCase())
                                }
                                options={[
                                    { label: 'Please select', value: 0 },
                                    ...projectDropDownList.map((item) => ({
                                        label: item.label,
                                        value: item.value,
                                    })),
                                ]}
                                disabled={selectedDepartment === 1}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item label="Project Tier" name="projectTierId">
                            <Select
                                showSearch
                                allowClear
                                placeholder="Please Select"
                                onChange={handleTierChange}
                                filterOption={(input, option) => {
                                    if (typeof option?.label === 'string') {
                                        return option.label
                                            .toLowerCase()
                                            .includes(input.toLowerCase())
                                    }
                                    return false
                                }}
                                options={[
                                    { label: 'Please select', value: 0 },
                                    ...ProjectManagmentTierList.map((item) => ({
                                        label: item.projectTierName,
                                        value: item.projectTierId,
                                    })),
                                ]}
                                disabled={selectedProjectID === 1}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="Task Type" name="taskTypeName">
                            <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={5}>
                                <Form.Item
                                    label="Repeat every"
                                    name="recurringFrequency"
                                >
                                    <InputNumber
                                        min={0}
                                        max={10}
                                        step={1}
                                        defaultValue={0}
                                        className={commonStyles.repeatWidth}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={7}>
                                <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: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnMon',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Tue"
                                            name="isRepeatOnTue"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.isRepeatOnTue ===
                                                    1
                                                }
                                                onChange={(
                                                    checked: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnTue',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Wed"
                                            name="isRepeatOnWed"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.isRepeatOnWed ===
                                                    1
                                                }
                                                onChange={(
                                                    checked: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnWed',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Thu"
                                            name="isRepeatOnThu"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.isRepeatOnThu ===
                                                    1
                                                }
                                                onChange={(
                                                    checked: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnThu',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Fri"
                                            name="isRepeatOnFri"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.isRepeatOnFri ===
                                                    1
                                                }
                                                onChange={(
                                                    checked: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnFri',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Sat"
                                            name="isRepeatOnSat"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.isRepeatOnSat ===
                                                    1
                                                }
                                                onChange={(
                                                    checked: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnSat',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={3}>
                                        <Form.Item
                                            label="Sun"
                                            name="isRepeatOnSun"
                                        >
                                            <Switch
                                                checked={
                                                    switchStates.isRepeatOnSun ===
                                                    1
                                                }
                                                onChange={(
                                                    checked: boolean
                                                ) => {
                                                    handleSwitchChange(
                                                        'isRepeatOnSun',
                                                        checked
                                                    )
                                                }}
                                            />
                                        </Form.Item>
                                    </Col>
                                </Row>
                            )}
                            <Row gutter={24}>
                                <Col span={3}>
                                    <Form.Item label=" " 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={14}>
                                            <Form.Item
                                                name="recurringOccurrence"
                                                label=" "
                                            >
                                                <InputNumber
                                                    min={0}
                                                    max={10}
                                                    step={1}
                                                    defaultValue={0}
                                                    disabled={endsValue !== 3}
                                                    className={
                                                        commonStyles.recureWidth
                                                    }
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={10}>
                                            <span>Occurrences</span>
                                        </Col>
                                    </Row>
                                </Col>
                            </Row>
                        </>
                    )}
                </Row>
                <Row gutter={16}>
                    <Col offset={22} span={2}>
                        <Tooltip title="Save Task">
                            <Button type="primary" htmlType="submit">
                                <SaveOutlined />
                            </Button>
                        </Tooltip>
                    </Col>
                </Row>
            </Form>
        </div>
    )
}

const mapStateToProps = (state: any): taskstate => {
    return {
        userList: state.user.userList,
        clientDropDownList: state.invoice.clientDropDownList,
        priorityDropDownList: state.client.priorityDropDownList,
        ProjectManagmentList: state.initial.ProjectManagmentList,
        projectDropDownList: state.helpdesk.projectDropDownList,
        allDepartmentList: state.helpdesk.allDepartmentList,
        ProjectManagmentTierList: state.initial.ProjectManagmentTierList,
    }
}

export default connect(mapStateToProps)(CreateTask)
