import {
  listCampaigns,
  updateCampaignGroup,
  type CampaignGroup,
} from "@/lib/features/notifications/action";
import {
  Button,
  Group,
  Modal,
  MultiSelect,
  Stack,
  TextInput,
  Textarea,
} from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
import { useEffect, useState } from "react";
import { runGroupAction } from "./shared";
import CampaignTagsInput from "./CampaignTagsInput";
import type { CampaignTag } from "@/lib/features/notifications/action";

const ParentCampaignFormModal: React.FC<{
  opened: boolean;
  onClose: () => void;
  onSaved: (group: CampaignGroup) => void;
  group: CampaignGroup;
}> = ({ opened, onClose, onSaved, group }) => {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [tags, setTags] = useState<CampaignTag[]>([]);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!opened) return;
    setName(group.name);
    setDescription(group.description ?? "");
    setTags(group.tags ?? []);
  }, [opened, group]);

  const handleSave = async () => {
    if (!name.trim()) return;
    setSaving(true);
    const saved = await runGroupAction(
      () =>
        updateCampaignGroup(group.id, {
          name: name.trim(),
          description: description.trim() || null,
          tagIds: tags.map((t) => t.id),
        }),
      "Campaign updated",
    );
    setSaving(false);
    if (saved) {
      onSaved(saved);
      onClose();
    }
  };

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title="Edit campaign"
      centered
      size="lg"
    >
      <Stack>
        <TextInput
          label="Title"
          required
          value={name}
          onChange={(e) => setName(e.currentTarget.value)}
          error={name.length > 0 && !name.trim() ? "Title is required" : null}
        />
        <Textarea
          label="Description"
          autosize
          minRows={2}
          value={description}
          onChange={(e) => setDescription(e.currentTarget.value)}
        />
        <CampaignTagsInput value={tags} onChange={setTags} />
        <Group justify="flex-end">
          <Button variant="default" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handleSave} loading={saving} disabled={!name.trim()}>
            Save
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
};

/** Searchable multi-select of campaigns that do not belong to any parent yet. */
export const UnassignedCampaignPicker: React.FC<{
  value: string[];
  onChange: (ids: string[]) => void;
  label?: string;
}> = ({ value, onChange, label = "Add existing notifications (optional)" }) => {
  const [search, setSearch] = useState("");
  const [debounced] = useDebouncedValue(search, 300);
  const [options, setOptions] = useState<{ value: string; label: string }[]>(
    [],
  );
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    listCampaigns(0, 50, { parentId: "none", search: debounced || undefined })
      .then((res: any) => {
        if (cancelled || !res.success) return;
        const items = Array.isArray(res.data)
          ? res.data
          : (res.data?.items ?? []);
        setOptions((prev) => {
          // Keep already-selected options so their labels survive a new search.
          const selected = prev.filter((o) => value.includes(o.value));
          const fresh = items.map((c: any) => ({
            value: c.id,
            label: `${c.name || c.title || "Untitled"} · ${c.status}`,
          }));
          const seen = new Set(fresh.map((o: { value: string }) => o.value));
          return [...selected.filter((o) => !seen.has(o.value)), ...fresh];
        });
      })
      .finally(() => !cancelled && setLoading(false));
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debounced]);

  return (
    <MultiSelect
      label={label}
      placeholder="Search notifications without a parent"
      data={options}
      value={value}
      onChange={onChange}
      searchable
      searchValue={search}
      onSearchChange={setSearch}
      filter={({ options }) => options}
      nothingFoundMessage={
        loading ? "Loading…" : "No unassigned notifications found"
      }
      clearable
      maxDropdownHeight={260}
    />
  );
};

export default ParentCampaignFormModal;
