import * as icon from '@mdi/js';
import Head from 'next/head'
import React, { useState } 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 BaseButton from "../components/BaseButton";
import CardBox from "../components/CardBox";
import CardBoxModal from "../components/CardBoxModal";
import FormField from "../components/FormField";
import FormFilePicker from "../components/FormFilePicker";
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 [organizations, setOrganizations] = React.useState(loadingMessage);
    const [firms, setFirms] = React.useState(loadingMessage);
    const [merchants, setMerchants] = React.useState(loadingMessage);
    const [customers, setCustomers] = React.useState(loadingMessage);
    const [suppliers, setSuppliers] = React.useState(loadingMessage);
    const [products, setProducts] = React.useState(loadingMessage);
    const [receipts, setReceipts] = React.useState(loadingMessage);
    const [ocr_extractions, setOcr_extractions] = React.useState(loadingMessage);
    const [sales_invoices, setSales_invoices] = React.useState(loadingMessage);
    const [sales_invoice_lines, setSales_invoice_lines] = React.useState(loadingMessage);
    const [purchase_invoices, setPurchase_invoices] = React.useState(loadingMessage);
    const [purchase_invoice_lines, setPurchase_invoice_lines] = React.useState(loadingMessage);
    const [expenses, setExpenses] = React.useState(loadingMessage);
    const [tax_periods, setTax_periods] = React.useState(loadingMessage);
    const [vat_declarations, setVat_declarations] = React.useState(loadingMessage);
    const [tot_declarations, setTot_declarations] = React.useState(loadingMessage);
    const [declaration_submissions, setDeclaration_submissions] = React.useState(loadingMessage);
    const [messages, setMessages] = React.useState(loadingMessage);
    const [audit_events, setAudit_events] = 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);

    const [isOcrModalActive, setIsOcrModalActive] = useState(false);
    const [ocrType, setOcrType] = useState<'sale' | 'purchase'>('sale');
    const [isProcessing, setIsProcessing] = useState(false);
    const [ocrResult, setOcrResult] = useState<any>(null);

    const isMerchant = currentUser?.app_role?.name === 'MerchantUser';
    const organizationName = currentUser?.organization?.name || 'SmartHisab';

    async function loadData() {
        const entities = ['users','roles','permissions','organizations','firms','merchants','customers','suppliers','products','receipts','ocr_extractions','sales_invoices','sales_invoice_lines','purchase_invoices','purchase_invoice_lines','expenses','tax_periods','vat_declarations','tot_declarations','declaration_submissions','messages','audit_events',];
        const fns = [setUsers,setRoles,setPermissions,setOrganizations,setFirms,setMerchants,setCustomers,setSuppliers,setProducts,setReceipts,setOcr_extractions,setSales_invoices,setSales_invoice_lines,setPurchase_invoices,setPurchase_invoice_lines,setExpenses,setTax_periods,setVat_declarations,setTot_declarations,setDeclaration_submissions,setMessages,setAudit_events,];

        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]);

    const handleOcrSimulate = async () => {
        setIsProcessing(true);
        try {
            const response = await axios.post('/ocr/simulate');
            setOcrResult(response.data);
        } catch (error) {
            console.error('OCR Simulation failed', error);
        } finally {
            setIsProcessing(false);
        }
    };

    const handleSaveTransaction = async () => {
        const endpoint = ocrType === 'sale' ? '/sales_invoices' : '/purchase_invoices';
        try {
            await axios.post(endpoint, {
                invoice_number: ocrResult.invoice_number,
                date: ocrResult.date,
                total_amount: parseFloat(ocrResult.total_amount),
                tax_amount: parseFloat(ocrResult.tax_amount),
            });
            setIsOcrModalActive(false);
            setOcrResult(null);
            loadData(); // Reload counts
            alert('Transaction saved successfully!');
        } catch (error) {
            console.error('Save failed', error);
        }
    };

    const transactionTypes = [
        {
          title: 'Purchase Entry Form',
          titleAm: 'የግዢ መዝገብ',
          description: 'Record purchase transactions with VAT and withholding tax calculations',
          icon: icon.mdiPackageVariantClosed,
          href: '/purchase_invoices/purchase_invoices-new',
          bgColor: 'bg-orange-50',
          borderColor: 'border-orange-100',
          iconBg: 'bg-orange-100',
          iconColor: 'text-orange-600',
          buttonBg: 'bg-orange-600',
          dotColor: 'bg-orange-400',
        },
        {
          title: 'Sales Entry Form',
          titleAm: 'የሽያጭ መዝገብ',
          description: 'Record sales transactions with VAT calculations',
          icon: icon.mdiCartOutline,
          href: '/sales_invoices/sales_invoices-new',
          bgColor: 'bg-emerald-50',
          borderColor: 'border-emerald-100',
          iconBg: 'bg-emerald-100',
          iconColor: 'text-emerald-600',
          buttonBg: 'bg-emerald-600',
          dotColor: 'bg-emerald-400',
        },
        {
          title: 'Expense Entry Form',
          titleAm: 'ወጪ መዝገብ',
          description: 'Record business expenses and operating costs',
          icon: icon.mdiCurrencyUsd,
          href: '/expenses/expenses-new',
          bgColor: 'bg-red-50',
          borderColor: 'border-red-100',
          iconBg: 'bg-red-100',
          iconColor: 'text-red-600',
          buttonBg: 'bg-red-600',
          dotColor: 'bg-red-400',
        },
        {
          title: 'Inventory Entry Form',
          titleAm: 'እቃ መዝገብ',
          description: 'Track inventory purchases and stock additions',
          icon: icon.mdiCubeOutline,
          href: '/products/products-new',
          bgColor: 'bg-indigo-50',
          borderColor: 'border-indigo-100',
          iconBg: 'bg-indigo-100',
          iconColor: 'text-indigo-600',
          buttonBg: 'bg-indigo-600',
          dotColor: 'bg-indigo-400',
        },
        {
          title: 'All Transactions',
          titleAm: 'ግብይቶች',
          description: 'View and manage all tax transactions',
          icon: icon.mdiViewList,
          href: '/sales_invoices/sales_invoices-list',
          bgColor: 'bg-cyan-50',
          borderColor: 'border-cyan-100',
          iconBg: 'bg-cyan-100',
          iconColor: 'text-cyan-600',
          buttonBg: 'bg-cyan-600',
          dotColor: 'bg-cyan-400',
        },
    ];

    return (
        <>
            <Head>
                <title>{getPageTitle('Overview')}</title>
            </Head>
            <SectionMain>
                <SectionTitleLineWithButton
                    icon={icon.mdiChartTimelineVariant}
                    title={isMerchant ? `Dashboard` : 'Overview'}
                    main
                >
                    {''}
                </SectionTitleLineWithButton>

                {isMerchant && (
                    <div className="mb-12">
                        <div className="flex flex-col items-center justify-center mb-10">
                            <p className="text-gray-500 font-medium mb-1 text-xs">የግብይት አይነት ይምረጡ</p>
                            <h2 className="text-2xl font-extrabold text-slate-900 mb-3 text-center">
                                Choose the type of transaction you want to record
                            </h2>
                            <div className="bg-emerald-100 text-emerald-700 px-3 py-0.5 rounded-full text-xs font-bold shadow-sm">
                                {organizationName}
                            </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            {transactionTypes.map((type, index) => (
                                <div
                                    key={index}
                                    className={`relative flex flex-col p-6 rounded-[2rem] border ${type.borderColor} ${type.bgColor} shadow-sm hover:shadow-md transition-shadow group`}
                                >
                                    <div className={`absolute top-5 right-5 w-2.5 h-2.5 rounded-full ${type.dotColor}`}></div>
                                    
                                    <div className={`w-12 h-12 ${type.iconBg} ${type.iconColor} rounded-xl flex items-center justify-center mb-4`}>
                                        <BaseIcon path={type.icon} size={24} />
                                    </div>

                                    <div className="mb-6 flex-grow">
                                        <h3 className="text-sm font-bold text-slate-900 mb-0.5">{type.titleAm}</h3>
                                        <h4 className="text-base font-bold text-slate-800 mb-2">{type.title}</h4>
                                        <p className="text-slate-500 text-xs leading-relaxed">
                                            {type.description}
                                        </p>
                                    </div>

                                    <Link href={type.href}>
                                        <button
                                            className={`w-full py-3 px-4 rounded-xl text-white text-sm font-bold flex items-center justify-center transition-all active:scale-95 ${type.buttonBg} hover:opacity-90 shadow-sm`}
                                        >
                                            Open Form
                                            <BaseIcon path={icon.mdiChevronRight} size={18} className="ml-1" />
                                        </button>
                                    </Link>
                                </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-500 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>

                <div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
                    {hasPermission(currentUser, 'READ_MERCHANTS') && (
                        <Link href={'/merchants/merchants-list'}>
                            <CardBox className={cardsStyle}>
                                <div className="flex justify-between align-center">
                                    <div>
                                        <div className="text-lg leading-tight text-gray-500 dark:text-gray-400">Merchants</div>
                                        <div className="text-3xl leading-tight font-semibold">{merchants}</div>
                                    </div>
                                    <BaseIcon className={iconsColor} w="w-16" h="h-16" size={48} path={'mdiStore' in icon ? icon['mdiStore' as keyof typeof icon] : icon.mdiTable} />
                                </div>
                            </CardBox>
                        </Link>
                    )}
                    {hasPermission(currentUser, 'READ_SALES_INVOICES') && (
                        <Link href={'/sales_invoices/sales_invoices-list'}>
                            <CardBox className={cardsStyle}>
                                <div className="flex justify-between align-center">
                                    <div>
                                        <div className="text-lg leading-tight text-gray-500 dark:text-gray-400">Sales Invoices</div>
                                        <div className="text-3xl leading-tight font-semibold">{sales_invoices}</div>
                                    </div>
                                    <BaseIcon className={iconsColor} w="w-16" h="h-16" size={48} path={icon.mdiFileDocumentOutline} />
                                </div>
                            </CardBox>
                        </Link>
                    )}
                    {hasPermission(currentUser, 'READ_PURCHASE_INVOICES') && (
                        <Link href={'/purchase_invoices/purchase_invoices-list'}>
                            <CardBox className={cardsStyle}>
                                <div className="flex justify-between align-center">
                                    <div>
                                        <div className="text-lg leading-tight text-gray-500 dark:text-gray-400">Purchase Invoices</div>
                                        <div className="text-3xl leading-tight font-semibold">{purchase_invoices}</div>
                                    </div>
                                    <BaseIcon className={iconsColor} w="w-16" h="h-16" size={48} path={icon.mdiFileDocumentMultipleOutline} />
                                </div>
                            </CardBox>
                        </Link>
                    )}
                </div>

                {/* Keeping the OCR modal logic for future use or hidden triggers */}
                <CardBoxModal
                    title={`Record ${ocrType === 'sale' ? 'Sale' : 'Purchase'}`}
                    isActive={isOcrModalActive}
                    onConfirm={ocrResult ? handleSaveTransaction : handleOcrSimulate}
                    onCancel={() => { setIsOcrModalActive(false); setOcrResult(null); }}
                    buttonColor="info"
                    buttonLabel={ocrResult ? "Confirm & Save" : (isProcessing ? "Processing..." : "Scan Receipt")}
                >
                    {!ocrResult ? (
                        <div className="space-y-6 py-4">
                            <FormField label="Snap or Upload Receipt" help="Our AI will extract the amount, date, and invoice number.">
                                <FormFilePicker label="Upload" color="info" accept="image/*" />
                            </FormField>
                            {isProcessing && (
                                <div className="flex items-center justify-center space-x-3 text-blue-600 animate-pulse">
                                    <BaseIcon path={icon.mdiLoading} className="animate-spin" />
                                    <span className="font-bold">Analyzing with SmartHisab AI...</span>
                                </div>
                            )}
                        </div>
                    ) : (
                        <div className="space-y-4 py-2">
                            <div className="bg-emerald-50 p-3 rounded-lg border border-emerald-100 flex items-center space-x-3 text-emerald-800 text-sm">
                                <BaseIcon path={icon.mdiCheckDecagram} className="text-emerald-500" />
                                <span className="font-bold">Extraction Successful! Please verify details.</span>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <FormField label="Invoice #">
                                    <input value={ocrResult.invoice_number} readOnly />
                                </FormField>
                                <FormField label="Date">
                                    <input value={ocrResult.date} readOnly />
                                </FormField>
                                <FormField label="Total (ETB)">
                                    <input value={ocrResult.total_amount} readOnly />
                                </FormField>
                                <FormField label="Tax (ETB)">
                                    <input value={ocrResult.tax_amount} readOnly />
                                </FormField>
                            </div>
                            <FormField label="Vendor / Client Name">
                                <input value={ocrResult.vendor_name} readOnly />
                            </FormField>
                        </div>
                    )}
                </CardBoxModal>
            </SectionMain>
        </>
    )
}

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

export default Dashboard