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 CardBox from '../components/CardBox';
import BaseButton from '../components/BaseButton';

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 [ai_models, setAi_models] = React.useState(loadingMessage);
    const [surveys, setSurveys] = React.useState(loadingMessage);
    const [profiles, setProfiles] = React.useState(loadingMessage);

    const { currentUser } = useAppSelector((state) => state.auth);
    const { isFetchingQuery } = useAppSelector((state) => state.openAi);
    const { rolesWidgets, loading } = useAppSelector((state) => state.roles);
    
    const [widgetsRole, setWidgetsRole] = React.useState({
        role: { value: '', label: '' },
    });

    async function loadData() {
        const entities = ['users','ai_models','surveys','profiles'];
        const fns = [setUsers,setAi_models,setSurveys,setProfiles];

        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);
                }
            });
        });
    }
  
    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;
        dispatch(fetchWidgets(widgetsRole?.role?.value || '')).then();
    }, [widgetsRole?.role?.value, dispatch]);
  
  return (
    <>
      <Head>
        <title>{getPageTitle('Dashboard')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
            icon={icon.mdiViewDashboard}
            title='Smart Filler Dashboard'
            main>
          {''}
        </SectionTitleLineWithButton>

        {/* Smart Filler Quick Actions */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <CardBox className="bg-gradient-to-br from-blue-600 to-indigo-700 text-white border-none shadow-lg">
                <div className="flex items-start justify-between">
                    <div className="space-y-4">
                        <div className="bg-white/20 p-2 rounded-lg inline-block">
                            <BaseIcon path={icon.mdiExtension} size={32} />
                        </div>
                        <h2 className="text-2xl font-bold italic">Chrome Extension Status</h2>
                        <p className="text-blue-100 max-w-sm">
                            Your Smart Survey Filler is ready to deploy. Download the latest version to start automating.
                        </p>
                        <BaseButton
                            label="Download V3 Extension"
                            color="white"
                            className="text-blue-700 font-bold"
                            icon={icon.mdiDownload}
                        />
                    </div>
                    <div className="hidden lg:block opacity-20 transform scale-150 translate-x-4">
                        <BaseIcon path={icon.mdiRobot} size={120} />
                    </div>
                </div>
            </CardBox>

            <CardBox className="bg-slate-800 border-slate-700 text-white shadow-lg">
                <div className="flex items-start justify-between">
                    <div className="space-y-4 w-full">
                        <div className="flex justify-between items-center">
                            <div className="bg-emerald-500/20 p-2 rounded-lg inline-block text-emerald-400">
                                <BaseIcon path={icon.mdiAccountCircle} size={32} />
                            </div>
                            <span className="bg-emerald-500 text-white text-xs px-2 py-1 rounded-full animate-pulse">ACTIVE</span>
                        </div>
                        <h2 className="text-2xl font-bold">Current AI Persona</h2>
                        <div className="bg-slate-900/50 p-4 rounded-xl border border-slate-700">
                            <p className="text-sm text-slate-400 uppercase font-bold tracking-wider mb-1">Primary Profile</p>
                            <p className="text-lg font-medium text-emerald-400">Tech Enthusiast / Senior Dev</p>
                        </div>
                        <BaseButton
                            href="/profiles/profiles-list"
                            label="Manage Personas"
                            color="info"
                            outline
                            className="w-full"
                            icon={icon.mdiCog}
                        />
                    </div>
                </div>
            </CardBox>
        </div>
        
        <div id="stats-grid" className='grid grid-cols-1 gap-6 lg:grid-cols-4 mb-8'>
            <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-sm uppercase font-bold text-gray-400 tracking-widest mb-1">Surveys Filled</div>
                        <div className="text-3xl font-extrabold">{surveys}</div>
                    </div>
                    <BaseIcon className="text-blue-500" w="w-12" h="h-12" size={32} path={icon.mdiFormSelect} />
                </div>
            </div>
            <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-sm uppercase font-bold text-gray-400 tracking-widest mb-1">Active Personas</div>
                        <div className="text-3xl font-extrabold">{profiles}</div>
                    </div>
                    <BaseIcon className="text-emerald-500" w="w-12" h="h-12" size={32} path={icon.mdiAccountMultiple} />
                </div>
            </div>
            <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-sm uppercase font-bold text-gray-400 tracking-widest mb-1">AI Models</div>
                        <div className="text-3xl font-extrabold">{ai_models}</div>
                    </div>
                    <BaseIcon className="text-violet-500" w="w-12" h="h-12" size={32} path={icon.mdiRobot} />
                </div>
            </div>
            <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-sm uppercase font-bold text-gray-400 tracking-widest mb-1">Platform Users</div>
                        <div className="text-3xl font-extrabold">{users}</div>
                    </div>
                    <BaseIcon className="text-orange-500" w="w-12" h="h-12" size={32} path={icon.mdiAccountGroup} />
                </div>
            </div>
        </div>

        {hasPermission(currentUser, 'CREATE_ROLES') && <WidgetCreator
            currentUser={currentUser}
            isFetchingQuery={isFetchingQuery}
            setWidgetsRole={setWidgetsRole}
            widgetsRole={widgetsRole}
        />}

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

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

export default Dashboard