import React, { Fragment, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Responsive, WidthProvider } from 'react-grid-layout';
const ResponsiveGridLayout = WidthProvider(Responsive);
import { useElementSize } from '@mantine/hooks';
import { Container, Title, ScrollArea, Box, ThemeIcon, Modal, Group, Text, Divider, Stack, Button, Loader, Center } from '@mantine/core';
import { IconGripVertical, IconLock, IconRotateClockwise } from '@tabler/icons-react';

import { fetchDashboardLayout, updateDashboardLayout } from '../reducers/dashboardSlice';
import useAuth from '../utils/useAuth';
import { translate } from '../utils/i18n';
import { fetchTasksByUser } from './Settings/store/myTaskSlice';
import { fetchTaskCounts } from './Settings/store/taskSlice';
import { fetchQuickTasksByUser } from './Settings/store/quickTaskSlice';
import { fatchLazytasksConfig } from './Settings/store/settingSlice';
import { fetchUserPermissions } from '../store/auth/permissionsSlice';

import Onboarding from './Onboarding/Onboarding';
import DashboardCard from './Dashboard/DashboardCard';
import DashboardPieChart from './Dashboard/DashboardPieChart';
import DashboardTaskProgress from './Dashboard/DashboardTaskProgress';
import DashboardBarChart from './Dashboard/DashboardBarChart';
import TaskListTabs from './Dashboard/TaskListTabs';
import QuickTaskList from './Dashboard/QuickTaskList';
import UserActivities from './Dashboard/UserActivities';
import UserEngagementChart from './Dashboard/UserEngagementChart';
// import UserEngagementChartNew from './Dashboard/UserEngagementChartNew';
import ReviewWidget from './Dashboard/ReviewWidget';

import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

const WIDGETS_CONFIG = {
    'summary_total': { component: <DashboardCard type="total" /> },
    'summary_progress': { component: <DashboardCard type="progress" /> },
    'summary_completed': { component: <DashboardCard type="completed" /> },
    'summary_overdue': { component: <DashboardCard type="overdue" /> },
    'pie': { component: <DashboardPieChart /> },
    'progress': { component: <DashboardTaskProgress /> },
    'bar': { component: <DashboardBarChart /> },
    'tabs': { component: <TaskListTabs /> },
    'quick': { component: <QuickTaskList /> },
    'activity': { component: <UserActivities /> },
    'engagement': { component: <UserEngagementChart /> },
    // 'engagement_new': { component: <UserEngagementChartNew /> },
};

// Default Layout (4 Columns)
const DEFAULT_LAYOUT = [
    { i: 'summary_total', x: 0, y: 0, w: 1, h: 4, minW: 1, minH: 3 },
    { i: 'summary_progress', x: 1, y: 0, w: 1, h: 4, minW: 1, minH: 3 },
    { i: 'summary_completed', x: 2, y: 0, w: 1, h: 4, minW: 1, minH: 3 },
    { i: 'summary_overdue', x: 3, y: 0, w: 1, h: 4, minW: 1, minH: 3 },
    { i: 'pie', x: 0, y: 4, w: 2, h: 15, minW: 2, minH: 8 },
    { i: 'progress', x: 2, y: 4, w: 2, h: 15, minW: 2, minH: 8 },
    { i: 'bar', x: 0, y: 19, w: 2, h: 12, minW: 2, minH: 8 },
    { i: 'tabs', x: 2, y: 19, w: 2, h: 12, minW: 2, minH: 8 },
    { i: 'engagement', x: 0, y: 31, w: 2, h: 12, minW: 2, minH: 8 },
    { i: 'engagement_new', x: 0, y: 43, w: 2, h: 12, minW: 2, minH: 8 },
    { i: 'quick', x: 2, y: 31, w: 1, h: 12, minW: 1, minH: 8 },
    { i: 'activity', x: 3, y: 31, w: 1, h: 12, minW: 1, minH: 8 },
];

const Dashboard = () => {

    const dispatch = useDispatch();
    const { signOut } = useAuth();
    const { loggedUserId } = useSelector((state) => state.auth.user)
    const { token, loggedInUser, xWpNonce } = useSelector((state) => state.auth.session);
    const { lazytasksConfig } = useSelector((state) => state.settings.setting);
    const permissions = useSelector((state) => state.auth.permissions);

    const [config, setConfig] = useState(lazytasksConfig);
    const [notEngagedModalOpen, setNotEngagedModalOpen] = useState(false);
    const [resetModalOpen, setResetModalOpen] = useState(false);
    const [customizationModalOpen, setCustomizationModalOpen] = useState(false);
    const [isCustomizationMode, setIsCustomizationMode] = useState(false);
    const permsFetchedRef = useRef(false);
    const [wiggle, setWiggle] = useState(false);
    const [hasSavedCustomLayout, setHasSavedCustomLayout] = useState(() =>
        localStorage.getItem('lt_has_saved_layout') === 'true');
    const [layoutSnapshot, setLayoutSnapshot] = useState(null);
    const [unsavedChangesModalOpen, setUnsavedChangesModalOpen] = useState(false);

    // Layout State
    const [layout, setLayout] = useState(DEFAULT_LAYOUT);
    const [isLayoutLoaded, setIsLayoutLoaded] = useState(false);

    // Grid Layout Width
    const { ref: containerRef, width } = useElementSize();

    useEffect(() => {
        if (lazytasksConfig) {
            setConfig(lazytasksConfig);
        }
    }, [lazytasksConfig]);

    useEffect(() => {
        if (!xWpNonce) return;

        const userId =
            loggedInUser?.loggedUserId ?? loggedUserId;

        const fetchData = async () => {
            try {
                // Fetch permissions first and await it. Any code after this await is
                // guaranteed to run with the fresh token from Routes.jsx, because
                // Routes.jsx dispatches synchronously on mount and all synchronous effects
                // complete before the first async await resolves.
                if (!permsFetchedRef.current) {
                    permsFetchedRef.current = true;
                    const permsResult = await dispatch(fetchUserPermissions());

                    // Gate config fetch on FRESH permissions from the API response —
                    // not the stale persisted llc_permissions — to avoid 403s from
                    // using the old token that was rehydrated from localStorage.
                    // Fetch config for all authenticated users — header needs core_setting
                    // (logo, title, colors) regardless of general-settings permission.
                    const response = await dispatch(fatchLazytasksConfig());
                    if (response?.payload?.status === 200) {
                        setConfig(response.payload.data);
                    }
                }

                // Critical path: fetch task counts so dashboard cards can render
                if (userId) {
                    dispatch(fetchTaskCounts());
                }

                // Fetch saved layout using Redux thunk
                const layoutResponse = await dispatch(fetchDashboardLayout());
                if (layoutResponse?.payload?.status === 200 && Array.isArray(layoutResponse.payload.data) && layoutResponse.payload.data.length > 0) {
                    const savedLayout = layoutResponse.payload.data;
                    // Validate if saved layout has correct structure (objects with 'i')
                    if (savedLayout[0] && typeof savedLayout[0] === 'object' && savedLayout[0].hasOwnProperty('i')) {
                        // Check for legacy 'summary' widget and reset if found to ensure new widgets appear at top
                        const hasLegacySummary = savedLayout.some(item => item.i === 'summary');

                        if (hasLegacySummary) {
                            console.log("Legacy 'summary' widget detected. Resetting to default layout.");
                            setLayout(DEFAULT_LAYOUT);
                            setIsLayoutLoaded(true);
                            return;
                        }

                        // Merge logic: Ensure all widgets in DEFAULT_LAYOUT are present
                        const validSavedLayout = savedLayout.filter(item => WIDGETS_CONFIG[item.i]);

                        // If any saved widget exceeds its default height, y-positions are stale — reset entirely
                        const hasStaleHeights = validSavedLayout.some(item => {
                            const defaultItem = DEFAULT_LAYOUT.find(d => d.i === item.i);
                            return defaultItem && item.h > defaultItem.h;
                        });

                        if (hasStaleHeights) {
                            setLayout(DEFAULT_LAYOUT);
                            setIsLayoutLoaded(true);
                            return;
                        }

                        // Enforce updated minH/minW from DEFAULT_LAYOUT on saved items
                        const updatedSavedLayout = validSavedLayout.map(savedItem => {
                            const defaultItem = DEFAULT_LAYOUT.find(d => d.i === savedItem.i);
                            if (defaultItem) {
                                // Update minH and minW if they differ or are missing
                                return {
                                    ...savedItem,
                                    minW: defaultItem.minW,
                                    minH: defaultItem.minH,
                                    // Ensure current dimensions respect new minimums
                                    w: Math.max(savedItem.w, defaultItem.minW),
                                    h: Math.min(Math.max(savedItem.h, defaultItem.minH), defaultItem.h)
                                };
                            }
                            return savedItem;
                        });

                        // Find missing widgets
                        const savedIds = updatedSavedLayout.map(item => item.i);
                        const missingWidgets = DEFAULT_LAYOUT.filter(item => !savedIds.includes(item.i));

                        // If we need to put missing widgets somewhere, we place them at the bottom
                        const maxY = updatedSavedLayout.reduce((max, item) => Math.max(max, item.y + item.h), 0);

                        const newWidgets = missingWidgets.map((item, index) => ({
                            ...item,
                            y: maxY + (index * item.h) // Simple stacking for new widgets
                        }));

                        setLayout([...updatedSavedLayout, ...newWidgets]);
                    } else {
                        // Legacy layout or invalid - reset to default
                        console.warn("Invalid or legacy layout detected. Resetting to default.");
                        setLayout(DEFAULT_LAYOUT);
                    }
                }
                setIsLayoutLoaded(true);

                // Deferred: secondary data fetched after layout renders to avoid competing with critical path
                if (userId) {
                    setTimeout(() => {
                        dispatch(fetchTasksByUser({ id: userId }));
                        dispatch(fetchQuickTasksByUser({ id: userId }));
                    }, 0);
                }
            } catch (error) {
                console.error('Unexpected error:', error);
                setIsLayoutLoaded(true);
            }
        };
        fetchData();
    }, [
        dispatch,
        xWpNonce,
        loggedInUser
    ]);


    useEffect(() => {
        if (loggedInUser) {
            const wpRoles = Array.isArray(loggedInUser.roles) ? loggedInUser.roles : [];
            const roles = Array.isArray(loggedInUser.llc_roles) ? loggedInUser.llc_roles : [];
            const perms = Array.isArray(loggedInUser.llc_permissions) ? loggedInUser.llc_permissions : [];
            const projectRoles = Array.isArray(loggedInUser.project_roles) ? loggedInUser.project_roles : [];

            const hasRoles = roles.length > 0;
            const hasProjectRoles = projectRoles.length > 0;

            const hasValidPermissions = perms.length > 0;
            const isWpAdmin = wpRoles.includes('administrator');

            const shouldOpen = !hasRoles && !hasValidPermissions && !hasProjectRoles && !isWpAdmin;

            setNotEngagedModalOpen(shouldOpen);
        }
    }, [loggedInUser, loggedUserId]);

    const handleGoBack = async () => {
        try {
            await signOut(); // wait for sign out to complete
        } catch (err) {
            // swallow or log if needed
            console.error('Sign out failed', err);
        } finally {
            const redirectUrl = appLocalizer?.home_url || '/';
            window.location.href = redirectUrl;
        }
    };

    const onLayoutChange = (currentLayout) => {
        if (!isLayoutLoaded) return;
        setLayout(currentLayout); // update state only — user must click Save to persist
    };

    const handleResetLayout = () => {
        setLayout(DEFAULT_LAYOUT);
        const cleanLayout = DEFAULT_LAYOUT.map(({ i, x, y, w, h, minW, minH }) => ({ i, x, y, w, h, minW, minH }));
        dispatch(updateDashboardLayout(cleanLayout)).catch(err => console.error("Failed to save layout", err));
        setHasSavedCustomLayout(false);
        localStorage.removeItem('lt_has_saved_layout');
        setIsCustomizationMode(false);
        setResetModalOpen(false);
    };

    const handleEnableCustomization = () => {
        setCustomizationModalOpen(false);
        setIsCustomizationMode(true);
        setLayoutSnapshot(layout);
        setWiggle(true);
        setTimeout(() => setWiggle(false), 1000);
    };

    const handleSaveLayout = () => {
        const cleanLayout = layout.map(({ i, x, y, w, h, minW, minH }) => ({ i, x, y, w, h, minW, minH }));
        dispatch(updateDashboardLayout(cleanLayout))
            .unwrap()
            .then(() => {
                setHasSavedCustomLayout(true);
                localStorage.setItem('lt_has_saved_layout', 'true');
                setIsCustomizationMode(false);
                setLayoutSnapshot(null);
            })
            .catch(err => console.error("Failed to save layout", err));
    };

    const handleExitCustomization = () => {
        const serialize = (l) => JSON.stringify(
            l.map(({ i, x, y, w, h }) => ({ i, x, y, w, h })).sort((a, b) => a.i.localeCompare(b.i))
        );
        const hasChanges = layoutSnapshot && serialize(layout) !== serialize(layoutSnapshot);
        if (hasChanges) {
            setUnsavedChangesModalOpen(true);
        } else {
            setIsCustomizationMode(false);
            setLayoutSnapshot(null);
        }
    };

    return (
        <Fragment>
            {/*<Header /> */}

            <div className='dashboard'>
                <Container size="full">
                    <div className="settings-page-card bg-white rounded-xl p-5 pt-3 mt-5 mb-5">
                        <div className='mt-2 mb-3'>
                            {/* <Title order={4}>{ __('Dashboard', 'lazytasks-project-task-management') }</Title> */}
                            <Group position="apart" justify="space-between">
                                <Title order={4}>{translate('Dashboard')}</Title>
                                {!isCustomizationMode ? (
                                    <Group gap="xs">
                                        {hasSavedCustomLayout && (
                                            <Button
                                                leftSection={<IconRotateClockwise size={16} />}
                                                variant="light"
                                                color="red"
                                                size="xs"
                                                onClick={() => setResetModalOpen(true)}
                                            >
                                                {translate('Reset Layout')}
                                            </Button>
                                        )}
                                        <Button
                                            variant="filled"
                                            color="orange"
                                            size="xs"
                                            style={{ color: 'white' }}
                                            onClick={() => setCustomizationModalOpen(true)}
                                        >
                                            {translate('Customize Dashboard')}
                                        </Button>
                                    </Group>
                                ) : (
                                    <Group gap="xs">
                                        <Button
                                            variant="light"
                                            color="gray"
                                            size="xs"
                                            onClick={handleExitCustomization}
                                        >
                                            {translate('Exit')}
                                        </Button>
                                        <Button
                                            variant="filled"
                                            color="green"
                                            size="xs"
                                            onClick={handleSaveLayout}
                                        >
                                            {translate('Save')}
                                        </Button>
                                    </Group>
                                )}
                            </Group>
                        </div>

                        <ReviewWidget />

                        <ScrollArea scrollbars="y" className={`w-full px-2 ${appLocalizer?.is_admin ? 'h-[calc(100vh-233px)]' : 'h-[calc(100vh-186px)]'}`}
                            scrollbarSize={4}
                        >
                            <div ref={containerRef} style={{ width: '100%', minHeight: '400px' }}>
                                {!isLayoutLoaded || width === 0 ? (
                                    <Center h={400} w="100%">
                                        <Loader size="lg" />
                                    </Center>
                                ) : (
                                    <ResponsiveGridLayout
                                        className="layout"
                                        width={width}
                                        layouts={{
                                            lg: layout.map(item => ({
                                                ...item,
                                                static: !isCustomizationMode
                                            }))
                                        }}
                                        breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
                                        cols={{ lg: 4, md: 4, sm: 2, xs: 1, xxs: 1 }}
                                        rowHeight={30}
                                        onLayoutChange={onLayoutChange}
                                        draggableHandle=".draggable-header"
                                        isDraggable={isCustomizationMode}
                                        isResizable={isCustomizationMode}
                                    >
                                        {layout.map(item => {
                                            const widget = WIDGETS_CONFIG[item.i];
                                            if (!widget) return null;

                                            const dragHandle = (
                                                <div
                                                    className="drag-handle"
                                                    style={{
                                                        cursor: 'grab',
                                                        opacity: 0.5,
                                                        display: 'flex',
                                                        alignItems: 'center',
                                                        justifyContent: 'center',
                                                        padding: '4px',
                                                        borderRadius: '4px',
                                                    }}
                                                >
                                                    <ThemeIcon variant="transparent" color="gray" size="sm">
                                                        <IconGripVertical size={16} />
                                                    </ThemeIcon>
                                                </div>
                                            );

                                            return (
                                                <div key={item.i}>
                                                    <Box
                                                        pos="relative"
                                                        h="100%"
                                                        style={{ overflow: 'hidden' }}
                                                        className={wiggle ? 'wiggle' : ''}
                                                    >
                                                        {React.cloneElement(widget.component, { dragHandle: isCustomizationMode ? dragHandle : null })}
                                                    </Box>
                                                </div>
                                            );
                                        })}
                                    </ResponsiveGridLayout>
                                )}
                            </div>
                        </ScrollArea>
                    </div>
                </Container>

                <Modal
                    opened={config?.lazytasks_basic_info_guide_modal && appLocalizer?.is_admin}
                    onClose={() => setConfig({ ...config, lazytasks_basic_info_guide_modal: false })}
                    title=""
                    size="auto"
                    // scrollAreaComponent={ScrollArea.Autosize}
                    withCloseButton={false}
                    closeOnClickOutside={false}
                    centered
                >
                    <Onboarding />
                </Modal>

                {notEngagedModalOpen && (
                    <Modal
                        opened={notEngagedModalOpen}
                        title={
                            <>
                                <Group spacing="xs">
                                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                                        <IconLock size={24} />
                                    </ThemeIcon>
                                    <Text size="md" weight={500}>
                                        {translate('You are not assigned to any project in LazyTask!')}
                                    </Text>
                                </Group>
                            </>
                        }
                        size="md"
                        withCloseButton={false}
                        closeOnClickOutside={false}
                        returnFocus={false}
                        centered
                        overlayProps={{
                            color: 'rgba(0, 0, 0, 0.85)', // dark semi-transparent background
                            blur: 3,                      // slightly blurred background
                            opacity: 1,                 // more visible dark overlay
                            zIndex: 200,
                        }}
                    >
                        <Divider size="xs" my={0} className='!-ml-4 w-[calc(100%+2rem)]' />
                        <Stack spacing="md" pt="md">
                            <Text size="sm" ta="center" pt={5} c="#4D4D4D">
                                {translate('You are currently added as a user in WordPress, but you are not assigned to any project in the LazyTask.')} <br />
                                <strong>
                                    {translate('To start working in LazyTask, please contact the admin so they can assign you to a project.')}
                                </strong>
                            </Text>
                            <Group mt="sm" justify="center">
                                <Button
                                    variant='filled'
                                    color='orange'
                                    tabIndex={-1}
                                    onClick={handleGoBack}
                                    style={{ outline: 'none', boxShadow: 'none' }}
                                    fullWidth
                                >
                                    {translate('Back to Home')}
                                </Button>
                            </Group>
                        </Stack>
                    </Modal>
                )}

                <Modal
                    opened={customizationModalOpen}
                    onClose={() => setCustomizationModalOpen(false)}
                    title={translate('Customize Dashboard')}
                    centered
                >
                    <Text size="sm">
                        {translate('You can now customize the layout, allowing you to drag and drop or resize widgets. Are you sure you want to proceed?')}
                    </Text>
                    <Group justify="flex-end" mt="md">
                        <Button variant="default" onClick={() => setCustomizationModalOpen(false)}>
                            {translate('Cancel')}
                        </Button>
                        <Button color="orange" onClick={handleEnableCustomization}>
                            {translate('Yes, Customize')}
                        </Button>
                    </Group>
                </Modal>

                <Modal
                    opened={resetModalOpen}
                    onClose={() => setResetModalOpen(false)}
                    title={translate('Reset Dashboard Layout')}
                    centered
                >
                    <Text size="sm">
                        {translate('Are you sure you want to reset the dashboard layout to its default state? This action cannot be undone.')}
                    </Text>
                    <Group justify="flex-end" mt="md">
                        <Button variant="default" onClick={() => setResetModalOpen(false)}>
                            {translate('Cancel')}
                        </Button>
                        <Button color="red" onClick={handleResetLayout}>
                            {translate('Yes, Reset')}
                        </Button>
                    </Group>
                </Modal>

                <Modal
                    opened={unsavedChangesModalOpen}
                    onClose={() => setUnsavedChangesModalOpen(false)}
                    title={translate('Unsaved Changes')}
                    centered
                >
                    <Text size="sm">
                        {translate('You have unsaved changes. Do you want to save before leaving?')}
                    </Text>
                    <Group justify="flex-end" mt="md">
                        <Button variant="default" onClick={() => {
                            setLayout(layoutSnapshot);
                            setLayoutSnapshot(null);
                            setIsCustomizationMode(false);
                            setUnsavedChangesModalOpen(false);
                        }}>
                            {translate('Discard Changes')}
                        </Button>
                        <Button color="orange" onClick={() => {
                            setUnsavedChangesModalOpen(false);
                            handleSaveLayout();
                        }}>
                            {translate('Save & Exit')}
                        </Button>
                    </Group>
                </Modal>

            </div>

            {/* <Footer /> */}
        </Fragment>

    );
}

export default Dashboard;
