import React, { useEffect, useState } from 'react'
import {
    Row,
    Col,
    Card,
    Tag,
    Modal,
    Table,
    type TableProps,
    Flex,
    Switch,
} from 'antd'
import styles from './index.less'
import { ReactComponent as ClientGroup } from '../../Assest/Svg/ClientsGroup.svg'
// import { ReactComponent as VerticalThreeDots } from '../../Assest/Svg/VerticalThreeDots.svg'
import ChartDataLabels from 'chartjs-plugin-datalabels'
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    BarElement,
    Title,
    Tooltip,
    Legend,
} from 'chart.js'
import { Bar } from 'react-chartjs-2'
import type {
    GetOverviewResponse,
    InitialClientOverviewDetailStateInterface,
    OverviewDetail,
    OverviewInfo,
} from '../../Types/Overview'
import { randomLightColor } from '../../Utils/randomColorGen'
import { useDispatch, connect } from 'react-redux'
import { GetClientOverviewDetail } from '../../Services/Overview'
import { useNavigate } from 'react-router-dom'

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)

const ONBOARDINGTAB = 'Onboarding'
const REGISTEREDTAB = 'Registered'
const PROSPECTTAB = 'Prospect'

const Clients = (
    {
        totalActiveCount,
        clientInfoList,
        businessTypeInfoList,
        prospectiveClientInfoList,
        serviceActiveInfoList,
        serviceSeparationInfoList,
        overviewServiceStatusList,
    }: GetOverviewResponse,
    props: InitialClientOverviewDetailStateInterface
): React.ReactElement => {
    const getOverviewDetailInfo = props?.overviewDetail
    const dispatch = useDispatch()
    const [isOpenModal, setOpenModal] = useState(false)
    const [divideWord, setDevideword] = useState('Active')
    const handleCancel = (): void => {
        setOpenModal(false)
        setSequenceNo(0)
    }
    const [newClientInfo, setNewClientInfo] = useState<OverviewInfo[]>([])
    const navigate = useNavigate()
    useEffect(() => {
        const newClientInfoList = clientInfoList
            .filter((item) => item.description.split('-')[1] === divideWord)
            .map((item) => ({
                ...item,
                description: item.description.split('-')[0],
            }))

        setNewClientInfo(newClientInfoList)
    }, [clientInfoList, divideWord])
    const getTotal = (list: number[]): number => {
        return list.length > 0
            ? list?.reduce(function (acc, obj) {
                  return acc + Number(obj)
              }, 0)
            : 0
    }

    const apiData: any = {
        Onboarding: {
            labels: newClientInfo?.map((item) => item.description),
            data: newClientInfo?.map((item) => item.recordCount),
            count: getTotal(newClientInfo?.map((item) => item.recordCount)),
            backgroundColors: newClientInfo?.map((item) => randomLightColor()),
        },
        Registered: {
            labels: businessTypeInfoList?.map((item) => item.description),
            data: businessTypeInfoList?.map((item) => item.recordCount),
            count: getTotal(
                businessTypeInfoList?.map((item) => item.recordCount)
            ),
            backgroundColors: businessTypeInfoList?.map((item) =>
                randomLightColor()
            ),
        },
        Prospect: {
            labels: prospectiveClientInfoList?.map((item) => item.description),
            data: prospectiveClientInfoList?.map((item) => item.recordCount),
            count: getTotal(
                prospectiveClientInfoList?.map((item) => item.recordCount)
            ),
            backgroundColors: prospectiveClientInfoList?.map((item) =>
                randomLightColor()
            ),
        },
        total: totalActiveCount ?? 0,
    }

    const [activeTab, setActiveTab] = useState(ONBOARDINGTAB)
    const [chartData, setChartData] = useState({
        labels: apiData[activeTab]?.labels,
        datasets: [
            {
                label: '',
                data: apiData[activeTab]?.data,
                borderColor: 'white',
                backgroundColor: apiData[activeTab]?.backgroundColors,
                barThickness: 20,
                borderRadius: 4,
            },
        ],
    })

    useEffect(() => {
        if (newClientInfo.length > 0) {
            setChartData({
                labels: apiData[activeTab]?.labels,
                datasets: [
                    {
                        label: '',
                        data: apiData[activeTab]?.data,
                        borderColor: 'white',
                        backgroundColor: apiData[activeTab]?.backgroundColors,
                        barThickness: 20,
                        borderRadius: 4,
                    },
                ],
            })
        }
    }, [newClientInfo])

    const [selectedSequenceNo, setSequenceNo] = useState(0)
    const onClick = (event: any, clickedElements: any[]): void => {
        if (clickedElements.length === 0) return
        const { dataIndex, raw } = clickedElements[0].element.$context
        const barLabel = event.chart.data.labels[dataIndex]

        if (activeTab === ONBOARDINGTAB) {
            findSequenceNo(newClientInfo, barLabel, raw)
        }

        if (activeTab === REGISTEREDTAB) {
            findSequenceNo(businessTypeInfoList, barLabel, raw)
        }

        if (activeTab === PROSPECTTAB) {
            findSequenceNo(prospectiveClientInfoList, barLabel, raw)
        }
    }

    useEffect(() => {
        if (selectedSequenceNo > 0) {
            const token = localStorage.getItem('jwtToken')
            const user = localStorage.getItem('user')
            const clientCategoryId =
                user !== null ? JSON.parse(user)?.clientCategoryId : ''
            if (token !== null && token !== undefined) {
                void GetClientOverviewDetail(
                    dispatch,
                    selectedSequenceNo,
                    clientCategoryId,
                    1,
                    10,
                    '=NA=',
                    token
                )
                setOpenModal(true)
            }
        }
    }, [selectedSequenceNo])

    const findSequenceNo = (
        list: OverviewInfo[],
        barLabel: string,
        count: number
    ): void => {
        const findId = list?.find(
            (item) =>
                item.description === barLabel && item.recordCount === count
        )?.sequenceNo
        if (findId !== undefined) {
            setSequenceNo(findId)
        }
    }
    // const [alignChart, setAligin] = useState('end')
    const options: any = {
        indexAxis: 'y',
        barThickness: 'flex',
        maxBarThickness: 30,
        aspectRatio: 1,
        elements: {
            bar: {
                borderWidth: 0.1,
            },
        },
        maintainAspectRatio: false,
        responsive: false,
        onClick,
        plugins: {
            legend: {
                display: false,
            },
            datalabels: {
                color: '#25396F',
                font: {
                    size: 10,
                    weight: 500,
                },
                formatter: (value: any) => {
                    return value
                },
                anchor: (context: any) => {
                    const value = context.dataset.data[context.dataIndex]
                    return value > 200 ? 'center' : 'end'
                },
                align: (context: any) => {
                    const value = context.dataset.data[context.dataIndex]
                    return value > 200 ? 'center' : 'end'
                },
            },
        },
        scales: {
            y: {
                ticks: {
                    color: '#25396F',
                    beginAtZero: true,
                    font: {
                        size: 13,
                        weight: 500,
                    },
                },
                grid: {
                    display: false,
                },
            },
            x: {
                grid: {
                    display: false,
                },
            },
        },
    }

    const onChangeTab = (activeTab: string): void => {
        setActiveTab(activeTab)
        setChartData({
            labels: apiData[activeTab].labels,
            datasets: [
                {
                    label: '',
                    data: apiData[activeTab].data,
                    borderColor: 'white',
                    backgroundColor: apiData[activeTab].backgroundColors,
                    barThickness: 20,
                    borderRadius: 4,
                },
            ],
        })
    }

    const columns: TableProps<OverviewDetail>['columns'] = [
        {
            title: 'Client No',
            dataIndex: 'clientNumber',
            key: 'clientNumber',
        },
        {
            title: 'Client',
            dataIndex: 'clientName',
            key: 'clientName',
        },
    ]
    const onAcitiveIncativechnage = (check: boolean): void => {
        setDevideword(check ? 'Active' : 'Inactive')
    }

    return (
        <div className={styles.marginRight10}>
            <Card className={`${styles.card} ${styles.client__card__height}`}>
                <div className={styles.cardContent}>
                    <Row
                        style={{
                            background: 'white',
                        }}
                    >
                        <Col span={8}>
                            <div
                                style={{ cursor: 'pointer' }}
                                onClick={() => {
                                    navigate(`/clients/registered-clients`)
                                }}
                            >
                                <ClientGroup />
                                <div className={styles.clients__first__left}>
                                    Clients
                                </div>
                            </div>
                        </Col>
                        <Col span={16} className={styles.client__first__middle}>
                            {/* <div className={styles.client__first__middle__text}>
                                Total
                            </div> */}
                            <div
                                className={styles.client__first__middle__count}
                            >
                                {apiData.total}
                            </div>
                            <div className={styles.client__first__middle__text}>
                                <Flex justify="flex-end">
                                    <Switch
                                        checkedChildren="Active"
                                        unCheckedChildren="Inactive"
                                        checked={divideWord === 'Active'}
                                        onChange={(check) => {
                                            onAcitiveIncativechnage(check)
                                        }}
                                    />
                                    {/* <Button
                                        size="small"
                                        onClick={() => {
                                            setDevideword('Active')
                                        }}
                                        className={`${
                                            divideWord === 'Active'
                                                ? styles.client__card__button
                                                : styles.client__card__buttonInactive
                                        }`}
                                    >
                                        Active
                                    </Button>
                                    <Button
                                        size="small"
                                        onClick={() => {
                                            setDevideword('Inactive')
                                        }}
                                        className={`${
                                            divideWord === 'Inactive'
                                                ? styles.client__card__button
                                                : styles.client__card__buttonInactive
                                        }`}
                                    >
                                        In Active
                                    </Button> */}
                                </Flex>
                            </div>
                        </Col>
                        {/* <Col span={2} className={styles.client__first__right}>
                            <VerticalThreeDots />
                        </Col> */}
                    </Row>
                    <Row className={styles.client__second}>
                        <Col span={8} className={styles.client__second__col}>
                            <div className={styles.client__second__number}>
                                <Tag
                                    bordered={false}
                                    color="#ffffff"
                                    className={
                                        styles.client__second__number__tag
                                    }
                                >
                                    {apiData[ONBOARDINGTAB].count}
                                </Tag>
                            </div>
                            <a
                                onClick={() => {
                                    onChangeTab(ONBOARDINGTAB)
                                }}
                                style={{
                                    fontSize: '12px',
                                    color:
                                        activeTab === ONBOARDINGTAB
                                            ? '#306BFF'
                                            : '#5F6D7E',
                                }}
                            >
                                {ONBOARDINGTAB}
                            </a>
                        </Col>
                        <Col span={8} className={styles.client__second__col}>
                            <div className={styles.client__second__number}>
                                <Tag
                                    bordered={false}
                                    color="#ffffff"
                                    className={
                                        styles.client__second__number__tag
                                    }
                                >
                                    {apiData[REGISTEREDTAB].count}
                                </Tag>
                            </div>
                            <a
                                onClick={() => {
                                    onChangeTab(REGISTEREDTAB)
                                }}
                                style={{
                                    fontSize: '12px',
                                    color:
                                        activeTab === REGISTEREDTAB
                                            ? '#306BFF'
                                            : '#5F6D7E',
                                }}
                            >
                                {REGISTEREDTAB}
                            </a>
                        </Col>
                        <Col span={8} className={styles.client__second__col}>
                            <div className={styles.client__second__number}>
                                <Tag
                                    bordered={false}
                                    color="#ffffff"
                                    className={
                                        styles.client__second__number__tag
                                    }
                                >
                                    {apiData[PROSPECTTAB].count}
                                </Tag>
                            </div>
                            <a
                                onClick={() => {
                                    onChangeTab(PROSPECTTAB)
                                }}
                                style={{
                                    fontSize: '12px',
                                    color:
                                        activeTab === PROSPECTTAB
                                            ? '#306BFF'
                                            : '#5F6D7E',
                                }}
                            >
                                {PROSPECTTAB}
                            </a>
                        </Col>
                    </Row>
                    <Row className={styles.client__third}>
                        <Bar
                            options={options}
                            data={chartData}
                            plugins={[ChartDataLabels]}
                            height={180}
                            width={240}
                        />
                    </Row>
                </div>
            </Card>

            <Modal
                width={600}
                title="Overview"
                open={isOpenModal}
                onCancel={handleCancel}
                footer={null}
            >
                <Table
                    columns={columns}
                    dataSource={getOverviewDetailInfo?.overviewDetailList}
                    rowKey="clientNumber"
                />
            </Modal>
        </div>
    )
}

const mapStateToProps = (
    state: any
): InitialClientOverviewDetailStateInterface => {
    return {
        overviewDetail: state.clientOverviewInfo.overviewDetail,
    }
}

export default connect(mapStateToProps)(Clients)
