import {
    addToBlacklist,
    listBlacklist,
    removeFromBlacklist,
    toggleBlacklistEntry,
    type BlacklistEntry,
} from "@/lib/features/event-analytics/query";
import {
    ActionIcon,
    Badge,
    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 {
    IconExclamationCircleFilled,
    IconPlus,
    IconSearch,
    IconTrash,
    IconUserOff,
} from "@tabler/icons-react";
import { useEffect, useState } from "react";
import ConfirmAlert from "@/components/blocks/ConfirmAlert/confirmAlert";

interface BlockedAccountsTabProps {
    canEdit: boolean;
    onChanged: () => void;
}

const BlockedAccountsTab = ({ canEdit, onChanged }: BlockedAccountsTabProps) => {
    const [items, setItems] = useState<BlacklistEntry[]>([]);
    const [total, setTotal] = useState(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 [identifier, setIdentifier] = useState("");
    const [reason, setReason] = useState("");
    const [identifierError, setIdentifierError] = useState("");
    const [submitting, setSubmitting] = useState(false);

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

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

    const fetchData = async () => {
        setLoading(true);
        try {
            const start = (page - 1) * parseInt(pageSize);
            const res = await listBlacklist(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 accounts:", e);
        } finally {
            setLoading(false);
        }
    };

    const handleAdd = async () => {
        const value = identifier.trim();
        if (!value) {
            setIdentifierError("Enter a membership number or email address");
            return;
        }
        setSubmitting(true);
        try {
            const body = value.includes("@")
                ? { email: value, reason: reason.trim() || undefined }
                : { memberNumber: value, reason: reason.trim() || undefined };
            const res = await addToBlacklist(body);
            if (res.success) {
                const added = res.data?.entries?.length ?? 0;
                notifications.show({
                    title: "Account blocked",
                    message:
                        added > 1
                            ? `${added} memberships matched and are now excluded`
                            : "Events from this account are excluded from analytics",
                    color: "green",
                });
                closeAddModal();
                setIdentifier("");
                setReason("");
                setIdentifierError("");
                setPage(1);
                fetchData();
                onChanged();
            } else {
                setIdentifierError(res.message || "Could not block that account");
            }
        } catch (e) {
            setIdentifierError("An unexpected error occurred");
        } finally {
            setSubmitting(false);
        }
    };

    const handleToggle = async (entry: BlacklistEntry) => {
        try {
            const res = await toggleBlacklistEntry(entry.id, !entry.isActive);
            if (res.success) {
                notifications.show({
                    title: "Status updated",
                    message: entry.isActive
                        ? "This account is counted in analytics again"
                        : "Events from this account are excluded again",
                    color: "green",
                });
                fetchData();
                onChanged();
            } 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 handleDelete = (entry: BlacklistEntry) => {
        setPendingDelete(entry);
        openConfirm();
    };

    const confirmDelete = async () => {
        if (!pendingDelete) return;
        try {
            const res = await removeFromBlacklist(pendingDelete.id);
            if (res.success) {
                notifications.show({
                    title: "Account removed",
                    message: "Its events are counted in analytics again",
                    color: "green",
                });
                fetchData();
                onChanged();
            } else {
                notifications.show({ title: "Error", message: "Failed to remove account", color: "red" });
            }
        } catch (e) {
            notifications.show({ title: "Error", message: "An unexpected error occurred", color: "red" });
        } finally {
            closeConfirm();
            setPendingDelete(null);
        }
    };

    const totalPages = Math.max(1, Math.ceil(total / parseInt(pageSize)));

    return (
        <Stack gap="md">
            <Flex justify="space-between" align="center" wrap="wrap" gap="sm">
                <Group gap="xs">
                    <TextInput
                        placeholder="Search by membership number or email..."
                        value={localSearch}
                        onChange={(e) => {
                            setLocalSearch(e.currentTarget.value);
                            setPage(1);
                        }}
                        leftSection={<IconSearch size={18} stroke={1.5} />}
                        size="sm"
                        radius="md"
                        variant="filled"
                        style={{ minWidth: 300 }}
                    />
                </Group>
                {canEdit && (
                    <Button leftSection={<IconPlus size={16} />} onClick={openAddModal}>
                        Block Account
                    </Button>
                )}
            </Flex>

            <Table verticalSpacing="md">
                <Table.Thead>
                    <Table.Tr>
                        <Table.Th>Account</Table.Th>
                        <Table.Th>Reason</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={6} style={{ textAlign: "center", padding: "40px" }}>
                                <IconUserOff size={48} color="var(--mantine-color-gray-3)" />
                                <Text c="dimmed" mt="sm">
                                    {loading ? "Loading..." : "No blocked accounts. Every event is counted."}
                                </Text>
                            </Table.Td>
                        </Table.Tr>
                    ) : (
                        items.map((item) => (
                            <Table.Tr key={item.id}>
                                <Table.Td>
                                    <Stack gap={2}>
                                        <Text fw={500}>{item.label ?? item.memberNumber}</Text>
                                        {item.email && (
                                            <Text size="xs" c="dimmed">
                                                {item.email}
                                            </Text>
                                        )}
                                        <Badge size="xs" variant="light" color="gray" w="fit-content">
                                            {item.memberNumber}
                                        </Badge>
                                    </Stack>
                                </Table.Td>
                                <Table.Td c="dimmed" fz="sm">
                                    {item.reason || "—"}
                                </Table.Td>
                                <Table.Td c="dimmed">
                                    {new Date(item.createdAt).toLocaleDateString(undefined, {
                                        year: "numeric",
                                        month: "short",
                                        day: "numeric",
                                        hour: "2-digit",
                                        minute: "2-digit",
                                    })}
                                </Table.Td>
                                <Table.Td c="dimmed" fz="sm">
                                    {item.updatedBy || item.createdBy || "—"}
                                </Table.Td>
                                <Table.Td>
                                    <Group gap="xs" wrap="nowrap">
                                        <Switch
                                            checked={item.isActive}
                                            onChange={() => handleToggle(item)}
                                            size="sm"
                                            disabled={!canEdit}
                                        />
                                        <Text size="sm" w={60}>
                                            {item.isActive ? "Active" : "Inactive"}
                                        </Text>
                                    </Group>
                                </Table.Td>
                                <Table.Td>
                                    <Group justify="flex-end">
                                        {canEdit && (
                                            <ActionIcon
                                                color="red"
                                                variant="light"
                                                onClick={() => handleDelete(item)}
                                            >
                                                <IconTrash size={16} />
                                            </ActionIcon>
                                        )}
                                    </Group>
                                </Table.Td>
                            </Table.Tr>
                        ))
                    )}
                </Table.Tbody>
            </Table>

            <Flex justify="space-between" align="center" wrap="wrap" gap="sm">
                <Group gap="xs">
                    <Select
                        style={{ width: 80 }}
                        data={["10", "20", "30", "40", "50"]}
                        value={pageSize}
                        onChange={(val) => {
                            setPageSize(val || "10");
                            setPage(1);
                        }}
                        allowDeselect={false}
                    />
                    <Text size="sm" c="dimmed">
                        Entries per page · Showing {total === 0 ? 0 : (page - 1) * parseInt(pageSize) + 1}
                        –{Math.min(page * parseInt(pageSize), total)} of {total}
                    </Text>
                </Group>
                <Pagination size="sm" value={page} total={totalPages} onChange={setPage} />
            </Flex>

            <Modal
                opened={addModalOpened}
                onClose={() => {
                    closeAddModal();
                    setIdentifierError("");
                    setIdentifier("");
                    setReason("");
                }}
                title="Block Account from Analytics"
                centered
            >
                <Stack>
                    <TextInput
                        label="Membership number or email"
                        placeholder="1278640 or tester@example.com"
                        value={identifier}
                        onChange={(e) => {
                            setIdentifier(e.currentTarget.value);
                            setIdentifierError("");
                        }}
                        error={identifierError}
                        required
                    />
                    <TextInput
                        label="Reason"
                        placeholder="QA account for booking flow"
                        value={reason}
                        onChange={(e) => setReason(e.currentTarget.value)}
                    />
                    <Text size="xs" c="dimmed">
                        Events from blocked accounts are left out of every figure in Event
                        Analytics — the tiles, the funnel, the tables and the export. An email
                        is matched to every membership it belongs to.
                    </Text>
                    <Button onClick={handleAdd} loading={submitting}>
                        Block Account
                    </Button>
                </Stack>
            </Modal>

            <ConfirmAlert
                title="Remove Blocked Account"
                titleIcon={<IconExclamationCircleFilled color="orange" />}
                message={`Are you sure you want to stop excluding ${pendingDelete?.memberNumber || ""}? Its events will be counted in analytics again.`}
                handleConfirm={confirmDelete}
                modalProps={{
                    opened: confirmOpened,
                    onClose: () => {
                        closeConfirm();
                        setPendingDelete(null);
                    },
                }}
            />
        </Stack>
    );
};

export default BlockedAccountsTab;
