import cx from 'clsx';
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    IconTable,
    IconListCheck,
    IconAppWindow,
    IconBell,
    IconChevronDown,
    IconPencil,
    IconSettings,
    IconLogout,
    IconPencilStar,
    IconMessages,
    IconInfoCircle,
    IconArrowsMaximize,
    IconArrowsMinimize,
    IconMenu2,
} from '@tabler/icons-react';
import {
    Avatar,
    Box,
    Burger,
    Button,
    Drawer,
    Group,
    Menu,
    rem,
    ScrollArea,
    Text,
    Title,
    Tooltip,
    UnstyledButton,
} from '@mantine/core';
import { useDisclosure, useFullscreen } from '@mantine/hooks';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { hasPermission } from '../ui/permissions';
import { translate } from '../../utils/i18n';
import appConfig from '../../configs/app.config';
import WorkspaceLists from '../Elements/Workspace/WorkspaceLists';
import ProfileEditDrawer from '../Profile/ProfileEditDrawer';
import ChangePassword from '../Profile/ChangePassword';
import { NotificationPopover } from './NotificationPopover';
import { MobileAppPopover } from './MobileAppPopover';
import { FeedbackForm } from './FeedbackForm';
import { AboutModal } from './AboutModal';
import LicenseWarningModal from '../LicenseWarningModal';
import { SuperAdminRoleAssignmentModal } from '../SuperAdminRoleAssignmentModal';
import useAuth from '../../utils/useAuth';
import { fetchSettings, fatchLazytasksConfig } from '../Settings/store/settingSlice';
import classes from './HeaderTabs.module.css';

const S = {
    white: '#FFFFFF', border: '#E2E8F0',
    orange: '#ED7D31',
    teal: '#39758D', tealLt: '#EBF1F4', tealNav: '#18313B',
    text: '#1A202C',
    radius: 6,
};

function HnBtn({ children, active, onClick, style, href, target, textColor, darkBg }) {
    const [hovered, setHovered] = useState(false);
    const base = {
        display: 'inline-flex', alignItems: 'center', gap: 6,
        height: 32, padding: '0 12px',
        borderRadius: S.radius,
        fontSize: 13, fontWeight: 600,
        border: 'none', cursor: 'pointer',
        transition: 'background 150ms, color 150ms',
        fontFamily: 'inherit',
        textDecoration: 'none',
        background: active ? S.tealNav : hovered
            ? (darkBg ? 'rgba(255,255,255,0.2)' : '#d8e8ed')
            : (darkBg ? 'rgba(255,255,255,0.1)' : S.tealLt),
        color: active ? '#fff' : (textColor || '#202020'),
    };
    if (href) {
        return (
            <a href={href} target={target} style={base}
                onMouseEnter={() => setHovered(true)}
                onMouseLeave={() => setHovered(false)}
            >
                {children}
            </a>
        );
    }
    return (
        <button style={{ ...base, ...style }} onClick={onClick}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => setHovered(false)}
        >
            {children}
        </button>
    );
}

function NavDrawerItem({ icon, label, active, onClick, href, target }) {
    const [hovered, setHovered] = useState(false);
    const base = {
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px',
        borderRadius: S.radius,
        fontSize: 14, fontWeight: 600,
        border: 'none', cursor: 'pointer',
        transition: 'background 150ms, color 150ms',
        fontFamily: 'inherit',
        textDecoration: 'none',
        width: '100%',
        background: active ? S.tealNav : hovered ? '#d8e8ed' : 'transparent',
        color: active ? '#fff' : '#202020',
    };
    if (href) {
        return (
            <a href={href} target={target} style={base}
                onMouseEnter={() => setHovered(true)}
                onMouseLeave={() => setHovered(false)}
                onClick={onClick}
            >
                {icon} {label}
            </a>
        );
    }
    return (
        <button style={base} onClick={onClick}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => setHovered(false)}
        >
            {icon} {label}
        </button>
    );
}

export function HeaderV3({ headerTimer = null, timeTrackerNavLink = null, performanceNavLink = null }) {
    const navigate = useNavigate();
    const location = useLocation();
    const { signOut } = useAuth();
    const dispatch = useDispatch();

    const { loggedInUser, xWpNonce } = useSelector(state => state.auth.session);
    const { portalSettings, lazytasksSiteSettings } = useSelector(state => state.settings.setting);


    useEffect(() => {
        if (xWpNonce) {
            dispatch(fetchSettings());
            dispatch(fatchLazytasksConfig());
        }
    }, [dispatch, xWpNonce]);

    let siteLogo = null;
    let siteTitle = null;
    let showLogoInHeader = true;
    let showTitleInHeader = true;
    let headerTitleSize = 's';
    let headerMenuDisplay = 'icon-text';
    let headerTitleColor = null;
    let headerBgColor = '#FFFFFF';
    let headerBgGradient = false;
    let headerBgColor2 = '#EBF1F4';
    if (lazytasksSiteSettings?.core_setting) {
        try {
            const core = JSON.parse(lazytasksSiteSettings.core_setting);
            if (core.site_logo) siteLogo = window.location.protocol === 'https:' ? core.site_logo.replace(/^http:\/\//i, 'https://') : core.site_logo;
            if (core.site_title) siteTitle = core.site_title;
            if (core.show_logo_in_header !== undefined) showLogoInHeader = core.show_logo_in_header !== false;
            if (core.show_title_in_header !== undefined) showTitleInHeader = core.show_title_in_header !== false;
            if (core.header_title_size) headerTitleSize = core.header_title_size;
            if (core.header_menu_display) headerMenuDisplay = core.header_menu_display;
            if (core.header_title_color) headerTitleColor = core.header_title_color;
            if (core.header_bg_color) headerBgColor = core.header_bg_color;
            headerBgGradient = core.header_bg_gradient === true;
            if (core.header_bg_color2) headerBgColor2 = core.header_bg_color2;
        } catch (e) {}
    }
    const titleFontSize = { s: 14, m: 18, lg: 24 }[headerTitleSize] ?? 14;

    const isDarkBg = (() => {
        const hex = headerBgColor.replace('#', '');
        const r = parseInt(hex.substr(0, 2), 16);
        const g = parseInt(hex.substr(2, 2), 16);
        const b = parseInt(hex.substr(4, 2), 16);
        return (r * 0.299 + g * 0.587 + b * 0.114) < 140;
    })();
    const headerTextColor = isDarkBg ? '#FFFFFF' : S.text;

    const [userMenuOpened, setUserMenuOpened] = useState(false);
    const [opened, { open, close, toggle }] = useDisclosure(false);
    const [profileDrawerOpened, { open: profileDrawerOpen, close: profileDrawerClose }] = useDisclosure(false);
    const [feedbackModalOpened, { open: feedbackModalOpen, close: feedbackModalClose }] = useDisclosure(false);
    const [aboutModalOpened, { open: aboutModalOpen, close: aboutModalClose }] = useDisclosure(false);
    const [navDrawerOpened, { open: openNavDrawer, close: closeNavDrawer }] = useDisclosure(false);
    const wpSidebarWasFolded = useRef(false);

    const handleNavDrawerOpen = () => {
        if (appLocalizer?.is_admin) {
            wpSidebarWasFolded.current = document.body.classList.contains('folded');
            if (!wpSidebarWasFolded.current) {
                document.body.classList.add('folded');
            }
        }
        openNavDrawer();
    };

    const handleNavDrawerClose = () => {
        if (appLocalizer?.is_admin && !wpSidebarWasFolded.current) {
            document.body.classList.remove('folded');
        }
        closeNavDrawer();
    };

    const { toggle: toggleFullscreen, fullscreen } = useFullscreen();

    const settingsLink = hasPermission(loggedInUser, ['general-settings', 'portal-management', 'manage-workspace', 'delete-workspace', 'manage-project', 'delete-project', 'manage-roles-permissions', 'manage-notification', 'manage-license', 'manage-users', 'manage-addon', 'manage-tags'], null, 'global') ? '/v3/settings' : null;

    return (
        <div style={{
            height: 60,
            background: headerBgGradient
                ? `linear-gradient(to right, ${headerBgColor}, ${headerBgColor2})`
                : headerBgColor,
            borderBottom: `1px solid ${S.border}`,
            display: 'flex',
            alignItems: 'center',
            padding: '0 20px',
            gap: 0,
            position: 'relative',
        }}>
            {/* Logo */}
            {showLogoInHeader && (
                <a
                    href="#"
                    onClick={e => { e.preventDefault(); navigate('/dashboard'); }}
                    style={{
                        display: 'flex', alignItems: 'center', gap: 8,
                        marginRight: 20, textDecoration: 'none', flexShrink: 0,
                        height: 40,
                    }}
                >
                    {siteLogo ? (
                        <img
                            src={siteLogo}
                            alt="Logo"
                            style={{ maxHeight: 36, maxWidth: 140, objectFit: 'contain', display: 'block' }}
                        />
                    ) : (
                        <>
                            <div style={{
                                width: 32, height: 32, background: S.orange,
                                borderRadius: S.radius,
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                flexShrink: 0,
                            }}>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                                    <polyline points="9 11 12 14 22 4" />
                                    <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
                                </svg>
                            </div>
                            <span style={{ fontSize: 15, fontWeight: 700, color: headerTextColor, letterSpacing: '-0.3px' }}>
                                LazyTasks
                            </span>
                        </>
                    )}
                </a>
            )}

            {/* Left nav */}
            <nav style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1 }}>
                {!navDrawerOpened && (
                    <>
                        <HnBtn active={location.pathname === '/dashboard'} onClick={() => navigate('/dashboard')} textColor={headerTextColor} darkBg={isDarkBg}>
                            {headerMenuDisplay !== 'text-only' && <IconTable size={16} stroke={1.5} />}
                            {headerMenuDisplay !== 'icon-only' && translate('Dashboard')}
                        </HnBtn>

                        <HnBtn active={location.pathname === '/my-task'} onClick={() => navigate('/my-task')} textColor={headerTextColor} darkBg={isDarkBg}>
                            {headerMenuDisplay !== 'text-only' && <IconListCheck size={16} stroke={1.5} />}
                            {headerMenuDisplay !== 'icon-only' && translate('My Tasks')}
                        </HnBtn>

                        <HnBtn onClick={handleNavDrawerOpen} textColor={headerTextColor} darkBg={isDarkBg}>
                            <IconMenu2 size={16} stroke={1.5} />
                        </HnBtn>
                    </>
                )}

            </nav>

            {/* Centered portal title */}
            {siteTitle && showTitleInHeader && (
                <div style={{
                    position: 'absolute',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    pointerEvents: 'none',
                    fontSize: titleFontSize,
                    fontWeight: 600,
                    color: headerTitleColor || headerTextColor,
                    whiteSpace: 'nowrap',
                }}>
                    {siteTitle}
                </div>
            )}

            {/* Right actions — identical to HeaderTabs */}
            <div className='flex items-center gap-2'>
                {headerTimer}
                <MobileAppPopover />

                <Button size="sm" h={32} className={`font-semibold`} onClick={open} variant="filled" color="#ED7D31"
                    style={{ fontSize: 13, borderRadius: 6 }}>
                    {translate('Workspace')}
                </Button>

                <NotificationPopover>
                    <Box className='h-[35px] w-[35px] border border-[#C2D4DC] ml-[6px] mr-[-2px] mt-[8px] rounded-full p-[6px] cursor-pointer'>
                        <IconBell size={20} stroke={1.25} color={headerTextColor} />
                    </Box>
                </NotificationPopover>

                <Burger opened={opened} onClick={toggle} hiddenFrom="xs" size="sm" />

                <Menu
                    width={200}
                    position="bottom-end"
                    transitionProps={{ transition: 'pop-top-right' }}
                    onClose={() => setUserMenuOpened(false)}
                    onOpen={() => setUserMenuOpened(true)}
                    withinPortal
                >
                    <Menu.Target>
                        <UnstyledButton className={cx(classes.user, { [classes.userActive]: userMenuOpened })}>
                            <Group gap={7}>
                                <Avatar src={loggedInUser?.avatar} alt={loggedInUser?.name} radius="xl" size={32} />
                                <Text fw={500} size="sm" lh={1} mr={3} c={headerTextColor}>
                                    {loggedInUser ? loggedInUser.name : ''}
                                </Text>
                                <IconChevronDown style={{ width: rem(12), height: rem(12) }} stroke={1.5} color={headerTextColor} />
                            </Group>
                        </UnstyledButton>
                    </Menu.Target>
                    <Menu.Dropdown>
                        <Menu.Item
                            onClick={profileDrawerOpen}
                            leftSection={<IconPencil style={{ width: rem(16), height: rem(16) }} stroke={1.5} />}
                        >
                            {translate('Profile')}
                        </Menu.Item>

                        {settingsLink && (
                            <Menu.Item
                                onClick={() => navigate(settingsLink)}
                                leftSection={<IconSettings style={{ width: rem(16), height: rem(16) }} stroke={1.5} />}
                                rightSection={
                                    <span style={{ fontSize: 9, fontWeight: 700, background: '#F4A05A', color: '#fff', borderRadius: 4, padding: '1px 5px', lineHeight: '14px', letterSpacing: 0.5 }}>NEW</span>
                                }
                            >
                                {translate('Settings')}
                            </Menu.Item>
                        )}

                        {!appLocalizer?.is_admin && (
                            <Menu.Item
                                onClick={toggleFullscreen}
                                leftSection={fullscreen
                                    ? <IconArrowsMinimize style={{ width: rem(16), height: rem(16) }} stroke={1.5} />
                                    : <IconArrowsMaximize style={{ width: rem(16), height: rem(16) }} stroke={1.5} />
                                }
                            >
                                {fullscreen ? translate('Exit Full Screen') : translate('Full Screen')}
                            </Menu.Item>
                        )}

                        {!appLocalizer?.is_admin && (
                            <Menu.Item
                                onClick={signOut}
                                leftSection={<IconLogout style={{ width: rem(16), height: rem(16) }} color={S.orange} stroke={1.5} />}
                                c={S.orange}
                            >
                                {translate('Logout')}
                            </Menu.Item>
                        )}

                        <Menu.Divider />

                        <Menu.Item
                            leftSection={<IconPencilStar style={{ width: rem(16), height: rem(16) }} stroke={1.5} />}
                            component="a"
                            href="https://wordpress.org/support/plugin/lazytasks-project-task-management/reviews/#new-post"
                            target="_blank"
                        >
                            {translate('Write a Review')}
                        </Menu.Item>

                        <Menu.Item
                            leftSection={<IconMessages style={{ width: rem(16), height: rem(16) }} stroke={1.5} />}
                            onClick={feedbackModalOpen}
                        >
                            {translate('Feedback')}
                        </Menu.Item>

                        <Menu.Item
                            leftSection={<IconInfoCircle style={{ width: rem(16), height: rem(16) }} stroke={1.5} />}
                            onClick={aboutModalOpen}
                        >
                            {translate('About')}
                        </Menu.Item>
                    </Menu.Dropdown>
                </Menu>
            </div>

            {/* Workspace Drawer */}
            <Drawer
                opened={opened}
                onClose={close}
                position="right"
                withCloseButton={false}
                size="lg"
                overlayProps={{ backgroundOpacity: 0.3, blur: 1 }}
                zIndex={10000000}
            >
                <Drawer.Body>
                    <div className='workspace-create-card w-full'>
                        <div className="relative flex justify-between mb-4">
                            <Title order={4}>{translate('Workspace')}</Title>
                            <Drawer.CloseButton />
                        </div>
                        <div className='border-t border-gray-400 w-[calc(100%+4rem)] -ml-8 pt-4 px-4' style={{ borderColor: '#EBF1F4' }} />
                        <WorkspaceLists onClose={close} />
                    </div>
                </Drawer.Body>
            </Drawer>

            {/* Navigation Drawer */}
            <Drawer
                opened={navDrawerOpened}
                onClose={handleNavDrawerClose}
                position="left"
                withCloseButton={false}
                size={280}
                overlayProps={{ backgroundOpacity: 0.3, blur: 1 }}
                zIndex={10000000}
                transitionProps={{ transition: 'slide-right', duration: 250 }}
                styles={{
                    inner: {
                        transform: appLocalizer?.is_admin ? 'translateX(36px)' : 'translateX(0px)',
                    },
                }}
            >
                <Drawer.Body>
                    <div className="flex justify-between items-center mb-4">
                        {siteLogo ? (
                            <img src={siteLogo} alt="Logo"
                                style={{ maxHeight: 28, maxWidth: 120, objectFit: 'contain' }} />
                        ) : (
                            <span style={{ fontSize: 15, fontWeight: 700, color: S.text }}>
                                {translate('Navigation')}
                            </span>
                        )}
                        <Drawer.CloseButton />
                    </div>
                    <div className='border-t w-[calc(100%+2rem)] -ml-4 pt-3 px-1' style={{ borderColor: '#EBF1F4' }} />
                    <nav className="flex flex-col gap-1 mt-2">
                        <NavDrawerItem
                            icon={<IconTable size={18} stroke={1.5} />}
                            label={translate('Dashboard')}
                            active={location.pathname === '/dashboard'}
                            onClick={() => { navigate('/dashboard'); handleNavDrawerClose(); }}
                        />
                        <NavDrawerItem
                            icon={<IconListCheck size={18} stroke={1.5} />}
                            label={translate('My Tasks')}
                            active={location.pathname === '/my-task'}
                            onClick={() => { navigate('/my-task'); handleNavDrawerClose(); }}
                        />

                        {timeTrackerNavLink && (
                            <div onClick={handleNavDrawerClose}
                                style={{ display: 'flex', width: '100%' }}
                                className="[&>button]:!bg-transparent [&>button]:!w-full [&>button]:!h-auto [&>button]:!p-[10px_14px] [&>button]:!text-sm [&>button]:!rounded-md [&>button]:hover:!bg-[#d8e8ed] [&>a]:!bg-transparent [&>a]:!w-full [&>a]:!h-auto [&>a]:!p-[10px_14px] [&>a]:!text-sm [&>a]:!rounded-md [&>a]:hover:!bg-[#d8e8ed]"
                            >
                                {timeTrackerNavLink}
                            </div>
                        )}
                        {performanceNavLink && (
                            <div onClick={handleNavDrawerClose}
                                style={{ display: 'flex', width: '100%' }}
                                className="[&>button]:!bg-transparent [&>button]:!w-full [&>button]:!h-auto [&>button]:!p-[10px_14px] [&>button]:!text-sm [&>button]:!rounded-md [&>button]:hover:!bg-[#d8e8ed] [&>a]:!bg-transparent [&>a]:!w-full [&>a]:!h-auto [&>a]:!p-[10px_14px] [&>a]:!text-sm [&>a]:!rounded-md [&>a]:hover:!bg-[#d8e8ed]"
                            >
                                {performanceNavLink}
                            </div>
                        )}

                        {appLocalizer?.is_admin && portalSettings?.status === 'publish' && (
                            <NavDrawerItem
                                icon={<IconAppWindow size={18} stroke={1.5} />}
                                label={translate('Portal')}
                                href={portalSettings?.permalink || `${appConfig.liveSiteUrl}/lazytasks`}
                                target="_blank"
                                onClick={handleNavDrawerClose}
                            />
                        )}
                    </nav>
                </Drawer.Body>
            </Drawer>

            {/* Profile Drawer */}
            <Drawer
                opened={profileDrawerOpened}
                onClose={profileDrawerClose}
                position="right"
                withCloseButton={false}
                size="md"
                overlayProps={{ backgroundOpacity: 0.5, blur: 1 }}
                zIndex={10000000}
            >
                <Drawer.Body>
                    <div className='workspace-create-card w-full'>
                        <div className="relative flex justify-between mb-4">
                            <Title order={4}>{translate('Profile')}</Title>
                            <Drawer.CloseButton />
                        </div>
                        <ScrollArea scrollbarSize={4} scrollbars="y" offsetScrollbars className="h-[calc(100vh-109px)]">
                            <div className='border-t border-gray-400 w-[calc(100%+4rem)] -ml-8 pt-4 px-4' style={{ borderColor: '#EBF1F4' }} />
                            <ProfileEditDrawer onSuccess={profileDrawerClose} />
                            <div className='border-t border-gray-400 w-[calc(100%+4rem)] -ml-8 pt-4 px-4' style={{ borderColor: '#EBF1F4', marginTop: 20 }} />
                            <ChangePassword onSuccess={profileDrawerClose} />
                        </ScrollArea>
                    </div>
                </Drawer.Body>
            </Drawer>

            <FeedbackForm feedbackModalOpen={feedbackModalOpened} setFeedbackModalOpen={feedbackModalClose} />
            <AboutModal aboutModalOpen={aboutModalOpened} setAboutModalOpen={aboutModalClose} />
            <LicenseWarningModal />
            <SuperAdminRoleAssignmentModal />
        </div>
    );
}
