import React, { useCallback, useEffect, useRef, useState } from 'react'
import { connect, useDispatch } from 'react-redux'
import { Row, Col, Button, Form, Input, Card } from 'antd'
import { SaveOutlined } from '@ant-design/icons'
import commonStyles from '../../../Utils/Common.less'
import AddNewButton from '../../../Components/AddNewButton'
import S3Upload from '../../../Components/S3Upload'
import {
    SaveAttachment,
    getattachmentdroplist,
} from '../../../Services/Helpdesk/Backlog'
import { type TaskAttachmentinterface } from '../../../Types/Backlog/Backlog'

export const AttachementDefaultData = {
    taskAttachmentId: '',
    taskId: '',
    attachmentFile: '',
    description: '',
}

const AttachementList = (
    props: TaskAttachmentinterface & { taskId: string }
): React.ReactElement => {
    const { taskId, TaskAttachmentList } = props
    const [editMode, setEditMode] = useState(false)
    const dispatch = useDispatch()
    const [form] = Form.useForm()
    const hasFetchedOnce = useRef(false)
    const [taskAttachmentId] = useState('0')
    useEffect(() => {
        form.setFieldsValue({
            taskAttachmentId: '',
            taskId: '',
            attachmentFile: '',
            description: '',
        })
    }, [taskId, dispatch])
    const getTableData = useCallback(() => {
        void getattachmentdroplist(dispatch, taskId)
    }, [taskId])

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

    const setFormData = (name: string, location: string): void => {
        form.setFieldValue(name, location)
    }
    const toggleEditMode = (): void => {
        setEditMode(!editMode)
        form.resetFields()
    }
    const handleSave = (): void => {
        form.validateFields()
            .then((values) => {
                const formattedValues = {
                    ...values,
                    taskAttachmentId,
                    taskId,
                    attachmentFile: values.attachmentFile,
                    description: values.description,
                }
                SaveAttachment(dispatch, formattedValues)
                    .then(() => {
                        setEditMode(false)
                        getTableData()
                    })
                    .catch((error) => {
                        console.error('Failed to save attachment:', error)
                    })
            })
            .catch((errorInfo) => {
                console.log('Validation Failed:', errorInfo)
            })
    }

    return (
        <>
            <Card
                extra={<AddNewButton clickAction={toggleEditMode} />}
                className={commonStyles.card}
            >
                {editMode ? (
                    <Form form={form} onFinish={handleSave}>
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item
                                    label="AttachmentFile"
                                    name="attachmentFile"
                                >
                                    <S3Upload
                                        name={'attachmentFile'}
                                        value={form.getFieldValue(
                                            'attachmentFile'
                                        )}
                                        setFormData={setFormData}
                                        corporate={''}
                                        corporateid={0}
                                        documenttype={''}
                                        documentbaseId={0}
                                        memberpersonId={0}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item
                                    label="Description"
                                    name="description"
                                >
                                    <Input.TextArea rows={4} />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row gutter={16}>
                            <Col offset={22} span={2}>
                                <Button type="primary" htmlType="submit">
                                    <SaveOutlined />
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                ) : (
                    <Row>
                        {TaskAttachmentList.map((attachment) => (
                            <Col
                                key={attachment.taskAttachmentId}
                                // xs={14}
                                // sm={12}
                                // md={8}
                                // lg={6}
                                // xl={4}
                                style={{ marginRight: '10px' }}
                            >
                                <Card
                                    hoverable
                                    className={commonStyles.cardMargin}
                                    style={{ width: 300, height: 250 }}
                                    cover={
                                        <img
                                            alt="attachment"
                                            src={attachment.attachmentFile}
                                            style={{
                                                maxWidth: '300px',
                                                maxHeight: '200px',
                                                height: 'auto',
                                            }}
                                        />
                                    }
                                >
                                    <div style={{ textAlign: 'center' }}>
                                        {attachment.description}
                                    </div>
                                </Card>
                            </Col>
                        ))}
                    </Row>
                )}
            </Card>
        </>
    )
}

const mapStateToProps = (state: any): TaskAttachmentinterface => {
    return {
        TaskAttachmentList: state.backlog.TaskAttachmentList,
        TaskAttachmentListCount: state.backlog.TaskAttachmentListCount,
    }
}

export default connect(mapStateToProps)(AttachementList)
