import ConfirmAlert from "@/components/blocks/ConfirmAlert/confirmAlert";
import { searchMemberAccountTypes } from "@/lib/features/members/query";
import type { CoreMemberAccountType } from "@/lib/features/members/types";
import {
  createCampaignGroup,
  type CampaignDraftPayload,
} from "@/lib/features/notifications/action";
import {
  ActionIcon,
  Alert,
  Badge,
  Button,
  Card,
  Group,
  Image,
  Modal,
  Stack,
  Text,
  TextInput,
  Textarea,
  Title,
  Tooltip,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import {
  IconAlertTriangle,
  IconArrowLeft,
  IconCalendarEvent,
  IconCopy,
  IconEdit,
  IconInbox,
  IconExclamationCircleFilled,
  IconPlus,
  IconSend,
  IconTrash,
  IconUsers,
} from "@tabler/icons-react";
import { useEffect, useMemo, useState } from "react";
import { useBlocker, useNavigate } from "react-router";
import AddNotification from "../../(widgets)/addNotification";
import type { Campaign } from "../../(widgets)/CampaignsTable/types";
import { UnassignedCampaignPicker } from "../../(widgets)/ParentCampaigns/ParentCampaignFormModal";
import { formatDateTime } from "../../(widgets)/ParentCampaigns/shared";
import { PromoThemeShell } from "@/routes/promo-code-campaigns/_components/PromoThemeShell";
import CampaignTagsInput from "../../(widgets)/ParentCampaigns/CampaignTagsInput";
import type { CampaignTag } from "@/lib/features/notifications/action";

type Draft = CampaignDraftPayload & { key: string };

const newKey = () => Math.random().toString(36).slice(2);

/** Short "who receives this" line from the composer's target criteria. */
function audienceSummary(t: any): string {
  if (!t) return "All members";
  const parts: string[] = [];
  const members = (t.members ?? []).filter(Boolean);
  if (members.length)
    parts.push(
      `${members.length} listed member${members.length === 1 ? "" : "s"}`,
    );
  if (t.country?.length)
    parts.push(
      t.country.length <= 3
        ? t.country.join(", ")
        : `${t.country.length} countries`,
    );
  if (t.city?.length)
    parts.push(`${t.city.length} cit${t.city.length === 1 ? "y" : "ies"}`);
  if (t.membershipType?.length)
    parts.push(
      `${t.membershipType.length} membership type${t.membershipType.length === 1 ? "" : "s"}`,
    );
  if (t.userSegment?.length && t.userSegment.length < 3)
    parts.push(t.userSegment.join(" / "));
  if (t.excludeEmails?.length) parts.push(`${t.excludeEmails.length} excluded`);
  return parts.length ? parts.join(" · ") : "All members";
}

const scheduleTime = (d: Draft) =>
  d.sendNow || !d.scheduled_at ? null : new Date(d.scheduled_at).getTime();

/** Build an initialData object the composer can prefill from. */
const toComposerData = (d: Draft): Campaign =>
  ({
    id: d.key,
    name: d.name,
    title: d.title,
    body: d.body,
    image_url: d.image_url ?? null,
    target_criteria: d.target_criteria,
    additional_data: d.additional_data,
    status: "DRAFT",
  }) as Campaign;

const CampaignBuilderClient: React.FC = () => {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [tags, setTags] = useState<CampaignTag[]>([]);
  const [drafts, setDrafts] = useState<Draft[]>([]);
  const [attachIds, setAttachIds] = useState<string[]>([]);
  const [accountTypes, setAccountTypes] = useState<CoreMemberAccountType[]>([]);

  const [composerOpened, { open: openComposer, close: closeComposer }] =
    useDisclosure(false);
  const [editingKey, setEditingKey] = useState<string | null>(null);
  const [composerData, setComposerData] = useState<Campaign | null>(null);
  const [reviewOpened, { open: openReview, close: closeReview }] =
    useDisclosure(false);
  const [saving, setSaving] = useState(false);
  const [done, setDone] = useState(false);
  const [triedSubmit, setTriedSubmit] = useState(false);

  useEffect(() => {
    searchMemberAccountTypes(1, 100)
      .then((res) => {
        if (res.success)
          setAccountTypes(
            (res.data?.account_types ?? []).filter(
              (t: any) => t.name !== "Karma Lite",
            ),
          );
      })
      .catch(() => {});
  }, []);

  // Nothing is saved until Confirm, so warn before leaving with unsaved work.
  const dirty =
    !done && (drafts.length > 0 || name.trim() !== "" || attachIds.length > 0);
  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      dirty && currentLocation.pathname !== nextLocation.pathname,
  );
  useEffect(() => {
    if (!dirty) return;
    const onUnload = (e: BeforeUnloadEvent) => e.preventDefault();
    window.addEventListener("beforeunload", onUnload);
    return () => window.removeEventListener("beforeunload", onUnload);
  }, [dirty]);

  const ordered = useMemo(
    () =>
      [...drafts].sort(
        (a, b) =>
          (scheduleTime(a) ?? -Infinity) - (scheduleTime(b) ?? -Infinity),
      ),
    [drafts],
  );
  const sendNowCount = drafts.filter((d) => d.sendNow).length;
  const now = Date.now();
  const pastScheduled = drafts.filter((d) => {
    const t = scheduleTime(d);
    return t !== null && t <= now;
  });

  const openAdd = () => {
    setEditingKey(null);
    setComposerData(null);
    openComposer();
  };
  const openEdit = (d: Draft) => {
    setEditingKey(d.key);
    setComposerData(toComposerData(d));
    openComposer();
  };
  const duplicate = (d: Draft) => {
    setEditingKey(null);
    setComposerData(toComposerData(d));
    openComposer();
  };

  const handleDraft = (payload: CampaignDraftPayload) => {
    setDrafts((prev) =>
      editingKey
        ? prev.map((d) =>
            d.key === editingKey ? { ...payload, key: editingKey } : d,
          )
        : [...prev, { ...payload, key: newKey() }],
    );
    setEditingKey(null);
  };

  const canReview =
    name.trim() !== "" && (drafts.length > 0 || attachIds.length > 0);

  const handleConfirm = async () => {
    setSaving(true);
    try {
      const res = await createCampaignGroup({
        name: name.trim(),
        description: description.trim() || undefined,
        campaignIds: attachIds,
        campaigns: ordered.map(({ key: _key, ...d }) => d),
        tagIds: tags.map((t) => t.id),
      });
      if (!res.success) {
        notifications.show({
          title: "Error",
          message: res.message || "Failed to create campaign",
          color: "red",
        });
        return;
      }
      const failed = res.data.failed_to_queue?.length ?? 0;
      notifications.show({
        title: failed ? "Created with warnings" : "Campaign created",
        message: failed
          ? `${failed} "send now" notification(s) could not be queued. Use Send Now on the campaign page.`
          : `${drafts.length} notification${drafts.length === 1 ? "" : "s"} created${sendNowCount ? `, ${sendNowCount} sending now` : ""}.`,
        color: failed ? "orange" : "green",
      });
      setDone(true);
      closeReview();
      // Let `done` flush so the leave-guard doesn't block this navigation.
      setTimeout(
        () =>
          navigate(`/admin/notifications/groups/${res.data.id}`, {
            replace: true,
          }),
        0,
      );
    } catch (e: any) {
      notifications.show({
        title: "Error",
        message: e?.message || "Failed to create campaign",
        color: "red",
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <PromoThemeShell>
      <Stack px="xl" py="xl" gap="lg" maw={1100}>
        <Group justify="space-between">
          <Group gap="xs">
            <ActionIcon
              variant="subtle"
              onClick={() => navigate("/admin/notifications")}
              aria-label="Back"
            >
              <IconArrowLeft size={18} />
            </ActionIcon>
            <Title order={3}>New Campaign</Title>
          </Group>
          <Group>
            <Button
              variant="default"
              onClick={() => navigate("/admin/notifications")}
            >
              Cancel
            </Button>
            <Tooltip
              label="Add a title and at least one notification"
              disabled={canReview}
            >
              <Button
                leftSection={<IconSend size={16} />}
                disabled={!canReview}
                onClick={() => {
                  setTriedSubmit(true);
                  if (canReview) openReview();
                }}
              >
                Review & confirm
              </Button>
            </Tooltip>
          </Group>
        </Group>

        <Alert
          variant="light"
          color="blue"
          icon={<IconExclamationCircleFilled size={18} />}
        >
          Nothing is saved or sent until you confirm. Notifications set to{" "}
          <b>Send now</b> stay editable here and only go out after the final
          confirmation.
        </Alert>

        <Card withBorder radius="lg" p="lg">
          <Stack>
            <TextInput
              label="Campaign title"
              placeholder="e.g. Karma Royal Palms — Summer 2026"
              required
              value={name}
              onChange={(e) => setName(e.currentTarget.value)}
              error={triedSubmit && !name.trim() ? "Title is required" : null}
            />
            <Textarea
              label="Description"
              placeholder="What this campaign is for"
              autosize
              minRows={2}
              value={description}
              onChange={(e) => setDescription(e.currentTarget.value)}
            />
            <CampaignTagsInput value={tags} onChange={setTags} />
          </Stack>
        </Card>

        <Group justify="space-between">
          <Group gap="xs">
            <Text fw={700} size="md">
              Notifications
            </Text>
            <Badge variant="light" size="md" radius="sm">
              {drafts.length}
            </Badge>
          </Group>
          <Button leftSection={<IconPlus size={16} />} onClick={openAdd}>
            Add notification
          </Button>
        </Group>

        {drafts.length === 0 ? (
          <Card withBorder radius="lg" p="xl">
            <Stack align="center" gap="xs">
              <IconInbox size={38} stroke={1.2} opacity={0.3} />
              <Text c="dimmed" size="sm">
                No notifications yet. Each one has its own content, audience and
                schedule.
              </Text>
              <Button
                variant="light"
                leftSection={<IconPlus size={16} />}
                onClick={openAdd}
              >
                Add the first notification
              </Button>
            </Stack>
          </Card>
        ) : (
          <Stack gap="sm">
            {ordered.map((d, i) => (
              <Card key={d.key} withBorder radius="lg" p="md">
                <Group justify="space-between" wrap="nowrap" align="flex-start">
                  <Group
                    wrap="nowrap"
                    align="flex-start"
                    style={{ minWidth: 0 }}
                  >
                    <Badge variant="light" circle size="lg" color="indigo">
                      {i + 1}
                    </Badge>
                    {d.image_url && (
                      <Image
                        src={d.image_url}
                        w={56}
                        h={56}
                        radius="md"
                        fit="cover"
                      />
                    )}
                    <Stack gap={2} style={{ minWidth: 0 }}>
                      <Text fw={600} lineClamp={1}>
                        {d.name || d.title || "Untitled"}
                      </Text>
                      <Text size="sm" lineClamp={1}>
                        {d.title?.trim() && <b>{d.title} — </b>}
                        {d.body}
                      </Text>
                      <Group gap="md" mt={4}>
                        <Group gap={4}>
                          {d.sendNow ? (
                            <IconSend
                              size={14}
                              color="var(--mantine-color-orange-6)"
                            />
                          ) : (
                            <IconCalendarEvent size={14} />
                          )}
                          <Text
                            size="xs"
                            c={d.sendNow ? "orange.7" : undefined}
                            fw={500}
                          >
                            {d.sendNow
                              ? "Send now (on confirm)"
                              : d.scheduled_at
                                ? formatDateTime(d.scheduled_at)
                                : "Not scheduled (saved as draft)"}
                          </Text>
                        </Group>
                        <Group gap={4}>
                          <IconUsers size={14} />
                          <Text size="xs">
                            {audienceSummary(d.target_criteria)}
                          </Text>
                        </Group>
                      </Group>
                    </Stack>
                  </Group>
                  <Group gap={4} wrap="nowrap">
                    <Tooltip label="Edit">
                      <ActionIcon variant="subtle" onClick={() => openEdit(d)}>
                        <IconEdit size={16} />
                      </ActionIcon>
                    </Tooltip>
                    <Tooltip label="Duplicate">
                      <ActionIcon
                        variant="subtle"
                        color="gray"
                        onClick={() => duplicate(d)}
                      >
                        <IconCopy size={16} />
                      </ActionIcon>
                    </Tooltip>
                    <Tooltip label="Remove">
                      <ActionIcon
                        variant="subtle"
                        color="red"
                        onClick={() =>
                          setDrafts((p) => p.filter((x) => x.key !== d.key))
                        }
                      >
                        <IconTrash size={16} />
                      </ActionIcon>
                    </Tooltip>
                  </Group>
                </Group>
              </Card>
            ))}
          </Stack>
        )}

        <Card withBorder radius="lg" p="lg">
          <UnassignedCampaignPicker
            value={attachIds}
            onChange={setAttachIds}
            label="Also include existing notifications (optional)"
          />
        </Card>

        <AddNotification
          accountTypes={accountTypes}
          opened={composerOpened}
          onClose={closeComposer}
          initialData={composerData}
          onDraftSubmit={handleDraft}
          onSuccess={closeComposer}
        />

        <Modal
          opened={reviewOpened}
          onClose={closeReview}
          title={<Text fw={600}>Confirm campaign</Text>}
          centered
          size="lg"
        >
          <Stack>
            <div>
              <Text fw={600}>{name}</Text>
              {description && (
                <Text size="sm" c="dimmed">
                  {description}
                </Text>
              )}
            </div>
            <Stack gap={6}>
              {ordered.map((d, i) => (
                <Group key={d.key} justify="space-between" wrap="nowrap">
                  <Text size="sm" lineClamp={1}>
                    {i + 1}. {d.name || d.title}
                  </Text>
                  <Badge
                    variant="light"
                    color={
                      d.sendNow ? "orange" : d.scheduled_at ? "blue" : "gray"
                    }
                  >
                    {d.sendNow
                      ? "Send now"
                      : d.scheduled_at
                        ? formatDateTime(d.scheduled_at)
                        : "Draft"}
                  </Badge>
                </Group>
              ))}
              {attachIds.length > 0 && (
                <Text size="sm" c="dimmed">
                  + {attachIds.length} existing notification
                  {attachIds.length === 1 ? "" : "s"} attached
                </Text>
              )}
            </Stack>
            {sendNowCount > 0 && (
              <Alert
                color="orange"
                variant="light"
                icon={<IconSend size={16} />}
              >
                {sendNowCount} notification{sendNowCount === 1 ? "" : "s"} will
                start sending immediately after you confirm.
              </Alert>
            )}
            {pastScheduled.length > 0 && (
              <Alert
                color="red"
                variant="light"
                icon={<IconAlertTriangle size={16} />}
              >
                {pastScheduled.length} notification
                {pastScheduled.length === 1 ? " is" : "s are"} scheduled in the
                past and will send immediately. Edit{" "}
                {pastScheduled.length === 1 ? "it" : "them"} first if that is
                not intended.
              </Alert>
            )}
            <Group justify="flex-end">
              <Button variant="default" onClick={closeReview}>
                Back to editing
              </Button>
              <Button onClick={handleConfirm} loading={saving}>
                Confirm & create
              </Button>
            </Group>
          </Stack>
        </Modal>

        <ConfirmAlert
          title="Leave without saving?"
          titleIcon={<IconExclamationCircleFilled color="orange" />}
          message="This campaign and its notifications have not been created yet. Leaving discards them."
          handleConfirm={() => blocker.proceed?.()}
          modalProps={{
            opened: blocker.state === "blocked",
            onClose: () => blocker.reset?.(),
          }}
        />
      </Stack>
    </PromoThemeShell>
  );
};

export default CampaignBuilderClient;
