/* eslint-disable @typescript-eslint/strict-boolean-expressions */

import React, { useEffect, useRef, useState } from 'react'
import { Col, Row, Form, Button, Select, Card, Tooltip } from 'antd'
import { connect, useDispatch } from 'react-redux'
import { CloudDownloadOutlined } from '@ant-design/icons'
import commonStyles from '../../../Utils/Common.less'
import { GetCategoryDropDownList } from '../../../Services/GroupAndPartners'
import { GetRegisteClientDetails } from '../../../Services/Common'
import { GetServiceDropDownList } from '../../../Services/Corporate'
import hederimage from '../../../Assest/Svg/pattern-2.svg'

import {
    type MissReportsData,
    type MissigInformationReportType,
} from '../../../Types/Reports'
import { GetMissingReportData } from '../../../Services/Reports'
import { missinglist } from '../../../Services/MissingInformation/PrpertyView'

import 'jspdf-autotable'
import { jsPDF } from 'jspdf'

const MissingInformation = (
    props: MissigInformationReportType
): React.ReactElement => {
    const { categoryDropDownList, missingdroplist, regiterClientDetails } =
        props
    const [noRecordsFound, setNoRecordsFound] = useState(false)
    const [form] = Form.useForm()
    const dispatch = useDispatch()
    const [selectedMissingId, setSelectedMissingId] = useState(0)
    const [selectedCompanyGroupId, setSelectedCompanyGroupsId] = useState(0)
    const [selectedBusinessId, setSelectedBusinessId] = useState(0)
    const hasFetchedOnce = useRef(false)
    useEffect(() => {
        if (!hasFetchedOnce.current) {
            hasFetchedOnce.current = true
            return
        }
        GetCategoryDropDownList(dispatch)
        GetRegisteClientDetails(dispatch)
        GetServiceDropDownList(dispatch)
        missinglist(dispatch)
    }, [dispatch])

    const handleSelectChangeMissingInfo = (value: number): void => {
        setSelectedMissingId(value)
    }

    const handleSelectChangeCompanyGroup = (value: number): void => {
        setSelectedCompanyGroupsId(value)
    }

    const handleSelectChangeBusinesType = (value: number): void => {
        setSelectedBusinessId(value)
    }

    const customizeRequiredMark = (
        label: React.ReactNode,
        { required }: { required: boolean }
    ): React.ReactElement => (
        <>
            {label}
            &nbsp;
            {required && <span className={commonStyles.requireIcon}>*</span>}
        </>
    )

    const getTabledata = async (): Promise<void> => {
        try {
            await form.validateFields()
            const reportData: MissReportsData = await GetMissingReportData(
                dispatch,
                selectedMissingId,
                selectedBusinessId,
                selectedCompanyGroupId
            )
            if (
                reportData?.missedInfos !== null &&
                reportData?.missedInfos !== undefined &&
                reportData?.missedInfos.length > 0
            ) {
                handleDownloadPDF(reportData)
                setNoRecordsFound(false)
            } else {
                setNoRecordsFound(true)
            }
        } catch (error) {
            console.error('Error fetching report data:', error)
        }
    }

    const getMissingCategoryLabel = (id: number): string => {
        if (id === 0) return 'All'
        const category = missingdroplist.find((item) => item.value === id)
        return category != null ? category.label : id.toString()
    }

    const getCompanyGroupLabel = (id: number): string => {
        if (id === 0) return 'All'
        const group = categoryDropDownList.find((item) => item.value === id)
        return group != null ? group.label : id.toString()
    }

    const handleDownloadPDF = (data: any): void => {
        // eslint-disable-next-line new-cap
        const doc = new jsPDF()
        const missingCompanyCategoryLabel = getCompanyGroupLabel(
            selectedCompanyGroupId
        )
        const headerColor: [number, number, number] = [0, 51, 153]
        doc.setTextColor(headerColor[0], headerColor[1], headerColor[2])
        const headerFontSize = 18
        const subHeaderFontSize = 20
        const addressFontSize = 10
        const categoryFontSize = 10
        const img = new Image()
        img.src = hederimage

        img.onload = function () {
            const canvas = document.createElement('canvas')
            canvas.width = img.width
            canvas.height = img.height
            const ctx = canvas.getContext('2d')
            ctx?.drawImage(img, 0, 0, img.width, img.height)
            const dataUrl = canvas.toDataURL('image/png')
            const logo = data?.businessDocumentTemplate?.companyLogo
            const marginTop = 5
            const marginLeftRight = 10
            const imageWidth =
                doc.internal.pageSize.getWidth() - 2 * marginLeftRight

            doc.addImage(
                dataUrl,
                'PNG',
                marginLeftRight,
                marginTop,
                imageWidth,
                5
            )

            const logoWidth = 50
            const logoHeight = 10
            const logoXPosition =
                doc.internal.pageSize.getWidth() - logoWidth - 10
            const logoYPosition = marginTop + 10

            if (logo) {
                doc.addImage(
                    logo,
                    'PNG',
                    logoXPosition,
                    logoYPosition,
                    logoWidth,
                    logoHeight
                )
            }

            const textXPosition = 14
            const textYPosition = logoYPosition + marginTop

            doc.setFontSize(headerFontSize)
            doc.setTextColor(0, 51, 153)
            doc.text(missingCompanyCategoryLabel, textXPosition, textYPosition)

            const addressYPosition = textYPosition + 5
            doc.setFontSize(addressFontSize)
            doc.setTextColor(160, 160, 160)
            doc.text(
                '14 Elm Road, Chessington, KT9 1AW, UNITED KINGDOM',
                textXPosition,
                addressYPosition
            )

            const subHeaderYPosition = addressYPosition + 10
            doc.setFontSize(subHeaderFontSize)
            doc.setTextColor(0, 51, 153)
            doc.text('Missing Info Report', textXPosition, subHeaderYPosition)

            const lineStartX =
                textXPosition + doc.getTextWidth('Missing Info Report') + 5
            const lineEndX = lineStartX + 80
            const lineY = subHeaderYPosition
            doc.setDrawColor(0, 51, 153)
            doc.setLineWidth(1)
            doc.line(lineStartX, lineY, lineEndX, lineY)

            doc.setFontSize(categoryFontSize)
            doc.setTextColor(0, 0, 0)
            const missingCategoryLabel =
                getMissingCategoryLabel(selectedMissingId)
            doc.text(
                `Missing Category Name: ${missingCategoryLabel}`,
                textXPosition,
                lineY + 10
            )

            const headers = [['Company Name', 'Client Number']]
            const tabledata = (data?.missedInfos || []).map(
                (item: { companyName: any; clientNumber: any }) => [
                    item.companyName,
                    item.clientNumber,
                ]
            )

            doc.autoTable({
                head: headers,
                body: tabledata,
                startY: lineY + 20,
                theme: 'grid',
                styles: {
                    halign: 'left',
                },
                headStyles: {
                    fillColor: [255, 255, 255],
                    textColor: [0, 0, 0],
                    lineColor: [160, 160, 160],
                    lineWidth: 0.05,
                },
            })

            const today = new Date()
            const formattedDate = `${
                today.getMonth() + 1
            }/${today.getDate()}/${today.getFullYear()}`
            const totalPages = doc.getNumberOfPages()

            for (let i = 1; i <= totalPages; i++) {
                doc.setPage(i)
                doc.setFontSize(10)

                const footerText = `Printed on: ${formattedDate} ${i}/${totalPages} Total Count: ${tabledata?.length}`
                const textWidth = doc.getTextWidth(footerText)
                const pageWidth = doc.internal.pageSize.getWidth()
                const xPosition = (pageWidth - textWidth) / 2
                const yPosition = doc.internal.pageSize.getHeight() - 10

                doc.text(footerText, xPosition, yPosition)
            }

            doc.save('Missing_Info_report.pdf')
        }
    }

    return (
        <>
            <Card title="Missing Info Reports" style={{ marginTop: '20px' }}>
                <div className={commonStyles.formWrapper}>
                    <Form
                        name="complex-form"
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                        initialValues={{ remember: true }}
                        layout={'vertical'}
                        autoComplete="off"
                        form={form}
                        requiredMark={customizeRequiredMark}
                    >
                        <Row gutter={16}>
                            <Col span={8}>
                                <Form.Item label="Missing Category">
                                    <Select
                                        placeholder="Please select"
                                        onChange={handleSelectChangeMissingInfo}
                                        value={selectedMissingId}
                                        allowClear
                                        showSearch
                                        filterOption={(input, option) =>
                                            (option?.label ?? '')
                                                .toLowerCase()
                                                .includes(input.toLowerCase())
                                        }
                                        options={[
                                            { value: 0, label: 'All' },
                                            ...missingdroplist,
                                        ]}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label="Company Group">
                                    <Select
                                        placeholder="Please select"
                                        onChange={
                                            handleSelectChangeCompanyGroup
                                        }
                                        value={selectedCompanyGroupId}
                                        allowClear
                                        showSearch
                                        filterOption={(input, option) =>
                                            (option?.label ?? '')
                                                .toLowerCase()
                                                .includes(input.toLowerCase())
                                        }
                                        options={[
                                            { value: 0, label: 'All' },
                                            ...categoryDropDownList,
                                        ]}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label="Business Type">
                                    <Select
                                        placeholder="Please select"
                                        onChange={handleSelectChangeBusinesType}
                                        value={selectedBusinessId}
                                        allowClear
                                        showSearch
                                        filterOption={(input, option) =>
                                            (option?.label ?? '')
                                                .toLowerCase()
                                                .includes(input.toLowerCase())
                                        }
                                        options={[
                                            { value: 0, label: 'All' },
                                            ...regiterClientDetails,
                                        ]}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col offset={22} span={2}>
                                <Tooltip title="Download Report">
                                    <Button
                                        type="primary"
                                        // eslint-disable-next-line @typescript-eslint/no-misused-promises
                                        onClick={getTabledata}
                                    >
                                        <CloudDownloadOutlined />
                                    </Button>
                                </Tooltip>
                            </Col>
                        </Row>
                    </Form>
                </div>
                {noRecordsFound && (
                    <div style={{ textAlign: 'left', marginTop: '20px' }}>
                        <span
                            style={{
                                color: '#808080',
                                fontSize: '20px',
                                fontWeight: 'bold',
                            }}
                        >
                            {' '}
                            No Records found
                        </span>
                    </div>
                )}
            </Card>
        </>
    )
}

const mapStateToProps = (state: any): MissigInformationReportType => {
    return {
        categoryDropDownList: state.initial.categoryDropDownList,
        regiterClientDetails: state.common.regiterClientDetails,
        missingreportStatusList: state.reports.missingreportStatusList,
        missingdroplist: state.missing.missingdroplist,
    }
}

export default connect(mapStateToProps)(MissingInformation)
