import React, { useEffect, useState } from 'react';
import { Alert, Button, Group, Text, Modal, List, Anchor, ScrollArea } from '@mantine/core';
import { IconShieldLock } from '@tabler/icons-react';
import { useSelector } from 'react-redux';
import { __ } from '@wordpress/i18n';
import { getAnalyticsConsent, updateAnalyticsConsent } from '../../services/AnalyticsService';

/**
 * Upgrade-path admin notice for the analytics opt-in.
 *
 * Renders at the top of the LazyTasks admin shell whenever consent state is
 * 'unknown' — which covers:
 *   - Existing users updating from a pre-analytics version of the plugin
 *   - Fresh installs that haven't reached the onboarding consent step yet
 *
 * No "X" close button by design — closing without deciding would leave consent
 * 'unknown' forever and keep nagging on every page load. The user must click
 * one of: Allow / No thanks / Learn more.
 *
 * Only visible to authenticated users with admin context. Hides itself after a
 * decision is made.
 */
const AnalyticsConsentNotice = () => {
    const session = useSelector((state) => state.auth?.session);
    const isAuthenticated = !!session?.token;
    // Restrict the notice to WP admins (administrator role). Lower-privileged
    // users like Editors or LazyTasks-only roles never see it — analytics
    // consent is a site-level decision the site owner should make.
    const isWpAdmin = !!session?.loggedInUser?.roles?.includes('administrator');

    const [shouldShow, setShouldShow] = useState(false);
    const [submitting, setSubmitting] = useState(false);
    const [learnOpen, setLearnOpen]   = useState(false);

    useEffect(() => {
        // Don't fire the API call until the user is a logged-in WP admin —
        // this notice mounts at the top of every admin page, including the
        // login screen, and we don't want to spam an unauthenticated check.
        if (!isAuthenticated || !isWpAdmin) {
            setShouldShow(false);
            return;
        }
        let cancelled = false;
        (async () => {
            try {
                const res = await getAnalyticsConsent();
                // Backend computes should_show_notice from consent state + snooze schedule.
                if (!cancelled && res?.data?.should_show_notice === true) {
                    setShouldShow(true);
                }
            } catch (e) {
                // Permission errors etc. — silently skip; notice is non-critical UI.
                if (!cancelled) setShouldShow(false);
            }
        })();
        return () => { cancelled = true; };
    }, [isAuthenticated, isWpAdmin]);

    const decide = async (state) => {
        setSubmitting(true);
        try {
            await updateAnalyticsConsent({ state, source: 'upgrade_notice' });
            setShouldShow(false);
        } catch (e) {
            // notified by BaseService
        } finally {
            setSubmitting(false);
        }
    };

    if (!shouldShow) return null;

    return (
        <>
            <div style={{ padding: '8px 16px 0' }}>
                <Alert
                    icon={<IconShieldLock size={18} />}
                    color="orange"
                    variant="light"
                    radius="md"
                    withCloseButton={false}
                    title={__('Help us improve LazyTasks', 'lazytasks-project-task-management')}
                >
                    <Text size="sm" mb="sm">
                        {__('Please allow LazyTasks to collect optional anonymous usage analytics to help shape the roadmap. We DO NOT collect any specific data on task content, project names, or personal data — we only collect anonymous data to help us improve your experience.', 'lazytasks-project-task-management')}
                    </Text>
                    <Group gap="xs">
                        <Button
                            color="orange"
                            size="xs"
                            loading={submitting}
                            onClick={() => decide('granted')}
                        >
                            {__('Allow analytics', 'lazytasks-project-task-management')}
                        </Button>
                        <Button
                            variant="default"
                            size="xs"
                            loading={submitting}
                            onClick={() => decide('declined')}
                        >
                            {__('Not now', 'lazytasks-project-task-management')}
                        </Button>
                        <Button
                            variant="subtle"
                            color="gray"
                            size="xs"
                            onClick={() => setLearnOpen(true)}
                        >
                            {__('Learn more', 'lazytasks-project-task-management')}
                        </Button>
                    </Group>
                </Alert>
            </div>

            <Modal
                opened={learnOpen}
                onClose={() => setLearnOpen(false)}
                title={__('What we collect', 'lazytasks-project-task-management')}
                centered
                size="lg"
            >
                <ScrollArea h={400} scrollbarSize={6}>
                    <Text size="sm" fw={600} mb={6}>{__('When analytics is on', 'lazytasks-project-task-management')}</Text>
                    <List size="sm" spacing="xs" mb="md">
                        <List.Item>{__('Plugin / WordPress / PHP version, locale, multisite flag', 'lazytasks-project-task-management')}</List.Item>
                        <List.Item>{__('Counts of feature use (task created, project created, settings updated, addon enabled / disabled)', 'lazytasks-project-task-management')}</List.Item>
                        <List.Item>{__('PHP fatal errors originating in this plugin (sanitized — no file paths, credentials, or API keys)', 'lazytasks-project-task-management')}</List.Item>
                        <List.Item>{__('A randomly-generated anonymous site identifier so we can group events from the same install', 'lazytasks-project-task-management')}</List.Item>
                    </List>

                    <Text size="sm" fw={600} mb={6}>{__('We never collect', 'lazytasks-project-task-management')}</Text>
                    <List size="sm" spacing="xs" mb="md">
                        <List.Item>{__('Task content, project names, comments, attachments', 'lazytasks-project-task-management')}</List.Item>
                        <List.Item>{__('User names, emails, or any user-identifiable data', 'lazytasks-project-task-management')}</List.Item>
                        <List.Item>{__('Site URL, IP addresses (stripped at our receiver)', 'lazytasks-project-task-management')}</List.Item>
                    </List>

                    <Text size="sm" fw={600} mb={6}>{__('Your control', 'lazytasks-project-task-management')}</Text>
                    <List size="sm" spacing="xs" mb="md">
                        <List.Item>{__('You can change this any time in Settings → Privacy & Analytics.', 'lazytasks-project-task-management')}</List.Item>
                        <List.Item>{__('"Delete my analytics data" purges every locally-queued event and asks our backend to remove anything we have already received.', 'lazytasks-project-task-management')}</List.Item>
                    </List>

                    <Text size="xs" c="dimmed">
                        <Anchor href="https://lazycoders.co/privacy" target="_blank" rel="noreferrer">
                            {__('Read the full privacy policy', 'lazytasks-project-task-management')}
                        </Anchor>
                    </Text>
                </ScrollArea>

                <Group justify="flex-end" mt="md">
                    <Button variant="default" onClick={() => setLearnOpen(false)}>
                        {__('Close', 'lazytasks-project-task-management')}
                    </Button>
                </Group>
            </Modal>
        </>
    );
};

export default AnalyticsConsentNotice;
