import EcommerceCentralDashboard from '@/components/dashboard/central/EcommerceCentralDashboard';
import SalesCentralDashboard from '@/components/dashboard/central/SalesCentralDashboard';
import EducationCentralDashboard from '@/components/dashboard/central/EducationCentralDashboard';
import ErpCentralDashboard from '@/components/dashboard/central/ErpCentralDashboard';
import { DateRangePicker } from '@/components/dashboard/date-range-picker';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { PageProps } from '@/types/global';
import { Link, router, usePage } from '@inertiajs/react';
import { format } from 'date-fns';
import { Settings } from 'lucide-react';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import FormFieldExamples from '@/components/form/FormFieldExamples';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Home', href: '/' },
    { title: 'Dashboard', href: '#' },
];

// Maps the central_dashboard setting slug → the React component to render
const PRODUCT_DASHBOARDS: Record<string, React.ComponentType<any>> = {
    'taskco-ecommerce': EcommerceCentralDashboard,
    'taskco-sales':     SalesCentralDashboard,
    'taskco-education': EducationCentralDashboard,
    'taskco-erp':       ErpCentralDashboard,
};

function Dashboard() {
    const { moduleStatus, active_dashboard, dashboard_data, dashboard_settings_data } = usePage<PageProps & {
        active_dashboard: string;
        dashboard_data: Record<string, any>;
        dashboard_settings_data: any[];
    }>().props;

    const [date, setDate] = useState<{ from: Date | undefined; to: Date | undefined }>({
        from: new Date(new Date().getFullYear(), 0, 1),
        to: new Date(),
    });
    const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);
    const isFirstRender = useRef(true);

    useEffect(() => {
        if (isFirstRender.current) { isFirstRender.current = false; return; }
        if (!date.from || !date.to) return;
        const timer = setTimeout(() => {
            router.reload({
                data: { from: format(date.from!, 'yyyy-MM-dd'), to: format(date.to!, 'yyyy-MM-dd') },
                preserveState: true,
                preserveScroll: true,
            });
        }, 600);
        return () => clearTimeout(timer);
    }, [date.from, date.to]);

    // Resolve the product dashboard component — ERP/default shown when no specific product is configured
    const ProductDashboard = PRODUCT_DASHBOARDS[active_dashboard] ?? ErpCentralDashboard;

    return (
        <div className="flex h-full flex-col p-2">
            <div className="mb-4 flex items-center justify-between">
                <h1 className="text-2xl font-bold tracking-tight">Dashboard</h1>
                <div className="flex gap-2">
                    <DateRangePicker date={date} setDate={setDate} isOpen={isDatePickerOpen} onOpenChange={setIsDatePickerOpen} />
                    <Link href={route('settings.company.edit')}>
                        <Button variant="outline" size="icon" className="border-gray-300 bg-card" aria-label="Dashboard settings">
                            <Settings className="h-4 w-4" color="black" />
                            <span className="sr-only">Dashboard settings</span>
                        </Button>
                    </Link>
                </div>
            </div>

            {/* ── Product dashboard (ERP shown by default when no product is configured) ── */}
            <ProductDashboard data={dashboard_data} />
        </div>
    );
}

Dashboard.layout = (page: ReactNode) => <AppLayout title="Dashboard" breadcrumbs={breadcrumbs}>{page}</AppLayout>;

export default Dashboard;
