import {
    listDefaultEmails,
    addDefaultEmail,
    deleteDefaultEmail,
} from "@/lib/features/notifications/action";
import {
    ActionIcon,
    Box,
    Button,
    Flex,
    Group,
    Modal,
    Stack,
    Table,
    Text,
    TextInput,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import {
    IconMail,
    IconPlus,
    IconTrash,
    IconExclamationCircleFilled,
} from "@tabler/icons-react";
import { useEffect, useState } from "react";
import ConfirmAlert from "@/components/blocks/ConfirmAlert/confirmAlert";

const DefaultEmailTab = () => {
    const [items, setItems] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    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(() => {
        fetchEmails();
    }, []);

    const fetchEmails = async () => {
        setLoading(true);
        try {
            const res = await listDefaultEmails();
            if (res.success) {
                setItems(res.data || []);
            }
        } catch (e) {
            console.error("Failed to fetch default 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 default list");
            return false;
        }
        setEmailError("");
        return true;
    };

    const handleAdd = async () => {
        if (!validateEmail(newEmail)) return;
        if (items.length >= 2) {
            notifications.show({ title: "Limit Reached", message: "Maximum 2 default emails allowed", color: "red" });
            return;
        }

        setSubmitting(true);
        try {
            const res = await addDefaultEmail(newEmail.trim());
            if (res.success) {
                notifications.show({ title: "Success", message: "Default email added", color: "green" });
                setNewEmail("");
                setEmailError("");
                closeAddModal();
                fetchEmails();
            } else {
                notifications.show({ title: "Error", message: res.message || "Failed to add email", 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 deleteDefaultEmail(pendingDelete.id);
            if (res.success) {
                notifications.show({ title: "Success", message: "Email removed", color: "green" });
                fetchEmails();
            } 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);
        }
    };

    return (
        <Stack gap="md">
            <Flex justify="space-between" align="center">
                <Box>
                    <Text fz={20} fw={500}>Default Emails</Text>
                    <Text fz="sm" c="dimmed">These emails are included in every campaign batch when "Apply Default Email" is checked. Maximum 2 emails.</Text>
                </Box>
                <Button
                    leftSection={<IconPlus size={16} />}
                    onClick={openAddModal}
                    disabled={items.length >= 2}
                >
                    Add Default Email
                </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></Table.Th>
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    {items.length === 0 ? (
                        <Table.Tr>
                            <Table.Td colSpan={4} style={{ textAlign: "center", padding: "40px" }}>
                                <IconMail size={48} color="var(--mantine-color-gray-3)" />
                                <Text c="dimmed" mt="sm">No default emails added yet</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",
                                    })}
                                </Table.Td>
                                <Table.Td c="dimmed" fz="sm">
                                    {item.updated_by || "—"}
                                </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>

            <Modal
                opened={addModalOpened}
                onClose={() => {
                    closeAddModal();
                    setEmailError("");
                    setNewEmail("");
                }}
                title="Add Default Email"
                centered
            >
                <Stack>
                    <TextInput
                        label="Email Address"
                        placeholder="example@company.com"
                        value={newEmail}
                        onChange={(e) => {
                            setNewEmail(e.currentTarget.value);
                            setEmailError("");
                        }}
                        error={emailError}
                        required
                    />
                    <Button onClick={handleAdd} loading={submitting}>
                        Add Email
                    </Button>
                </Stack>
            </Modal>

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

export default DefaultEmailTab;
