import { Box, Button, Card, Flex, Group, Modal, Stack, Text, TextInput, SegmentedControl } from "@mantine/core";
import { IconSend } from "@tabler/icons-react";
import React, { useState } from "react";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import { sendTestCampaign } from "@/lib/features/notifications/action";
import NotificationCard from "./notificationCard";

interface DevicePreviewProps {
    title: string;
    body: string;
    image?: string;
}

const DevicePreview: React.FC<DevicePreviewProps> = ({ title, body, image }) => {
    const [device, setDevice] = useState<"android" | "ios">("ios");
    const [opened, { open, close }] = useDisclosure(false);
    const [testEmail, setTestEmail] = useState("");
    const [sending, setSending] = useState(false);

    const handleSendTest = async () => {
        if (!testEmail || !testEmail.includes("@")) {
            notifications.show({
                title: "Error",
                message: "Please enter a valid email address",
                color: "red",
            });
            return;
        }

        setSending(true);
        try {
            const res: any = await sendTestCampaign({
                title,
                body,
                target_email: testEmail,
                image_url: image || undefined,
                name: "test_adding"
            });

            if (res.success) {
                notifications.show({
                    title: "Success",
                    message: "Test notification sent!",
                    color: "green",
                });
                close();
            } else {
                throw new Error(res.message || "Failed to send");
            }
        } catch (e: any) {
            notifications.show({
                title: "Error",
                message: e.message || "Failed to send test notification",
                color: "red",
            });
        } finally {
            setSending(false);
        }
    };

    return (
        <Card withBorder radius="md" p="md" style={{ height: "100%", display: "flex", flexDirection: "column" }}>
            <Flex justify="space-between" align="center" mb="md">
                <Text fw={500}>Device preview</Text>
            </Flex>

            <Text size="sm" c="dimmed" mb="lg">
                This preview provides a general idea of how your message will appear on a mobile device.
            </Text>

            <Button
                variant="light"
                radius="xl"
                leftSection={<IconSend size={16} />}
                mb="lg"
                onClick={open}
            >
                Send test message
            </Button>

            <SegmentedControl
                value={device}
                onChange={(val) => setDevice(val as "android" | "ios")}
                data={[
                    { label: 'Android', value: 'android' },
                    { label: 'iOS', value: 'ios' },
                ]}
                mb="md"
            />

            <Box
                style={{
                    flex: 1,
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    backgroundColor: "#f8f9fa",
                    borderRadius: 16,
                    padding: 20
                }}
            >
                <Box
                    style={{
                        width: 340,
                        background: device === "ios"
                            ? "linear-gradient(180deg, #3a2a3f 0%, #1a1420 100%)"
                            : "linear-gradient(180deg, #c8c8ca 0%, #b9b8b6 100%)",
                        borderRadius: device === "ios" ? 40 : 20,
                        boxShadow: "0 10px 25px rgba(0,0,0,0.1)",
                        overflow: "hidden",
                        border: "1px solid #eee",
                        position: "relative",
                        minHeight: 540
                    }}
                >
                    <Flex justify="space-between" align="center" px="md" py="xs">
                        <Text size="xs" fw={700} c="#fff">9:41</Text>
                        <Group gap={5}>
                            <Box w={10} h={10} bg="white" opacity={0.5} style={{ borderRadius: "50%" }} />
                            <Box w={10} h={10} bg="white" opacity={0.5} style={{ borderRadius: "50%" }} />
                        </Group>
                    </Flex>

                    {device === "android" && (
                        <Text fz={14} fw={600} c="#fff" px="md" pt={14} pb={4} style={{ textShadow: "0 1px 3px rgba(0,0,0,0.35)" }}>
                            Karma Subito
                        </Text>
                    )}

                    <Box p="sm" pt={device === "ios" ? 40 : 6}>
                        <NotificationCard title={title} body={body} image={image} device={device} />
                    </Box>
                </Box>
            </Box>

            <Modal opened={opened} onClose={close} title="Send Test Notification" centered>
                <Stack>
                    <Text size="sm">Enter an email address to send this notification to.</Text>
                    <TextInput
                        placeholder="email@example.com"
                        label="Target Email"
                        value={testEmail}
                        onChange={(e) => setTestEmail(e.target.value)}
                        data-autofocus
                    />
                    <Group justify="flex-end">
                        <Button variant="subtle" onClick={close}>Cancel</Button>
                        <Button onClick={handleSendTest} loading={sending}>Send</Button>
                    </Group>
                </Stack>
            </Modal>

        </Card>
    );
};

export default DevicePreview;
