import {
  deleteCampaignGroup,
  type CampaignGroup,
} from "@/lib/features/notifications/action";
import { Alert, Button, Group, Modal, Radio, Stack, Text } from "@mantine/core";
import { IconAlertTriangle, IconTrash } from "@tabler/icons-react";
import { useEffect, useState } from "react";
import { runGroupAction } from "./shared";

type DeleteMode = "keep" | "delete";

const DeleteCampaignModal: React.FC<{
  group: CampaignGroup | null;
  onClose: () => void;
  onDeleted: () => void;
}> = ({ group, onClose, onDeleted }) => {
  const [mode, setMode] = useState<DeleteMode>("keep");
  const [deleting, setDeleting] = useState(false);

  useEffect(() => {
    if (group) setMode("keep");
  }, [group]);

  const notificationCount = group?.progress.total ?? 0;
  const activeCount =
    (group?.progress.active ?? 0) + (group?.progress.upcoming ?? 0);
  const plural = notificationCount === 1 ? "" : "s";

  const handleDelete = async () => {
    if (!group) return;
    setDeleting(true);
    const withNotifications = mode === "delete";
    const ok = await runGroupAction(
      () => deleteCampaignGroup(group.id, { withNotifications }),
      withNotifications
        ? `Campaign and ${notificationCount} notification${plural} deleted`
        : "Campaign deleted, notifications kept",
    );
    setDeleting(false);
    if (!ok) return;
    onClose();
    onDeleted();
  };

  return (
    <Modal
      opened={!!group}
      onClose={onClose}
      centered
      size="md"
      title={
        <Group gap="xs">
          <IconTrash size={18} color="var(--mantine-color-red-6)" />
          <Text fw={700}>Delete campaign</Text>
        </Group>
      }
    >
      <Stack gap="md">
        <Text size="sm">
          Delete <b>{group?.name}</b>? It contains {notificationCount}{" "}
          notification{plural}.
        </Text>

        {notificationCount > 0 && (
          <Radio.Group
            label="What should happen to its notifications?"
            value={mode}
            onChange={(value) => setMode(value as DeleteMode)}
          >
            <Stack gap="sm" mt="xs">
              <Radio
                value="keep"
                label="Keep the notifications"
                description="They stay as standalone notifications with their current status. Any paused by this campaign stay paused."
              />
              <Radio
                value="delete"
                color="red"
                label={`Delete all ${notificationCount} notification${plural} too`}
                description="They move to Deleted Campaigns and anything scheduled will not send. They can be restored from there."
              />
            </Stack>
          </Radio.Group>
        )}

        {mode === "delete" && activeCount > 0 && (
          <Alert
            color="red"
            variant="light"
            icon={<IconAlertTriangle size={16} />}
          >
            {activeCount} notification{activeCount === 1 ? " is" : "s are"}{" "}
            still sending or scheduled. Scheduled ones will not send; sending
            ones stop after the current batch.
          </Alert>
        )}

        <Group justify="flex-end">
          <Button variant="default" onClick={onClose} disabled={deleting}>
            Cancel
          </Button>
          <Button
            color="red"
            leftSection={<IconTrash size={16} />}
            loading={deleting}
            onClick={handleDelete}
          >
            {mode === "delete"
              ? "Delete campaign and notifications"
              : "Delete campaign"}
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
};

export default DeleteCampaignModal;
