import type {
  CampaignGroup,
  CampaignGroupStatus,
} from "@/lib/features/notifications/action";
import { Badge, Group, Progress, Text, Tooltip } from "@mantine/core";
import { notifications } from "@mantine/notifications";

export const GROUP_STATUS_META: Record<
  CampaignGroupStatus,
  { label: string; color: string }
> = {
  DRAFT: { label: "Draft", color: "gray" },
  SCHEDULED: { label: "Scheduled", color: "blue" },
  SENDING: { label: "Sending", color: "yellow" },
  ACTIVE: { label: "Active", color: "green" },
  PAUSED: { label: "Paused", color: "orange" },
  COMPLETED: { label: "Completed", color: "teal" },
};

export const GroupStatusBadge: React.FC<{ status: CampaignGroupStatus }> = ({
  status,
}) => {
  const meta = GROUP_STATUS_META[status] ?? { label: status, color: "gray" };
  return (
    <Badge variant="light" color={meta.color} size="sm">
      {meta.label}
    </Badge>
  );
};

export const formatDateTime = (value?: string | null) =>
  value
    ? new Date(value).toLocaleString(undefined, {
        day: "2-digit",
        month: "short",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      })
    : "—";

/** One-line answer to "what happens next" for a parent campaign. */
export const nextStepLabel = (group: CampaignGroup) => {
  if (group.status === "SENDING") return "Sending now";
  if (group.status === "PAUSED") return "Paused";
  if (group.status === "COMPLETED") return "All subcampaigns sent";
  if (group.next_scheduled_at)
    return `Next: ${formatDateTime(group.next_scheduled_at)}`;
  if (group.progress.total === 0) return "No subcampaigns yet";
  return "Nothing scheduled";
};

/** Stacked bar: completed / sending / upcoming / failed subcampaigns. */
export const GroupProgress: React.FC<{
  group: CampaignGroup;
  size?: "sm" | "md" | "lg";
}> = ({ group, size = "md" }) => {
  const { total, completed, active, upcoming, failed } = group.progress;
  const pct = (n: number) => (total ? (n / total) * 100 : 0);
  return (
    <div>
      <Progress.Root size={size}>
        <Tooltip label={`${completed} completed`}>
          <Progress.Section value={pct(completed)} color="teal" />
        </Tooltip>
        <Tooltip label={`${active} sending`}>
          <Progress.Section value={pct(active)} color="yellow" animated />
        </Tooltip>
        <Tooltip label={`${failed} stopped / failed`}>
          <Progress.Section value={pct(failed)} color="red" />
        </Tooltip>
        <Tooltip label={`${upcoming} upcoming`}>
          <Progress.Section value={pct(upcoming)} color="blue.2" />
        </Tooltip>
      </Progress.Root>
      <Group gap="xs" mt={4}>
        <Text size="xs" c="dimmed">
          {completed}/{total} sent
        </Text>
        {active > 0 && (
          <Text size="xs" c="yellow.8">
            · {active} sending
          </Text>
        )}
        {upcoming > 0 && (
          <Text size="xs" c="dimmed">
            · {upcoming} upcoming
          </Text>
        )}
        {failed > 0 && (
          <Text size="xs" c="red">
            · {failed} stopped/failed
          </Text>
        )}
      </Group>
    </div>
  );
};

/** Calls a core action and shows a toast; returns the response data on success. */
export async function runGroupAction<T>(
  action: () => Promise<{ success: boolean; message: string; data: T }>,
  successMessage: string,
): Promise<T | null> {
  try {
    const res = await action();
    if (res.success) {
      notifications.show({
        title: "Success",
        message: successMessage,
        color: "green",
      });
      return res.data;
    }
    notifications.show({
      title: "Error",
      message: res.message || "Action failed",
      color: "red",
    });
  } catch (e: any) {
    notifications.show({
      title: "Error",
      message: e?.message || "Action failed",
      color: "red",
    });
  }
  return null;
}
