import { ActionIcon, Avatar, Badge, Box, Button, Card, Flex, Group, Image, Modal, Stack, Text, TextInput, SegmentedControl } from "@mantine/core";
import { IconBrandAndroid, IconBrandApple, 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";

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

const DevicePreview: React.FC<DevicePreviewProps> = ({ title, body, image, appName = "Karma Group" }) => {
    const [device, setDevice] = useState<"android" | "ios">("android");
    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" // Hardcoded as per requirement
            });

            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
                }}
            >
                {/* Phone Frame */}
                <Box
                    style={{
                        width: 300,
                        backgroundColor: "#fff",
                        borderRadius: device === "ios" ? 40 : 20,
                        boxShadow: "0 10px 25px rgba(0,0,0,0.1)",
                        overflow: "hidden",
                        border: "1px solid #eee",
                        position: "relative",
                        minHeight: 500
                    }}
                >
                    {/* Status Bar Mockup */}
                    <Flex justify="space-between" align="center" px="md" py="xs" bg={device === "android" ? "white" : "transparent"}>
                        <Text size="xs" fw={700} c="dimmed">9:41</Text>
                        <Group gap={5}>
                            <Box w={10} h={10} bg="gray" style={{ borderRadius: "50%" }} />
                            <Box w={10} h={10} bg="gray" style={{ borderRadius: "50%" }} />
                        </Group>
                    </Flex>

                    {/* Notification Card */}
                    <Box p="sm" pt={device === "ios" ? 40 : 10}>
                        <Card
                            radius="md"
                            p="sm"
                            withBorder={device === "ios"}
                            shadow="sm"
                            bg="white"
                        >
                            <Group align="start" wrap="nowrap">
                                {device === "android" ? (
                                    <Avatar size="sm" radius="xl" src="/favicon.ico" color="blue">K</Avatar>
                                ) : (
                                    <Avatar size="md" radius={8} src="/favicon.ico" color="blue">K</Avatar>
                                )}

                                <div style={{ flex: 1 }}>
                                    <Group justify="space-between" mb={2}>
                                        <Text size="xs" fw={500} c="dimmed">{appName}</Text>
                                        <Text size="xs" c="dimmed">now</Text>
                                    </Group>
                                    <Text size="sm" fw={700} lh={1.2} mb={2}>{title || "Notification Title"}</Text>
                                    <Text size="xs" c="dimmed" lh={1.4}>{body || "Notification body text goes here..."}</Text>

                                    {image && (
                                        <Image
                                            src={image}
                                            mt="xs"
                                            radius="sm"
                                            h={150}
                                            w="100%"
                                            fit="cover"
                                            fallbackSrc="https://placehold.co/600x400?text=Image"
                                        />
                                    )}
                                </div>
                            </Group>
                            {device === "android" && (
                                <Group mt="xs" gap="xl">
                                    {/* Android Actions Mockup */}
                                </Group>
                            )}
                        </Card>
                    </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;
