import {
    Modal,
    Anchor,
    Text,
    Flex,
    Button,
    Image,
    Box,
    ActionIcon,
} from '@mantine/core';
import {
    IconBrandWhatsapp,
    IconInfoCircle,
    IconDeviceMobile,
    IconLock,
    IconMessages,
    IconPencilStar,
    IconRefresh,
    IconX
} from '@tabler/icons-react';
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fatchLazytasksConfig } from "../Settings/store/settingSlice";
import androidQR from '../../assets/android.png';
import iosQR from '../../assets/ios.png';
import appleStoreIcon from '../../assets/app-store-icon.png';
import googlePlayIcon from '../../assets/google-play-icon.png';
import { translate } from "../../utils/i18n";
import { useDisclosure } from "@mantine/hooks";
import { FeedbackForm } from "./FeedbackForm";
import { AboutModal } from "./AboutModal";
import FluentFormIframe from "./FluentFormIframe";
import {hasPermission} from "../ui/permissions";

const S = {
    orange: '#ED7D31',
    orangeDk: '#D46A1E',
    orangeLt: '#FEF0E6',
    teal: '#39758D',
    tealLt: '#EBF1F4',
    bg: '#F4F6F8',
    white: '#FFFFFF',
    border: '#E2E8F0',
    text: '#1A202C',
    muted: '#64748B',
    light: '#94A3B8',
    shadow: '0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.05)',
    radius: 12,
    radiusSm: 6,
};

export function MobileAppPopover() {
    const [opened, setOpened] = useState(false);
    const dispatch = useDispatch();
    const { lazytasksConfig } = useSelector((state) => state.settings.setting);
    const [config, setConfig] = useState(lazytasksConfig);
    const { loggedInUser, xWpNonce } = useSelector((state) => state.auth.session);
    const [feedbackModalOpened, { open: feedbackModalOpen, close: feedbackModalClose }] = useDisclosure(false);
    const [aboutModalOpened, { open: aboutModalOpen, close: aboutModalClose }] = useDisclosure(false);

    useEffect(() => {
        const fetchData = async () => {
            try {
                if (xWpNonce && loggedInUser && hasPermission(loggedInUser, ['general-settings'], null, 'global')) {
                    await dispatch(fatchLazytasksConfig()).then((response) => {
                        if (response.payload && response.payload.status === 200) {
                            setConfig(response.payload.data);
                        }
                    });
                }
            } catch (err) {
                console.error("Unexpected error:", err);
            }
        };
        fetchData();
    }, [dispatch, xWpNonce]);

    const hasRoleAdministrator = loggedInUser?.is_superadmin ?? false;
    const isPremium = appLocalizer.premiumInstalled !== '' && window.appLocalizerPremium;
    const isFree = appLocalizer.premiumInstalled === '' && window.appLocalizerPremium === undefined;

    return (
        <>
            <Button
                size="sm"
                h={32}
                className="font-semibold"
                onClick={() => setOpened(true)}
                variant="filled"
                color={S.teal}
                style={{ fontSize: 13, borderRadius: S.radiusSm }}
            >
                {translate('Mobile App')}
            </Button>

            <Modal
                opened={opened}
                onClose={() => setOpened(false)}
                size="700px"
                centered
                withCloseButton={false}
                zIndex={10000}
                padding={0}
                radius={S.radius}
            >
                <Box p="xl" pt="lg">
                    {/* Header */}
                    <Flex align="center" justify="space-between" mb="lg">
                        <Flex align="center" gap={10}>
                            <IconDeviceMobile size={20} color={S.teal} stroke={2} />
                            <Box>
                                <Text size="md" fw={700} c={S.text}>
                                    {translate('Connect LazyTasks Mobile App')}
                                </Text>
                                {isFree &&
                                    <Text size="xs" c={S.muted}>
                                        {translate('Free version — upgrade to connect your workspace')}
                                    </Text>
                                }
                            </Box>
                        </Flex>
                        <ActionIcon variant="light" color="gray" radius={S.radiusSm} onClick={() => setOpened(false)}>
                            <IconX size={14} stroke={2.5} />
                        </ActionIcon>
                    </Flex>

                    {/* Step 1: Download */}
                    <Box mb="md">
                        <Flex align="center" gap={10} mb={6}>
                            <Box style={{
                                width: 24, height: 24, borderRadius: '50%',
                                background: S.orange, color: '#fff',
                                fontSize: 12, fontWeight: 700,
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                flexShrink: 0,
                            }}>1</Box>
                            <Text size="sm" fw={600} c={S.text}>{translate('Download LazyTasks Mobile App')}</Text>
                        </Flex>
                        <Text size="xs" c={S.muted} ml={34} mb="sm" lh={1.5}>
                            {translate('Scan the QR code for your device, or tap the store badge to download.')}
                        </Text>
                        <Flex gap={12} ml={34}>
                            <Anchor
                                href="https://play.google.com/store/apps/details?id=com.lazytasks.lazycoders"
                                target="_blank"
                                underline="never"
                                style={{
                                    flex: 1, background: S.bg, borderRadius: S.radiusSm,
                                    padding: 16, display: 'flex', flexDirection: 'column',
                                    alignItems: 'center', gap: 10, border: '1px solid transparent',
                                    transition: 'all 180ms ease',
                                }}
                                className="qr-download-card"
                            >
                                <Text size="xs" fw={500} c={S.muted}>{translate('Android')}</Text>
                                <Image radius="sm" h={120} w={120} fit="contain" src={androidQR} />
                                <Image radius="sm" h={28} w="auto" src={googlePlayIcon} />
                            </Anchor>
                            <Anchor
                                href="https://apps.apple.com/us/app/lazytasks/id6499516984"
                                target="_blank"
                                underline="never"
                                style={{
                                    flex: 1, background: S.bg, borderRadius: S.radiusSm,
                                    padding: 16, display: 'flex', flexDirection: 'column',
                                    alignItems: 'center', gap: 10, border: '1px solid transparent',
                                    transition: 'all 180ms ease',
                                }}
                                className="qr-download-card"
                            >
                                <Text size="xs" fw={500} c={S.muted}>{translate('iOS')}</Text>
                                <Image radius="sm" h={120} w={120} fit="contain" src={iosQR} />
                                <Image radius="sm" h={28} w="auto" src={appleStoreIcon} />
                            </Anchor>
                        </Flex>
                    </Box>

                    {/* Divider */}
                    <Box style={{ height: 1, background: S.border, marginLeft: 34 }} mb="md" />

                    {/* Step 2: Connect (Premium) or Upgrade (Free) */}
                    <Box>
                        <Flex align="center" gap={10} mb={6}>
                            <Box style={{
                                width: 24, height: 24, borderRadius: '50%',
                                background: S.orange, color: '#fff',
                                fontSize: 12, fontWeight: 700,
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                flexShrink: 0,
                            }}>2</Box>
                            <Text size="sm" fw={600} c={S.text}>{translate('Connect to Your Workspace')}</Text>
                        </Flex>

                        {isPremium && (
                            <>
                                <Text size="xs" c={S.muted} ml={34} mb="sm" lh={1.5}>
                                    {translate('Open the app and scan this code to link your account.')}
                                </Text>
                                <Flex
                                    ml={34}
                                    style={{ background: S.bg, borderRadius: S.radiusSm, padding: 20 }}
                                    align="center"
                                    gap={24}
                                >
                                    <Image
                                        radius="sm"
                                        h={120}
                                        w={120}
                                        fit="contain"
                                        src={lazytasksConfig && lazytasksConfig.qrCode}
                                        style={{ flexShrink: 0 }}
                                    />
                                    <Box style={{ flex: 1 }}>
                                        <Text size="xs" c={S.text} lh={1.8} mb={8}>
                                            <Text span fw={600} c={S.teal}>1.</Text> {translate('Open LazyTasks on your phone')}<br/>
                                            <Text span fw={600} c={S.teal}>2.</Text> {translate('Tap')} <Text span fw={600} c={S.teal}>{translate('"Scan QR Code"')}</Text> {translate('on the login screen')}<br/>
                                            <Text span fw={600} c={S.teal}>3.</Text> {translate('Point your camera at this code')}
                                        </Text>
                                        <Flex align="center" gap={4}>
                                            <IconRefresh size={12} color={S.light} stroke={2} />
                                            <Text size="xs" c={S.light}>{translate('This code refreshes automatically')}</Text>
                                        </Flex>
                                    </Box>
                                </Flex>
                            </>
                        )}

                        {isFree && (
                            <>
                                {hasRoleAdministrator ? (
                                    <Box
                                        ml={34}
                                        style={{
                                            background: S.orangeLt, border: `1px solid #f5d5b8`,
                                            borderRadius: S.radiusSm, padding: 20,
                                        }}
                                    >
                                        <Flex align="flex-start" gap={16}>
                                            <Box style={{
                                                width: 44, height: 44, borderRadius: '50%',
                                                background: S.white, display: 'flex',
                                                alignItems: 'center', justifyContent: 'center',
                                                flexShrink: 0, boxShadow: S.shadow,
                                            }}>
                                                <IconLock size={22} color={S.orange} stroke={2} />
                                            </Box>
                                            <Box style={{ flex: 1 }}>
                                                <Text size="xs" fw={700} c={S.orange} tt="uppercase" style={{ letterSpacing: 0.5 }} mb={4}>
                                                    {translate('Premium Feature')}
                                                </Text>
                                                <Text size="xs" c={S.text} lh={1.5} mb={12}>
                                                    {translate('Upgrade to Premium to connect the mobile app and manage your tasks on the go — with real-time sync, push notifications, and full project access.')}
                                                </Text>
                                                <Anchor
                                                    href="https://lazycoders.co/lazytasks/?product_name=lazy_task&plugin_slug=lazytasks-premium#buy-now"
                                                    target="_blank"
                                                    underline="never"
                                                >
                                                    <Button
                                                        size="xs"
                                                        px="lg"
                                                        bg={S.orange}
                                                        radius={S.radiusSm}
                                                        style={{ fontWeight: 600 }}
                                                    >
                                                        {translate('Upgrade Now')}
                                                    </Button>
                                                </Anchor>
                                            </Box>
                                        </Flex>
                                    </Box>
                                ) : (
                                    <Box
                                        ml={34}
                                        style={{
                                            background: S.orangeLt, border: `1px solid #f5d5b8`,
                                            borderRadius: S.radiusSm, padding: 20,
                                        }}
                                    >
                                        <Flex align="center" gap={12}>
                                            <IconLock size={20} color={S.orange} stroke={2} />
                                            <Text size="xs" c={S.text} lh={1.5}>
                                                {translate('Mobile app connection requires Premium. Contact your administrator to upgrade.')}
                                            </Text>
                                        </Flex>
                                    </Box>
                                )}

                                {/* Action buttons row */}
                                <Flex gap={8} mt="lg" pt="md" style={{ borderTop: `1px solid ${S.border}` }}>
                                    <Anchor
                                        href="https://wordpress.org/support/plugin/lazytasks-project-task-management/reviews/#new-post"
                                        target="_blank"
                                        underline="never"
                                        style={{ flex: 1 }}
                                    >
                                        <Button
                                            variant="default"
                                            size="xs"
                                            leftSection={<IconPencilStar size={14} />}
                                            fullWidth
                                            radius={S.radiusSm}
                                            styles={{ root: { color: S.muted, fontWeight: 500 } }}
                                        >
                                            {translate('Review')}
                                        </Button>
                                    </Anchor>
                                    <Button
                                        variant="default"
                                        size="xs"
                                        leftSection={<IconMessages size={14} />}
                                        onClick={feedbackModalOpen}
                                        style={{ flex: 1 }}
                                        radius={S.radiusSm}
                                        styles={{ root: { color: S.muted, fontWeight: 500 } }}
                                    >
                                        {translate('Feedback')}
                                    </Button>
                                    {hasRoleAdministrator &&
                                        <Anchor href="https://wa.me/+16478484547" target="_blank" underline="never" style={{ flex: 1 }}>
                                            <Button
                                                variant="default"
                                                size="xs"
                                                leftSection={<IconBrandWhatsapp size={14} />}
                                                fullWidth
                                                radius={S.radiusSm}
                                                styles={{ root: { color: S.muted, fontWeight: 500 } }}
                                            >
                                                {translate('WhatsApp')}
                                            </Button>
                                        </Anchor>
                                    }
                                    <Button
                                        variant="default"
                                        size="xs"
                                        leftSection={<IconInfoCircle size={14} />}
                                        onClick={aboutModalOpen}
                                        style={{ flex: 1 }}
                                        radius={S.radiusSm}
                                        styles={{ root: { color: S.muted, fontWeight: 500 } }}
                                    >
                                        {translate('About')}
                                    </Button>
                                </Flex>

                                {feedbackModalOpened &&
                                    <FeedbackForm feedbackModalOpen={feedbackModalOpened} setFeedbackModalOpen={feedbackModalClose} />
                                }
                                {aboutModalOpened &&
                                    <AboutModal aboutModalOpen={aboutModalOpened} setAboutModalOpen={aboutModalClose} />
                                }
                            </>
                        )}
                    </Box>
                </Box>
            </Modal>
        </>
    );
}
