import * as icon from '@mdi/js';
import Head from 'next/head'
import React, { useEffect, useState } from 'react'
import type { ReactElement } from 'react'
import LayoutAuthenticated from '../layouts/Authenticated'
import SectionMain from '../components/SectionMain'
import BaseIcon from "../components/BaseIcon";
import BaseButton from "../components/BaseButton";
import { getPageTitle } from '../config'

import { useAppDispatch, useAppSelector } from '../stores/hooks';
import DashboardWidgets from '../components/Finance/Dashboard/DashboardWidgets';
import QuickActions from '../components/Finance/Dashboard/QuickActions';
import RecentTransactions from '../components/Finance/Dashboard/RecentTransactions';
import UpcomingDueDates from '../components/Finance/Dashboard/UpcomingDueDates';
import ProfitLossSummaryChart from '../components/Finance/Dashboard/ProfitLossSummaryChart';
import { fetchDashboardStats } from '../stores/dashboardSlice';

const Dashboard = () => {
    const dispatch = useAppDispatch();
    const { currentUser } = useAppSelector((state) => state.auth);
    const { activeContext } = useAppSelector((state) => state.context);

    const isMerchant = currentUser?.app_role?.name === 'MerchantUser';
    const merchantName = activeContext?.name || currentUser?.organization?.name || 'SmartHisab User';

    useEffect(() => {
        dispatch(fetchDashboardStats());
    }, [dispatch, activeContext?.id]);

    return (
        <>
            <Head>
                <title>{getPageTitle('Dashboard')}</title>
            </Head>
            
            <SectionMain>
                <div className="flex flex-col md:flex-row md:items-center justify-between mb-8 gap-4">
                    <div>
                        <h1 className="text-3xl font-black text-slate-900 dark:text-white mb-2 tracking-tight">
                            Welcome back, {merchantName}
                        </h1>
                        <p className="text-slate-500 dark:text-gray-400 text-sm font-medium">
                            Here&apos;s what&apos;s happening with {activeContext?.type === 'merchant' ? 'this merchant' : 'your firm'} today
                        </p>
                    </div>

                    <div className="flex items-center space-x-3">
                        <div className="relative group">
                            <select className="appearance-none bg-white dark:bg-dark-900 border border-gray-100 dark:border-dark-700 rounded-xl px-4 py-2.5 pr-10 text-sm font-bold text-slate-700 dark:text-white shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all cursor-pointer">
                                <option>Last 30 days</option>
                                <option>Last 7 days</option>
                                <option>Last 3 months</option>
                                <option>This Year</option>
                            </select>
                            <BaseIcon path={icon.mdiChevronDown} size={20} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
                        </div>

                        <BaseButton
                            label="New Sale"
                            icon={icon.mdiPlus}
                            color="info"
                            href="/sales_invoices/sales_invoices-new"
                            className="shadow-lg shadow-indigo-200 dark:shadow-none font-bold py-2.5 px-5 rounded-xl transition-all active:scale-95"
                        />
                    </div>
                </div>

                <DashboardWidgets />

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
                    <div className="lg:col-span-2">
                        <QuickActions />
                        <RecentTransactions />
                    </div>
                    <div className="space-y-8">
                        <UpcomingDueDates />
                        <ProfitLossSummaryChart />
                    </div>
                </div>

                {!isMerchant && !activeContext && (
                    <div className="mt-12 pt-8 border-t border-gray-100 dark:border-dark-700">
                         <div className="bg-white dark:bg-dark-900 rounded-[2rem] p-8 border border-dashed border-gray-200 dark:border-dark-600 text-center">
                            <BaseIcon path={icon.mdiShieldCheckOutline} size={48} className="text-gray-300 mx-auto mb-4" />
                            <h3 className="text-lg font-bold text-slate-900 dark:text-white mb-2">Administrative Overview</h3>
                            <p className="text-slate-500 dark:text-gray-400 text-sm max-w-md mx-auto">
                                You are viewing the dashboard as an administrator. Switch to a specific merchant to see their business metrics.
                            </p>
                         </div>
                    </div>
                )}
            </SectionMain>
        </>
    )
}

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

export default Dashboard