import React, { useState, useEffect } from 'react';
import {
    IconSettings2,
    IconBuilding,
    IconShieldCheck,
    IconBell,
    IconCertificate,
    IconUsers,
} from '@tabler/icons-react';
import { useSelector, useDispatch } from 'react-redux';
import { useSearchParams } from 'react-router-dom';
import { fetchUserPermissions } from '../../../store/auth/permissionsSlice';
import { hasPermission } from '../../ui/permissions';
import { __ } from '@wordpress/i18n';
import GeneralTabV3 from './GeneralTabV3';
import WorkspaceProjectsTabV3 from './WorkspaceProjectsTabV3';
import RolesPermissionsTabV3 from './RolesPermissionsTabV3';
import NotificationTemplatesTabV3 from './NotificationTemplatesTabV3';
import LicenseTabV3 from './LicenseTabV3';
import ManageUsersTabV3 from './ManageUsersTabV3';
import { ADDON_REGISTRY } from './addonRegistry';

const TabButton = ({ value, icon, label, isActive, onClick }) => {
    const [hovered, setHovered] = useState(false);
    return (
        <button
            onClick={() => onClick(value)}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => setHovered(false)}
            style={{
                height: 30,
                padding: '0 14px',
                borderRadius: 6,
                background: isActive ? '#39758D' : hovered ? '#dce7ec' : '#EBF1F4',
                color: isActive ? '#fff' : '#000',
                fontSize: 13,
                fontWeight: 500,
                border: 'none',
                cursor: 'pointer',
                display: 'inline-flex',
                alignItems: 'center',
                gap: 6,
                fontFamily: 'inherit',
                transition: '150ms ease',
            }}
        >
            {icon}
            {label}
        </button>
    );
};

const SettingsPageV3 = () => {
    const { loggedInUser } = useSelector((state) => state.auth.session);

    const hasGeneral      = hasPermission(loggedInUser, ['general-settings', 'portal-management', 'manage-notification', 'manage-addon', 'manage-tags'], null, 'global');
    const hasWP           = hasPermission(loggedInUser, ['manage-workspace', 'delete-workspace', 'manage-project', 'delete-project'], null, 'global');
    const hasRoles        = hasPermission(loggedInUser, ['manage-roles-permissions'], null, 'global');
    const hasNotifications= hasPermission(loggedInUser, ['manage-notification'], null, 'global');
    const hasManageUsers  = hasPermission(loggedInUser, ['manage-users'], null, 'global');
    const hasLicense      = hasPermission(loggedInUser, ['manage-license'], null, 'global');

    const dispatch = useDispatch();

    React.useEffect(() => {
        dispatch(fetchUserPermissions());
    }, [dispatch]);

    // Coexistence: when the notification addon is active it supplies the templates tab;
    // otherwise fall back to the embedded NotificationTemplatesTabV3.
    const [NotificationTab, setNotificationTab] = useState(() => window.lazytasksNotification?.settingsTab?.component || null);
    useEffect(() => {
        const onNotificationReady = () => setNotificationTab(() => window.lazytasksNotification?.settingsTab?.component || null);
        if (!window.lazytasksNotification) {
            window.addEventListener('lazytasksNotificationReady', onNotificationReady);
        }
        return () => window.removeEventListener('lazytasksNotificationReady', onNotificationReady);
    }, []);
    const notificationReleased = ADDON_REGISTRY.notification?.status === 'released';

    let defaultTab = null;
    if (hasGeneral)            defaultTab = 'general';
    else if (hasWP)            defaultTab = 'workspace';
    else if (hasManageUsers)   defaultTab = 'users';
    else if (hasRoles)         defaultTab = 'roles';
    else if (hasNotifications) defaultTab = 'notifications';
    else if (hasLicense)       defaultTab = 'license';

    const VALID_TABS = ['general', 'workspace', 'users', 'roles', 'notifications', 'license'];
    const [searchParams, setSearchParams] = useSearchParams();
    const tabParam = searchParams.get('tab');
    const [activeTab, setActiveTab] = useState(VALID_TABS.includes(tabParam) ? tabParam : defaultTab);

    // Sync activeTab when URL search params change (e.g. cross-tab navigation)
    useEffect(() => {
        if (tabParam && VALID_TABS.includes(tabParam) && tabParam !== activeTab) {
            setActiveTab(tabParam);
        }
    }, [tabParam]);

    const handleTabChange = (tab) => {
        setActiveTab(tab);
        setSearchParams({ tab });
    };

    return (
        <div className="dashboard" style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 60px)', overflow: 'hidden' }}>
            <div style={{ padding: '0 20px 0', display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>
                <div style={{ maxWidth: 1280, width: '100%', margin: '0 auto', paddingTop: 16, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
                    <div style={{ fontSize: 17, fontWeight: 700, color: '#1A202C', marginBottom: 12 }}>
                        {__( 'Settings', 'lazytasks-project-task-management' )}
                    </div>

                    <div style={{ display: 'flex', gap: 4, marginBottom: 24, flexWrap: 'wrap' }}>
                        {hasGeneral && (
                            <TabButton value="general" icon={<IconSettings2 size={15} stroke={1.5} />} label={__( 'General', 'lazytasks-project-task-management' )} isActive={activeTab === 'general'} onClick={handleTabChange} />
                        )}
                        {hasWP && (
                            <TabButton value="workspace" icon={<IconBuilding size={15} stroke={1.5} />} label={__( 'Workspace & Projects', 'lazytasks-project-task-management' )} isActive={activeTab === 'workspace'} onClick={handleTabChange} />
                        )}
                        {hasManageUsers && (
                            <TabButton value="users" icon={<IconUsers size={15} stroke={1.5} />} label={__( 'Manage Users', 'lazytasks-project-task-management' )} isActive={activeTab === 'users'} onClick={handleTabChange} />
                        )}
                        {hasRoles && (
                            <TabButton value="roles" icon={<IconShieldCheck size={15} stroke={1.5} />} label={__( 'Roles & Permissions', 'lazytasks-project-task-management' )} isActive={activeTab === 'roles'} onClick={handleTabChange} />
                        )}
                        {hasNotifications && (
                            <TabButton value="notifications" icon={<IconBell size={15} stroke={1.5} />} label={__( 'Notification Templates', 'lazytasks-project-task-management' )} isActive={activeTab === 'notifications'} onClick={handleTabChange} />
                        )}
                        {hasLicense && (
                            <TabButton value="license" icon={<IconCertificate size={15} stroke={1.5} />} label={__( 'License', 'lazytasks-project-task-management' )} isActive={activeTab === 'license'} onClick={handleTabChange} />
                        )}
                    </div>

                    <div style={{ flex: 1, overflowY: activeTab === 'general' ? 'hidden' : 'auto', overflowX: 'hidden', minHeight: 0, paddingBottom: activeTab === 'general' ? 0 : 24 }}>
                        {activeTab === 'general' && hasGeneral && <GeneralTabV3 />}
                        {activeTab === 'workspace' && hasWP && <WorkspaceProjectsTabV3 />}
                        {activeTab === 'users' && hasManageUsers && <ManageUsersTabV3 />}
                        {activeTab === 'roles' && hasRoles && <RolesPermissionsTabV3 />}
                        {activeTab === 'notifications' && hasNotifications && (
                            NotificationTab && notificationReleased ? <NotificationTab /> : <NotificationTemplatesTabV3 />
                        )}
                        {activeTab === 'license' && hasLicense && <LicenseTabV3 />}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default SettingsPageV3;
