import {
    listBlockedEmails,
    createBlockedEmail,
    deleteBlockedEmail,
    toggleBlockedEmail,
} from "@/lib/features/notifications/action";
import {
    ActionIcon,
    Box,
    Button,
    Flex,
    Group,
    Modal,
    Pagination,
    Select,
    Stack,
    Switch,
    Table,
    Text,
    TextInput,
} from "@mantine/core";
import { useDebouncedValue, useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import { IconMailOff, IconPlus, IconSearch, IconTrash, IconExclamationCircleFilled } from "@tabler/icons-react";
import { useEffect, useState } from "react";
import ConfirmAlert from "@/components/blocks/ConfirmAlert/confirmAlert";

interface BlockListTabProps {
    initialData?: { items: any[]; total: number };
    revalidate: () => void;
}

const BlockListTab = ({ initialData, revalidate }: BlockListTabProps) => {
    const [items, setItems] = useState<any[]>(initialData?.items || []);
    const [total, setTotal] = useState(initialData?.total || 0);
    const [loading, setLoading] = useState(false);

    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState("10");
    const [localSearch, setLocalSearch] = useState("");
    const [debouncedSearch] = useDebouncedValue(localSearch, 500);

    const [addModalOpened, { open: openAddModal, close: closeAddModal }] = useDisclosure(false);
    const [newEmail, setNewEmail] = useState("");
    const [emailError, setEmailError] = useState("");
    const [submitting, setSubmitting] = useState(false);

    const [confirmOpened, { open: openConfirm, close: closeConfirm }] = useDisclosure(false);
    const [pendingDelete, setPendingDelete] = useState<{ id: string; email: string } | null>(null);

    useEffect(() => {
        if (initialData) {
            setItems(initialData.items || []);
            setTotal(initialData.total || 0);
        }
    }, [initialData]);

    useEffect(() => {
        fetchData();
    }, [page, pageSize, debouncedSearch]);

    const fetchData = async () => {
        setLoading(true);
        try {
            const start = (page - 1) * parseInt(pageSize);
            const res = await listBlockedEmails(start, parseInt(pageSize), debouncedSearch || undefined);
            if (res.success) {
                setItems(res.data.items || []);
                setTotal(res.data.total || 0);
            }
        } catch (e) {
            console.error("Failed to fetch blocked emails:", e);
        } finally {
            setLoading(false);
        }
    };

    const validateEmail = (email: string): boolean => {
        const normalized = email.trim().toLowerCase();
        if (!normalized) {
            setEmailError("Email is required");
            return false;
        }
        const emailRegex = /.+@.+/;
        if (!emailRegex.test(normalized)) {
            setEmailError("Please enter a valid email address");
            return false;
        }
        const isDuplicate = items.some(item => item.email.toLowerCase() === normalized);
        if (isDuplicate) {
            setEmailError("This email already exists in the block list");
            return false;
        }
        setEmailError("");
        return true;
    };

    const handleAdd = async () => {
        if (!validateEmail(newEmail)) return;
        setSubmitting(true);
        try {
            const res = await createBlockedEmail(newEmail);
            if (res.success) {
                notifications.show({ title: "Success", message: "Email added to block list", color: "green" });
                setNewEmail("");
                setEmailError("");
                closeAddModal();
                fetchData();
            } else {
                notifications.show({ title: "Error", message: res.message || "Failed to add email. It may already exist in the block list.", color: "red" });
            }
        } catch (e) {
            notifications.show({ title: "Error", message: "An unexpected error occurred", color: "red" });
        } finally {
            setSubmitting(false);
        }
    };

    const handleDelete = (id: string, email: string) => {
        setPendingDelete({ id, email });
        openConfirm();
    };

    const confirmDelete = async () => {
        if (!pendingDelete) return;
        try {
            const res = await deleteBlockedEmail(pendingDelete.id);
            if (res.success) {
                notifications.show({ title: "Success", message: "Email removed from block list", color: "green" });
                fetchData();
            } else {
                notifications.show({ title: "Error", message: "Failed to remove email", color: "red" });
            }
        } catch (e) {
            notifications.show({ title: "Error", message: "An unexpected error occurred", color: "red" });
        } finally {
            closeConfirm();
            setPendingDelete(null);
        }
    };

    const handleToggle = async (id: string, currentActive: boolean) => {
        try {
            const res = await toggleBlockedEmail(id, !currentActive);
            if (res.success) {
                notifications.show({
                    title: "Success",
                    message: `Email ${!currentActive ? "activated" : "deactivated"}`,
                    color: "green",
                });
                fetchData();
            } else {
                notifications.show({ title: "Error", message: "Failed to update status", color: "red" });
            }
        } catch (e) {
            notifications.show({ title: "Error", message: "An unexpected error occurred", color: "red" });
        }
    };

    const handleSearch = () => {
        setPage(1);
        fetchData();
    };

    return (
        <Stack gap="md">
            <Flex justify="space-between" align="center">
                <Group gap="xs">
                    <TextInput
                        placeholder="Search blocked emails..."
                        value={localSearch}
                        onChange={(e) => {
                            setLocalSearch(e.currentTarget.value);
                            setPage(1);
                        }}
                        onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
                        leftSection={<IconSearch size={18} stroke={1.5} />}
                        size="sm"
                        radius="md"
                        variant="filled"
                        style={{ minWidth: 300 }}
                    />
                    <Button variant="light" size="sm" onClick={handleSearch}>
                        Search
                    </Button>
                </Group>
                <Button leftSection={<IconPlus size={16} />} onClick={openAddModal}>
                    Add Email to Block List
                </Button>
            </Flex>

            <Table verticalSpacing="md">
                <Table.Thead>
                    <Table.Tr>
                        <Table.Th>Email Address</Table.Th>
                        <Table.Th>Date Added</Table.Th>
                        <Table.Th>Updated By</Table.Th>
                        <Table.Th w={150}>Status</Table.Th>
                        <Table.Th></Table.Th>
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    {items.length === 0 ? (
                        <Table.Tr>
                            <Table.Td colSpan={5} style={{ textAlign: "center", padding: "40px" }}>
                                <IconMailOff size={48} color="var(--mantine-color-gray-3)" />
                                <Text c="dimmed" mt="sm">No emails found in the block list</Text>
                            </Table.Td>
                        </Table.Tr>
                    ) : (
                        items.map((item) => (
                            <Table.Tr key={item.id}>
                                <Table.Td fw={500}>{item.email}</Table.Td>
                                <Table.Td c="dimmed">
                                    {new Date(item.created_at).toLocaleDateString(undefined, {
                                        year: "numeric",
                                        month: "short",
                                        day: "numeric",
                                        hour: "2-digit",
                                        minute: "2-digit",
                                    })}
                                </Table.Td>
                                <Table.Td c="dimmed" fz="sm">
                                    {item.updated_by || "—"}
                                </Table.Td>
                                <Table.Td>
                                    <Group gap="xs" wrap="nowrap">
                                        <Switch
                                            checked={item.is_active ?? true}
                                            onChange={() => handleToggle(item.id, item.is_active ?? true)}
                                            size="sm"
                                        />
                                        <Text size="sm" w={60}>
                                            {item.is_active ?? true ? "Active" : "Inactive"}
                                        </Text>
                                    </Group>
                                </Table.Td>
                                <Table.Td>
                                    <Group justify="flex-end">
                                        <ActionIcon
                                            color="red"
                                            variant="light"
                                            onClick={() => handleDelete(item.id, item.email)}
                                        >
                                            <IconTrash size={16} />
                                        </ActionIcon>
                                    </Group>
                                </Table.Td>
                            </Table.Tr>
                        ))
                    )}
                </Table.Tbody>
            </Table>

            <Flex justify="space-between" align="center">
                <Group gap="xs">
                    <Select
                        style={{ width: 80 }}
                        data={["10", "20", "30", "40", "50"]}
                        value={pageSize}
                        onChange={(val) => {
                            setPageSize(val || "10");
                            setPage(1);
                        }}
                    />
                    <Text size="sm" c="dimmed">Entries per page</Text>
                </Group>
                <Pagination
                    total={Math.max(1, Math.ceil(total / parseInt(pageSize)))}
                    value={page}
                    onChange={setPage}
                />
            </Flex>

            <Modal
                opened={addModalOpened}
                onClose={() => {
                    closeAddModal();
                    setEmailError("");
                    setNewEmail("");
                }}
                title="Add Email to Block List"
                centered
            >
                <Stack>
                    <TextInput
                        label="Email Address"
                        placeholder="example@email.com"
                        value={newEmail}
                        onChange={(e) => {
                            setNewEmail(e.currentTarget.value);
                            setEmailError("");
                        }}
                        error={emailError}
                        required
                    />
                    <Text size="xs" c="dimmed">
                        Emails in this list will be filtered out when "Apply Block List" is checked during campaign creation.
                    </Text>
                    <Button onClick={handleAdd} loading={submitting}>
                        Add to Block List
                    </Button>
                </Stack>
            </Modal>

            <ConfirmAlert
                title="Remove Email"
                titleIcon={<IconExclamationCircleFilled color="orange" />}
                message={`Are you sure you want to remove ${pendingDelete?.email || ""} from the block list?`}
                handleConfirm={confirmDelete}
                modalProps={{
                    opened: confirmOpened,
                    onClose: () => {
                        closeConfirm();
                        setPendingDelete(null);
                    },
                }}
            />
        </Stack>
    );
};

export default BlockListTab;
