import * as icon from '@mdi/js';
import Head from 'next/head'
import React from 'react'
import axios from 'axios';
import type { ReactElement } from 'react'
import LayoutAuthenticated from '../layouts/Authenticated'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import BaseIcon from "../components/BaseIcon";
import { getPageTitle } from '../config'
import Link from "next/link";

import { hasPermission } from "../helpers/userPermissions";
import { fetchWidgets } from '../stores/roles/rolesSlice';
import { WidgetCreator } from '../components/WidgetCreator/WidgetCreator';
import { SmartWidget } from '../components/SmartWidget/SmartWidget';

import { useAppDispatch, useAppSelector } from '../stores/hooks';
const Dashboard = () => {
    const dispatch = useAppDispatch();
    const iconsColor = useAppSelector((state) => state.style.iconsColor);
    const corners = useAppSelector((state) => state.style.corners);
    const cardsStyle = useAppSelector((state) => state.style.cardsStyle);

    const loadingMessage = 'Loading...';

    
    const [users, setUsers] = React.useState(loadingMessage);
    const [roles, setRoles] = React.useState(loadingMessage);
    const [permissions, setPermissions] = React.useState(loadingMessage);
    const [customers, setCustomers] = React.useState(loadingMessage);
    const [devices, setDevices] = React.useState(loadingMessage);
    const [repair_orders, setRepair_orders] = React.useState(loadingMessage);
    const [repair_services, setRepair_services] = React.useState(loadingMessage);
    const [order_items, setOrder_items] = React.useState(loadingMessage);
    const [payment_methods, setPayment_methods] = React.useState(loadingMessage);
    const [payments, setPayments] = React.useState(loadingMessage);
    const [invoices, setInvoices] = React.useState(loadingMessage);
    const [invoice_items, setInvoice_items] = React.useState(loadingMessage);
    const [whatsapp_notifications, setWhatsapp_notifications] = React.useState(loadingMessage);
    const [ai_chat_sessions, setAi_chat_sessions] = React.useState(loadingMessage);
    const [ai_chat_messages, setAi_chat_messages] = React.useState(loadingMessage);
    const [qr_links, setQr_links] = React.useState(loadingMessage);

    
    const [widgetsRole, setWidgetsRole] = React.useState({
        role: { value: '', label: '' },
    });
    const { currentUser } = useAppSelector((state) => state.auth);
    const { isFetchingQuery } = useAppSelector((state) => state.openAi);
    
    const { rolesWidgets, loading } = useAppSelector((state) => state.roles);
    
    
    async function loadData() {
        const entities = ['users','roles','permissions','customers','devices','repair_orders','repair_services','order_items','payment_methods','payments','invoices','invoice_items','whatsapp_notifications','ai_chat_sessions','ai_chat_messages','qr_links',];
        const fns = [setUsers,setRoles,setPermissions,setCustomers,setDevices,setRepair_orders,setRepair_services,setOrder_items,setPayment_methods,setPayments,setInvoices,setInvoice_items,setWhatsapp_notifications,setAi_chat_sessions,setAi_chat_messages,setQr_links,];

        const requests = entities.map((entity, index) => {
          
          if(hasPermission(currentUser, `READ_${entity.toUpperCase()}`)) {
            return axios.get(`/${entity.toLowerCase()}/count`);
          } else {
            fns[index](null);
            return Promise.resolve({data: {count: null}});
          }
          
        });

        Promise.allSettled(requests).then((results) => {
            results.forEach((result, i) => {
                if (result.status === 'fulfilled') {
                    fns[i](result.value.data.count);
                } else {
                    fns[i](result.reason.message);
                }
            });
        });
    }
  
    async function getWidgets(roleId) {
        await dispatch(fetchWidgets(roleId));
    }
    React.useEffect(() => {
        if (!currentUser) return;
        loadData().then();
        setWidgetsRole({ role: { value: currentUser?.app_role?.id, label: currentUser?.app_role?.name } });
    }, [currentUser]);

    React.useEffect(() => {
        if (!currentUser || !widgetsRole?.role?.value) return;
        getWidgets(widgetsRole?.role?.value || '').then();
    }, [widgetsRole?.role?.value]);
  
  return (
    <>
      <Head>
        <title>
            {getPageTitle('Overview')}
        </title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
            icon={icon.mdiChartTimelineVariant}
            title='Overview'
            main>
          {''}
        </SectionTitleLineWithButton>
        
        {hasPermission(currentUser, 'CREATE_ROLES') && <WidgetCreator
            currentUser={currentUser}
            isFetchingQuery={isFetchingQuery}
            setWidgetsRole={setWidgetsRole}
            widgetsRole={widgetsRole}
        />}
        {!!rolesWidgets.length &&
            hasPermission(currentUser, 'CREATE_ROLES') && (
                <p className='  text-gray-200 dark:text-gray-400 mb-4'>
                    {`${widgetsRole?.role?.label || 'Users'}'s widgets`}
                </p>
            )}

        <div className='grid grid-cols-1 gap-6 lg:grid-cols-4 mb-6 grid-flow-dense'>
            {(isFetchingQuery || loading) && (
                <div className={` ${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 text-lg leading-tight   text-gray-200 flex items-center ${cardsStyle} dark:border-dark-700 p-6`}>
                    <BaseIcon
                        className={`${iconsColor} animate-spin mr-5`}
                        w='w-16'
                        h='h-16'
                        size={48}
                        path={icon.mdiLoading}
                    />{' '}
                    Loading widgets...
                </div>
            )}

            { rolesWidgets &&
                rolesWidgets.map((widget) => (
                    <SmartWidget
                        key={widget.id}
                        userId={currentUser?.id}
                        widget={widget}
                        roleId={widgetsRole?.role?.value || ''}
                        admin={hasPermission(currentUser, 'CREATE_ROLES')}
                    />
            ))}
        </div>

        {!!rolesWidgets.length && <hr className='my-6 text-neonGreenTheme-mainBG  ' />}
        
        <div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
        
          
            {hasPermission(currentUser, 'READ_USERS') && <Link href={'/users/users-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Users
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {users}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={icon.mdiAccountGroup || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_ROLES') && <Link href={'/roles/roles-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Roles
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {roles}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={icon.mdiShieldAccountVariantOutline || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_PERMISSIONS') && <Link href={'/permissions/permissions-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Permissions
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {permissions}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={icon.mdiShieldAccountOutline || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_CUSTOMERS') && <Link href={'/customers/customers-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Customers
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {customers}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiAccountBadge' in icon ? icon['mdiAccountBadge' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_DEVICES') && <Link href={'/devices/devices-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Devices
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {devices}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiCellphone' in icon ? icon['mdiCellphone' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_REPAIR_ORDERS') && <Link href={'/repair_orders/repair_orders-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Repair orders
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {repair_orders}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiClipboardText' in icon ? icon['mdiClipboardText' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_REPAIR_SERVICES') && <Link href={'/repair_services/repair_services-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Repair services
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {repair_services}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiWrench' in icon ? icon['mdiWrench' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_ORDER_ITEMS') && <Link href={'/order_items/order_items-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Order items
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {order_items}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiFormatListBulleted' in icon ? icon['mdiFormatListBulleted' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_PAYMENT_METHODS') && <Link href={'/payment_methods/payment_methods-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Payment methods
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {payment_methods}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiQrcode' in icon ? icon['mdiQrcode' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_PAYMENTS') && <Link href={'/payments/payments-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Payments
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {payments}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiCreditCardOutline' in icon ? icon['mdiCreditCardOutline' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_INVOICES') && <Link href={'/invoices/invoices-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Invoices
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {invoices}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiFileDocumentOutline' in icon ? icon['mdiFileDocumentOutline' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_INVOICE_ITEMS') && <Link href={'/invoice_items/invoice_items-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Invoice items
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {invoice_items}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiReceiptTextOutline' in icon ? icon['mdiReceiptTextOutline' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_WHATSAPP_NOTIFICATIONS') && <Link href={'/whatsapp_notifications/whatsapp_notifications-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Whatsapp notifications
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {whatsapp_notifications}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiWhatsapp' in icon ? icon['mdiWhatsapp' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_AI_CHAT_SESSIONS') && <Link href={'/ai_chat_sessions/ai_chat_sessions-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Ai chat sessions
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {ai_chat_sessions}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiRobotOutline' in icon ? icon['mdiRobotOutline' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_AI_CHAT_MESSAGES') && <Link href={'/ai_chat_messages/ai_chat_messages-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Ai chat messages
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {ai_chat_messages}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiMessageTextOutline' in icon ? icon['mdiMessageTextOutline' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
            {hasPermission(currentUser, 'READ_QR_LINKS') && <Link href={'/qr_links/qr_links-list'}>
                <div
                    className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
                >
                    <div className="flex justify-between align-center">
                        <div>
                            <div className="text-lg leading-tight   text-gray-200 dark:text-gray-400">
                              Qr links
                            </div>
                            <div className="text-3xl leading-tight font-semibold">
                                {qr_links}
                            </div>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w="w-16"
                                h="h-16"
                                size={48}
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                path={'mdiQrcodeScan' in icon ? icon['mdiQrcodeScan' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
                            />
                        </div>
                    </div>
                </div>
            </Link>}
          
          
        </div>
      </SectionMain>
    </>
  )
}

Dashboard.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}

export default Dashboard
