import { connect, useDispatch } from 'react-redux'
import {
    type InvoiceDetailsListDataTypeInterface,
    type PaidInvoiceProps,
    type PaidInvoiceSateProps,
} from '../../../Types/Invoice/Invoicing'
import commonStyles from '../../../Utils/Common.less'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { Space, Table, Tooltip, type TableProps, Modal } from 'antd'
import { type TableParamsInterface } from '../../../Types/CommonType'
import {
    commonTableParams,
    setCommonTableParamsData,
} from '../../../Utils/CommontTable'
import { GetInvoiceList, GetInvoicePreview } from '../../../Services/Invoice'
import calculatePagination from '../../../Utils/Pagination'
import { type ColumnsType } from 'antd/es/table'
import {
    PhoneOutlined,
    MailOutlined,
    MessageOutlined,
    HistoryOutlined,
    EyeOutlined,
    FilePdfOutlined,
    DownloadOutlined,
} from '@ant-design/icons'
import invoive from './Invoice.less'
import { ReactComponent as Invoice } from '../../../Assest/Svg/invoice.svg'
import UnpaidPhoneCall from './UnpaidInvoiceHistory/phoneCall'
import UnpaidSms from './UnpaidInvoiceHistory/sms'
import InvoiceHistory from '../../../Components/history'
import UnpaidMail from './UnpaidInvoiceHistory/mailModel'
import ComPaidInvoice from './CommunicationStatus/paidInvoice'
import { useNavigate } from 'react-router-dom'
import {
    InvoiceDownload,
    InvoiceUpload,
} from './CommunicationStatus/DownloadInvoice'
import { SaveEmailAttachments } from '../../../Services/Corporate'

const UnPaidInvoiceList = (props: PaidInvoiceProps): React.ReactElement => {
    const {
        invoiceDetailsList,
        invoiceDetailsListCount,
        activeButton,
        searchData,
        resetData,
    } = props
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const [tableParams, setTableParams] =
        useState<TableParamsInterface>(commonTableParams)
    const [currentPage, setCurrentPage] = useState(1)
    const [itemsPerPage, setItemsPerPage] = useState(10)
    const [Phonecallmodel, setPhonecallmodel] = useState(false)
    const [smsmodel, setSMSmodel] = useState(false)
    const [mailmodel, setMailmodel] = useState(false)
    const [Historymodel, setHistorymodel] = useState(false)
    const [PidInvoicemodel, setPidInvoicemodel] = useState(false)
    const [serviceId, setServiceId] = useState(0)
    const [invoiceId, setInvoiceId] = useState(0)
    const [selectedButtonId, setSelectedButtonId] = useState<number | null>(
        null
    )
    const hasFetchedOnce = useRef(false)
    useEffect(() => {
        if (searchData !== null) {
            getTableData()
        }
    }, [searchData])

    const getTableData = useCallback(() => {
        const { pageSize, pageNo, sortOrderList, searchCriteriaList } =
            setCommonTableParamsData(tableParams)
        GetInvoiceList(
            dispatch,
            {
                pageNo,
                pageSize,
                searchCriteriaList,
                sortOrderList,
            },
            searchData ?? undefined,
            activeButton
        )
    }, [
        tableParams?.sorter,
        tableParams.pagination?.current,
        tableParams?.filter,
        searchData,
        resetData,
    ])

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

    const handleDataCountChange = useCallback(() => {
        setTableParams({
            ...tableParams,
            pagination: {
                ...tableParams.pagination,
                total: invoiceDetailsListCount,
            },
        })
    }, [invoiceDetailsListCount])

    useEffect(() => {
        handleDataCountChange()
    }, [handleDataCountChange])

    const handlePageChange = (pageNo: number, pageSize: number): void => {
        window.scrollTo(0, 0)
        setCurrentPage(pageNo)
        setItemsPerPage(pageSize)
    }
    const handlePageSizeChange = (pageSize: number): void => {
        setItemsPerPage(pageSize)
        setCurrentPage(1) // Reset to first page when page size changes
    }

    const pagination = calculatePagination(
        currentPage,
        invoiceDetailsListCount,
        itemsPerPage,
        handlePageSizeChange
    )

    const columns: ColumnsType<InvoiceDetailsListDataTypeInterface> = [
        { title: '#', dataIndex: 'no' },
        {
            title: 'Invoice No',
            dataIndex: 'invoiceNo',
        },
        { title: 'Date', dataIndex: 'invoiceDate' },
        { width: 100, title: 'Number', dataIndex: 'clientNumber' },
        {
            title: 'Client',
            dataIndex: 'clientName',
        },
        { width: 100, title: 'Amount', dataIndex: 'netTotal' },
        {
            title: 'Current Status',
            key: 'CurrentStatus',
            render: (_, record: InvoiceDetailsListDataTypeInterface) => {
                return (
                    <Space size="middle" direction="vertical">
                        <span className={invoive.communicatioStatus}>
                            INVOICED ON {record.invoiceDate}
                        </span>

                        <span>
                            <Space size="middle">
                                <Tooltip title="View Invoice">
                                    <EyeOutlined
                                        className={commonStyles.clickableIcon}
                                        onClick={() => {
                                            onInvoiceviewClick(
                                                record.invoiceId,
                                                record.invoiceNo
                                            )
                                        }}
                                    />
                                </Tooltip>

                                <Tooltip title="Preview Invoice">
                                    <FilePdfOutlined
                                        onClick={() => {
                                            onInvoicePreviewClick(
                                                record.invoiceId
                                            )
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                                <Tooltip title="Send Invoice Mail">
                                    <MailOutlined
                                        onClick={() => {
                                            onSendEmail(record.invoiceId)
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                                <Tooltip title="Paid Invoice">
                                    <Invoice
                                        className={invoive.invoice}
                                        onClick={() => {
                                            openPaidModel(record.invoiceId)
                                        }}
                                    />
                                </Tooltip>
                                <Tooltip title="Download Invoice">
                                    <DownloadOutlined
                                        onClick={() => {
                                            handleDownloadPreviewInvoice(
                                                record.invoiceId
                                            )
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                            </Space>
                        </span>
                    </Space>
                )
            },
        },
        {
            title: 'Communication',
            key: 'action',
            render: (_, record: InvoiceDetailsListDataTypeInterface) => {
                return (
                    <Space size="middle" direction="vertical">
                        <span className={invoive.communicatioStatus}>
                            {record.lastCommunicationStatus}
                        </span>

                        <span>
                            <Space size="middle">
                                <Tooltip title="Communication History">
                                    <HistoryOutlined
                                        onClick={() => {
                                            openHistoryModel(record.invoiceId)
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                                <Tooltip title="Send Mail">
                                    <MailOutlined
                                        onClick={() => {
                                            openMailModel(
                                                record.invoiceId,
                                                record.serviceProcessId
                                            )
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                                <Tooltip title="Send SMS">
                                    <MessageOutlined
                                        onClick={() => {
                                            openSMSModel(
                                                record.invoiceId,
                                                record.serviceProcessId
                                            )
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                                <Tooltip title="Phone Calls">
                                    <PhoneOutlined
                                        onClick={() => {
                                            openPhonecallModel(
                                                record.invoiceId,
                                                record.serviceProcessId
                                            )
                                        }}
                                        className={commonStyles.clickableIcon}
                                    />
                                </Tooltip>
                            </Space>
                        </span>
                    </Space>
                )
            },
        },
    ]
    const onChangeTableParams: TableProps<InvoiceDetailsListDataTypeInterface>['onChange'] =
        (pagination, filters, sorter: any, extra) => {
            handlePageChange(pagination.current ?? 1, pagination.pageSize ?? 10)
            setTableParams({
                ...tableParams,
                pagination,
                sorter: {
                    field: sorter?.field ?? '',
                    order: sorter?.order ?? '',
                },
            })
        }

    const openPhonecallModel = (
        invoiceId: number,
        serviceProcessId: number
    ): void => {
        setInvoiceId(invoiceId)
        setServiceId(serviceProcessId)
        setPhonecallmodel(!Phonecallmodel)
    }

    const openSMSModel = (
        invoiceId: number,
        serviceProcessId: number
    ): void => {
        setInvoiceId(invoiceId)
        setServiceId(serviceProcessId)
        setSMSmodel(!smsmodel)
    }

    const changePhonecallModalStatus = (): void => {
        setPhonecallmodel(!Phonecallmodel)
    }

    const changeSMSModalStatus = (): void => {
        setSMSmodel(!smsmodel)
    }

    const openMailModel = (
        invoiceId: number,
        serviceProcessId: number
    ): void => {
        setInvoiceId(invoiceId)
        setServiceId(serviceProcessId)
        setMailmodel(!mailmodel)
    }

    const changeMailModalStatus = (): void => {
        setMailmodel(!mailmodel)
    }

    const openHistoryModel = (id: number): void => {
        setInvoiceId(id)
        setHistorymodel(!Historymodel)
    }

    const openPaidModel = (id: number): void => {
        setInvoiceId(id)
        setPidInvoicemodel(!PidInvoicemodel)
    }

    const changeHistoryModalStatus = (): void => {
        setSelectedButtonId(null)
        setHistorymodel(!Historymodel)
    }

    const changePaidModalStatus = (): void => {
        setPidInvoicemodel(!PidInvoicemodel)
    }

    const onInvoiceviewClick = (
        InvoiceId: number,
        invoicename: string
    ): void => {
        const invoiceSaveViewStatus = true
        navigate(`/invoicing/invoic-status/view-invoice`, {
            state: { InvoiceId, invoicename, invoiceSaveViewStatus },
        })
    }

    const onInvoicePreviewClick = (InvoiceId: number): void => {
        navigate(`/invoicing/invoic-status/previewInvoice-invoice`, {
            state: { InvoiceId },
        })
    }
    const onSendEmail = (invoiceIds: number): void => {
        const gererateUpload = async (): Promise<void> => {
            const previewDatas = await GetInvoicePreview(dispatch, invoiceIds)
            const uploadurl = await InvoiceUpload(previewDatas)
            const dataToUpload = {
                clientAttachmentId: 0,
                clientEmailId: 0,
                attachmentPath: uploadurl,
                uniqueCode: `InvoiceId_${invoiceIds}`,
            }
            void SaveEmailAttachments(dispatch, dataToUpload)
        }
        void gererateUpload()
        setTimeout(() => {
            navigate(`/invoicing/invoic-status/send-invoiceDetailsEmail`, {
                state: { invoiceIds },
            })
        }, 3000)
    }
    const handleDownloadPreviewInvoice = (InvoiceId: number): void => {
        void downlodaInvoice(InvoiceId)
    }
    const downlodaInvoice = async (InvoiceId: number): Promise<void> => {
        const previewDatas = await GetInvoicePreview(dispatch, InvoiceId)

        try {
            void InvoiceDownload(previewDatas)
        } catch (error) {}
        // navigate(`/invoicing/invoic-status/previewInvoice-invoice`, {
        //     state: { InvoiceId, downloatstatus },
        // })
    }

    const [showMessage, setShowMessage] = useState(false)

    useEffect(() => {
        const timer = setTimeout(() => {
            setShowMessage(true)
        }, 3000)

        // Clear the timer if the component unmounts
        return () => {
            clearTimeout(timer)
        }
    }, [])
    return (
        <>
            <div className={commonStyles.table}>
                {invoiceDetailsList?.length > 0 ? (
                    <Table
                        columns={columns}
                        dataSource={invoiceDetailsList}
                        onChange={onChangeTableParams}
                        pagination={pagination}
                    />
                ) : (
                    <div>
                        {showMessage ? (
                            <h4>No matching data available</h4>
                        ) : (
                            <h4>Loading data...</h4>
                        )}
                    </div>
                )}
            </div>
            <Modal
                footer={null}
                onCancel={changePhonecallModalStatus}
                width={'35%'}
                title={'Phone Calls'}
                open={Phonecallmodel}
            >
                <UnpaidPhoneCall
                    serviceProcessId={serviceId}
                    invoiceIds={invoiceId}
                    changePhoneCallModalStatus={changePhonecallModalStatus}
                />
            </Modal>
            <Modal
                footer={null}
                onCancel={changeSMSModalStatus}
                width={'35%'}
                title={'SMS'}
                open={smsmodel}
            >
                <UnpaidSms
                    serviceProcessId={serviceId}
                    invoiceIds={invoiceId}
                    changeSMSModalStatus={changeSMSModalStatus}
                />
            </Modal>
            <Modal
                footer={null}
                onCancel={changeMailModalStatus}
                width={'35%'}
                title={'Send Email'}
                open={mailmodel}
            >
                <UnpaidMail
                    serviceProcessId={serviceId}
                    invoiceIds={invoiceId}
                    changeMailModalStatus={changeMailModalStatus}
                />
            </Modal>
            <Modal
                footer={null}
                onCancel={changeHistoryModalStatus}
                width={'50%'}
                title={'Communication History'}
                open={Historymodel}
            >
                <InvoiceHistory
                    invoiceIds={invoiceId}
                    seletedButton={selectedButtonId}
                    setButtonID={setSelectedButtonId}
                />
            </Modal>
            <Modal
                footer={null}
                onCancel={changePaidModalStatus}
                width={'35%'}
                title={'Paid Invoice'}
                open={PidInvoicemodel}
            >
                <ComPaidInvoice
                    invoiceIds={invoiceId}
                    changePaidModalStatus={changePaidModalStatus}
                />
            </Modal>
        </>
    )
}
const mapStateToProps = (state: any): PaidInvoiceSateProps => {
    return {
        invoiceDetailsList: state.invoice.invoiceDetailsList,
        invoiceDetailsListCount: state.invoice.invoiceDetailsListCount,
    }
}

export default connect(mapStateToProps)(UnPaidInvoiceList)
