<template>
  <div>
    <div class="bg-guild-900 border-b border-guild-700">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="py-6">
          <h1 class="text-display font-bold text-guild-100">Member Management</h1>
          <p class="text-guild-400">
            Manage Ghost Guild members, their contributions, and access levels
          </p>
        </div>
      </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Search and Actions -->
      <div class="mb-6 flex justify-between items-center">
        <div class="flex gap-4 items-center">
          <input
            v-model="searchQuery"
            placeholder="Search members..."
            class="border border-guild-700 bg-guild-900 text-guild-100 placeholder-guild-500 rounded-lg px-4 py-2 w-80 focus:ring-2 focus:ring-candlelight-500 focus:border-transparent"
          />
          <select
            v-model="circleFilter"
            class="border border-guild-700 bg-guild-900 text-guild-100 rounded-lg px-4 py-2 focus:ring-2 focus:ring-candlelight-500 focus:border-transparent"
          >
            <option value="">All Circles</option>
            <option value="community">Community</option>
            <option value="founder">Founder</option>
            <option value="practitioner">Practitioner</option>
          </select>
        </div>
        <div class="flex gap-3">
          <button
            @click="showImportModal = true"
            class="border border-guild-600 text-guild-100 px-4 py-2 rounded-lg hover:bg-guild-800 focus:ring-2 focus:ring-candlelight-500 focus:ring-offset-2"
          >
            Import CSV
          </button>
          <button
            :disabled="selectedMemberIds.length === 0"
            @click="openInviteModal"
            class="border border-guild-600 text-guild-100 px-4 py-2 rounded-lg hover:bg-guild-800 focus:ring-2 focus:ring-candlelight-500 focus:ring-offset-2 disabled:opacity-40 disabled:cursor-not-allowed"
          >
            Send Invites ({{ selectedMemberIds.length }})
          </button>
          <button
            @click="showCreateModal = true"
            class="bg-candlelight-600 text-white px-4 py-2 rounded-lg hover:bg-candlelight-700 focus:ring-2 focus:ring-candlelight-500 focus:ring-offset-2"
          >
            Add Member
          </button>
        </div>
      </div>

      <!-- Members Table -->
      <div class="bg-guild-900 rounded-lg shadow overflow-hidden">
        <div v-if="pending" class="p-8 text-center text-guild-100">
          <div class="inline-flex items-center">
            <div
              class="animate-spin rounded-full h-6 w-6 border-b-2 border-candlelight-500 mr-3"
            ></div>
            Loading members...
          </div>
        </div>

        <div v-else-if="error" class="p-8 text-center text-ember-400">
          Error loading members: {{ error }}
        </div>

        <table v-else class="w-full">
          <thead class="bg-guild-950">
            <tr>
              <th class="px-4 py-3 text-left">
                <UCheckbox
                  :model-value="allVisibleSelected ? true : (someVisibleSelected ? 'indeterminate' : false)"
                  @update:model-value="toggleSelectAll"
                />
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Name
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Email
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Circle
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Contribution
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Invite
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Slack
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Joined
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium text-guild-500 uppercase tracking-wider"
              >
                Actions
              </th>
            </tr>
          </thead>
          <tbody class="bg-guild-900 divide-y divide-guild-700">
            <tr
              v-for="member in filteredMembers"
              :key="member._id"
              class="hover:bg-guild-800"
            >
              <td class="px-4 py-4">
                <UCheckbox
                  :model-value="selectedMemberIds.includes(member._id)"
                  @update:model-value="toggleSelect(member._id)"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-guild-100">
                  {{ member.name }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-guild-400">
                  {{ member.email }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="getCircleClasses(member.circle)"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ member.circle }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-candlelight-900/20 text-candlelight-400"
                >
                  ${{ member.contributionTier }}/month
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="
                    member.inviteEmailSent
                      ? 'bg-candlelight-900/20 text-candlelight-400'
                      : 'bg-guild-800 text-guild-500'
                  "
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ member.inviteEmailSent ? 'Sent' : 'Not sent' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="
                    member.slackInvited
                      ? 'bg-candlelight-900/20 text-candlelight-400'
                      : 'bg-guild-800 text-guild-300'
                  "
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ member.slackInvited ? "Invited" : "Pending" }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-guild-400 text-ui-mono">
                {{ formatDate(member.createdAt) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-guild-400">
                <div class="flex gap-2">
                  <button
                    @click="sendSlackInvite(member)"
                    class="text-candlelight-400 hover:text-candlelight-300"
                  >
                    Slack Invite
                  </button>
                  <button
                    @click="editMember(member)"
                    class="text-candlelight-400 hover:text-candlelight-300"
                  >
                    Edit
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <div
          v-if="!pending && !error && filteredMembers.length === 0"
          class="p-8 text-center text-guild-500"
        >
          No members found matching your criteria
        </div>
      </div>
    </div>

    <!-- Create Member Modal -->
    <div
      v-if="showCreateModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-guild-900 rounded-lg shadow-xl max-w-md w-full mx-4 border border-guild-700">
        <div class="px-6 py-4 border-b border-guild-700">
          <h3 class="text-display-sm font-semibold text-guild-100">Add New Member</h3>
        </div>

        <form @submit.prevent="createMember" class="p-6 space-y-4">
          <div>
            <label class="block text-sm font-medium text-guild-100 mb-1"
              >Name</label
            >
            <input
              v-model="newMember.name"
              placeholder="Full name"
              required
              class="w-full border border-guild-700 bg-guild-800 text-guild-100 placeholder-guild-500 rounded-lg px-3 py-2 focus:ring-2 focus:ring-candlelight-500 focus:border-transparent"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-guild-100 mb-1"
              >Email</label
            >
            <input
              v-model="newMember.email"
              type="email"
              placeholder="email@example.com"
              required
              class="w-full border border-guild-700 bg-guild-800 text-guild-100 placeholder-guild-500 rounded-lg px-3 py-2 focus:ring-2 focus:ring-candlelight-500 focus:border-transparent"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-guild-100 mb-1"
              >Circle</label
            >
            <USelect
              v-model="newMember.circle"
              :items="[
                { label: 'Community', value: 'community' },
                { label: 'Founder', value: 'founder' },
                { label: 'Practitioner', value: 'practitioner' },
              ]"
              class="w-full"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-guild-100 mb-1"
              >Contribution Tier</label
            >
            <USelect
              v-model="newMember.contributionTier"
              :items="[
                { label: '$0/month', value: '0' },
                { label: '$5/month', value: '5' },
                { label: '$15/month', value: '15' },
                { label: '$30/month', value: '30' },
                { label: '$50/month', value: '50' },
              ]"
              class="w-full"
            />
          </div>

          <div class="flex justify-end gap-3 pt-4">
            <button
              type="button"
              @click="showCreateModal = false"
              class="px-4 py-2 text-guild-400 hover:text-guild-100"
            >
              Cancel
            </button>
            <button
              type="submit"
              :disabled="creating"
              class="bg-candlelight-600 text-white px-4 py-2 rounded-lg hover:bg-candlelight-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ creating ? "Creating..." : "Create Member" }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- CSV Import Modal -->
    <div
      v-if="showImportModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-guild-900 rounded-lg shadow-xl max-w-2xl w-full mx-4 border border-guild-700 max-h-[90vh] flex flex-col">
        <div class="px-6 py-4 border-b border-guild-700 flex justify-between items-center">
          <h3 class="text-display-sm font-semibold text-guild-100">Import Members from CSV</h3>
          <button @click="closeImportModal" class="text-guild-500 hover:text-guild-300">
            &times;
          </button>
        </div>

        <div class="p-6 space-y-4 overflow-y-auto">
          <!-- File input -->
          <div v-if="!csvRows.length">
            <p class="text-sm text-guild-400 mb-3">
              Upload a CSV file with columns: <code class="text-guild-200">name,email,circle,contributionTier</code>
            </p>
            <p class="text-sm text-guild-500 mb-4">
              Valid circles: community, founder, practitioner. Valid tiers: 0, 5, 15, 30, 50.
            </p>
            <input
              ref="csvFileInput"
              type="file"
              accept=".csv"
              @change="handleCsvFile"
              class="block w-full text-sm text-guild-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-candlelight-600 file:text-white hover:file:bg-candlelight-700"
            />
          </div>

          <!-- Parse error -->
          <div v-if="csvParseError" class="p-3 bg-ember-500/10 border border-ember-500/30 rounded-lg">
            <p class="text-ember-400 text-sm">{{ csvParseError }}</p>
          </div>

          <!-- Preview table -->
          <div v-if="csvRows.length" class="space-y-4">
            <div class="flex justify-between items-center">
              <p class="text-sm text-guild-300">
                {{ csvRows.length }} row{{ csvRows.length !== 1 ? 's' : '' }} parsed.
                <span v-if="csvValidRows.length !== csvRows.length" class="text-ember-400">
                  {{ csvRows.length - csvValidRows.length }} with errors.
                </span>
              </p>
              <button
                @click="resetCsvImport"
                class="text-sm text-guild-400 hover:text-guild-200"
              >
                Choose different file
              </button>
            </div>

            <div class="overflow-x-auto max-h-64 overflow-y-auto rounded border border-guild-700">
              <table class="w-full text-sm">
                <thead class="bg-guild-950 sticky top-0">
                  <tr>
                    <th class="px-3 py-2 text-left text-xs text-guild-500 uppercase">Status</th>
                    <th class="px-3 py-2 text-left text-xs text-guild-500 uppercase">Name</th>
                    <th class="px-3 py-2 text-left text-xs text-guild-500 uppercase">Email</th>
                    <th class="px-3 py-2 text-left text-xs text-guild-500 uppercase">Circle</th>
                    <th class="px-3 py-2 text-left text-xs text-guild-500 uppercase">Tier</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-guild-800">
                  <tr v-for="(row, i) in csvRows" :key="i" :class="row.error ? 'bg-ember-500/5' : ''">
                    <td class="px-3 py-2">
                      <span v-if="row.error" class="text-ember-400 text-xs">{{ row.error }}</span>
                      <span v-else class="text-candlelight-400 text-xs">OK</span>
                    </td>
                    <td class="px-3 py-2 text-guild-200">{{ row.name }}</td>
                    <td class="px-3 py-2 text-guild-400">{{ row.email }}</td>
                    <td class="px-3 py-2 text-guild-400">{{ row.circle }}</td>
                    <td class="px-3 py-2 text-guild-400">${{ row.contributionTier }}/mo</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Import results -->
            <div v-if="importResults" class="p-4 rounded-lg border border-guild-700 bg-guild-800">
              <p class="text-guild-100 font-medium mb-2">Import complete</p>
              <p class="text-sm text-candlelight-400">{{ importResults.created }} created</p>
              <p v-if="importResults.failed" class="text-sm text-ember-400">{{ importResults.failed }} failed</p>
              <div v-if="importResults.results?.some(r => !r.success)" class="mt-2 space-y-1">
                <p
                  v-for="fail in importResults.results.filter(r => !r.success)"
                  :key="fail.email"
                  class="text-xs text-ember-400"
                >
                  {{ fail.email }}: {{ fail.error }}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div class="px-6 py-4 border-t border-guild-700 flex justify-end gap-3">
          <button
            @click="closeImportModal"
            class="px-4 py-2 text-guild-400 hover:text-guild-100"
          >
            {{ importResults ? 'Done' : 'Cancel' }}
          </button>
          <button
            v-if="csvValidRows.length && !importResults"
            :disabled="importing"
            @click="submitImport"
            class="bg-candlelight-600 text-white px-4 py-2 rounded-lg hover:bg-candlelight-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {{ importing ? 'Importing...' : `Import ${csvValidRows.length} member${csvValidRows.length !== 1 ? 's' : ''}` }}
          </button>
        </div>
      </div>
    </div>

    <!-- Send Invites Modal -->
    <div
      v-if="showInviteModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-guild-900 rounded-lg shadow-xl max-w-2xl w-full mx-4 border border-guild-700 max-h-[90vh] flex flex-col">
        <div class="px-6 py-4 border-b border-guild-700 flex justify-between items-center">
          <h3 class="text-display-sm font-semibold text-guild-100">Send Invite Emails</h3>
          <button @click="showInviteModal = false" class="text-guild-500 hover:text-guild-300">
            &times;
          </button>
        </div>

        <div class="p-6 space-y-4 overflow-y-auto">
          <p class="text-sm text-guild-400">
            Sending to <strong class="text-guild-200">{{ selectedMemberIds.length }}</strong>
            member{{ selectedMemberIds.length !== 1 ? 's' : '' }}.
            Each will receive a unique magic login link valid for 48 hours.
          </p>

          <!-- Email template editor -->
          <div>
            <label class="block text-sm font-medium text-guild-100 mb-2">Email template</label>
            <textarea
              v-model="inviteTemplate"
              rows="12"
              class="w-full border border-guild-700 bg-guild-800 text-guild-100 placeholder-guild-500 rounded-lg px-3 py-2 font-mono text-sm focus:ring-2 focus:ring-candlelight-500 focus:border-transparent"
            ></textarea>
            <p class="text-xs text-guild-500 mt-1">
              Available tokens: <code>{name}</code>, <code>{loginLink}</code>, <code>{circle}</code>
            </p>
          </div>

          <!-- Preview -->
          <div v-if="invitePreviewMember">
            <label class="block text-sm font-medium text-guild-100 mb-2">Preview ({{ invitePreviewMember.name }})</label>
            <pre class="text-sm text-guild-300 bg-guild-950 border border-guild-700 rounded-lg p-4 whitespace-pre-wrap font-mono overflow-auto max-h-48">{{ invitePreviewText }}</pre>
          </div>

          <!-- Results -->
          <div v-if="inviteResults" class="p-4 rounded-lg border border-guild-700 bg-guild-800">
            <p class="text-guild-100 font-medium mb-2">Invites sent</p>
            <p class="text-sm text-candlelight-400">{{ inviteResults.sent }} sent</p>
            <p v-if="inviteResults.failed" class="text-sm text-ember-400">{{ inviteResults.failed }} failed</p>
            <div v-if="inviteResults.results?.some(r => !r.success)" class="mt-2 space-y-1">
              <p
                v-for="fail in inviteResults.results.filter(r => !r.success)"
                :key="fail.email"
                class="text-xs text-ember-400"
              >
                {{ fail.email }}: {{ fail.error }}
              </p>
            </div>
          </div>
        </div>

        <div class="px-6 py-4 border-t border-guild-700 flex justify-end gap-3">
          <button
            @click="showInviteModal = false"
            class="px-4 py-2 text-guild-400 hover:text-guild-100"
          >
            {{ inviteResults ? 'Done' : 'Cancel' }}
          </button>
          <button
            v-if="!inviteResults"
            :disabled="sendingInvites"
            @click="submitInvites"
            class="bg-candlelight-600 text-white px-4 py-2 rounded-lg hover:bg-candlelight-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {{ sendingInvites ? 'Sending...' : `Send ${selectedMemberIds.length} invite${selectedMemberIds.length !== 1 ? 's' : ''}` }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  layout: "admin",
});

const toast = useToast();

const {
  data: members,
  pending,
  error,
  refresh,
} = await useFetch("/api/admin/members");

const searchQuery = ref("");
const circleFilter = ref("");
const showCreateModal = ref(false);
const creating = ref(false);

// Selection
const selectedMemberIds = ref([]);

// CSV import
const showImportModal = ref(false);
const csvFileInput = ref(null);
const csvRows = ref([]);
const csvParseError = ref("");
const importing = ref(false);
const importResults = ref(null);

// Invite
const showInviteModal = ref(false);
const sendingInvites = ref(false);
const inviteResults = ref(null);

const DEFAULT_INVITE_TEMPLATE = `Hi {name},

You've been invited to Ghost Guild as a member of the {circle} circle.

Sign in here to get started:
{loginLink}

This link expires in 48 hours. After that, you can always request a new login link at https://ghostguild.org/login.

See you inside.`;

const inviteTemplate = ref(DEFAULT_INVITE_TEMPLATE);

const newMember = reactive({
  name: "",
  email: "",
  circle: "community",
  contributionTier: "0",
});

const filteredMembers = computed(() => {
  if (!members.value) return [];

  return members.value.filter((member) => {
    const matchesSearch =
      !searchQuery.value ||
      member.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      member.email.toLowerCase().includes(searchQuery.value.toLowerCase());

    const matchesCircle =
      !circleFilter.value || member.circle === circleFilter.value;

    return matchesSearch && matchesCircle;
  });
});

// Selection helpers
const allVisibleSelected = computed(() => {
  if (!filteredMembers.value.length) return false;
  return filteredMembers.value.every((m) =>
    selectedMemberIds.value.includes(m._id)
  );
});

const someVisibleSelected = computed(() => {
  return filteredMembers.value.some((m) =>
    selectedMemberIds.value.includes(m._id)
  );
});

const toggleSelectAll = () => {
  if (allVisibleSelected.value) {
    const visibleIds = new Set(filteredMembers.value.map((m) => m._id));
    selectedMemberIds.value = selectedMemberIds.value.filter(
      (id) => !visibleIds.has(id)
    );
  } else {
    const currentSet = new Set(selectedMemberIds.value);
    for (const m of filteredMembers.value) {
      currentSet.add(m._id);
    }
    selectedMemberIds.value = [...currentSet];
  }
};

const toggleSelect = (id) => {
  const idx = selectedMemberIds.value.indexOf(id);
  if (idx >= 0) {
    selectedMemberIds.value.splice(idx, 1);
  } else {
    selectedMemberIds.value.push(id);
  }
};

// Invite preview
const invitePreviewMember = computed(() => {
  if (!selectedMemberIds.value.length || !members.value) return null;
  return members.value.find((m) => m._id === selectedMemberIds.value[0]);
});

const invitePreviewText = computed(() => {
  if (!invitePreviewMember.value) return "";
  return inviteTemplate.value
    .replace(/\{name\}/g, invitePreviewMember.value.name)
    .replace(/\{loginLink\}/g, "https://ghostguild.org/api/auth/verify?token=...")
    .replace(/\{circle\}/g, invitePreviewMember.value.circle);
});

const getCircleClasses = (circle) => {
  const classes = {
    community: "bg-candlelight-900/20 text-candlelight-400",
    founder: "bg-earth-900/20 text-earth-400",
    practitioner: "bg-candlelight-900/20 text-candlelight-400",
  };
  return classes[circle] || "bg-guild-800 text-guild-300";
};

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString();
};

// --- Create Member ---
const createMember = async () => {
  creating.value = true;
  try {
    await $fetch("/api/admin/members", {
      method: "POST",
      body: newMember,
    });

    showCreateModal.value = false;
    Object.assign(newMember, {
      name: "",
      email: "",
      circle: "community",
      contributionTier: "0",
    });

    await refresh();
    toast.add({ title: "Member created", color: "green" });
  } catch (err) {
    console.error("Failed to create member:", err);
    toast.add({
      title: "Failed to create member",
      description: err.data?.statusMessage || err.message,
      color: "red",
    });
  } finally {
    creating.value = false;
  }
};

// --- CSV Import ---
const VALID_CIRCLES = ["community", "founder", "practitioner"];
const VALID_TIERS = ["0", "5", "15", "30", "50"];

const handleCsvFile = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  csvParseError.value = "";
  csvRows.value = [];

  const reader = new FileReader();
  reader.onload = (e) => {
    const text = e.target.result;
    parseCsv(text);
  };
  reader.readAsText(file);
};

const parseCsv = (text) => {
  const lines = text.split(/\r?\n/).filter((l) => l.trim());
  if (lines.length < 2) {
    csvParseError.value = "CSV must have a header row and at least one data row.";
    return;
  }

  const header = lines[0].split(",").map((h) => h.trim().toLowerCase());
  const nameIdx = header.indexOf("name");
  const emailIdx = header.indexOf("email");
  const circleIdx = header.indexOf("circle");
  const tierIdx = header.indexOf("contributiontier");

  if (nameIdx === -1 || emailIdx === -1 || circleIdx === -1 || tierIdx === -1) {
    csvParseError.value = `Missing required columns. Found: ${header.join(", ")}. Need: name, email, circle, contributionTier`;
    return;
  }

  const seenEmails = new Set();
  const rows = [];

  for (let i = 1; i < lines.length; i++) {
    const cols = lines[i].split(",").map((c) => c.trim());
    const name = cols[nameIdx] || "";
    const email = (cols[emailIdx] || "").toLowerCase();
    const circle = (cols[circleIdx] || "").toLowerCase();
    const contributionTier = cols[tierIdx] || "";

    let error = null;
    if (!name) error = "Missing name";
    else if (!email || !email.includes("@")) error = "Invalid email";
    else if (!VALID_CIRCLES.includes(circle)) error = `Invalid circle: ${circle}`;
    else if (!VALID_TIERS.includes(contributionTier)) error = `Invalid tier: ${contributionTier}`;
    else if (seenEmails.has(email)) error = "Duplicate email in CSV";

    if (!error) seenEmails.add(email);

    rows.push({ name, email, circle, contributionTier, error });
  }

  csvRows.value = rows;
};

const csvValidRows = computed(() => csvRows.value.filter((r) => !r.error));

const resetCsvImport = () => {
  csvRows.value = [];
  csvParseError.value = "";
  importResults.value = null;
  if (csvFileInput.value) csvFileInput.value.value = "";
};

const closeImportModal = () => {
  showImportModal.value = false;
  if (importResults.value) {
    resetCsvImport();
    refresh();
  }
};

const submitImport = async () => {
  importing.value = true;
  try {
    const payload = csvValidRows.value.map(({ name, email, circle, contributionTier }) => ({
      name,
      email,
      circle,
      contributionTier,
    }));

    const result = await $fetch("/api/admin/members/import", {
      method: "POST",
      body: { members: payload },
    });

    importResults.value = result;
    toast.add({
      title: `Imported ${result.created} member${result.created !== 1 ? "s" : ""}`,
      description: result.failed ? `${result.failed} failed` : undefined,
      color: result.failed ? "orange" : "green",
    });
  } catch (err) {
    console.error("Import failed:", err);
    toast.add({
      title: "Import failed",
      description: err.data?.statusMessage || err.message,
      color: "red",
    });
  } finally {
    importing.value = false;
  }
};

// --- Send Invites ---
const openInviteModal = () => {
  inviteResults.value = null;
  inviteTemplate.value = DEFAULT_INVITE_TEMPLATE;
  showInviteModal.value = true;
};

const submitInvites = async () => {
  sendingInvites.value = true;
  try {
    const result = await $fetch("/api/admin/members/invite", {
      method: "POST",
      body: {
        memberIds: selectedMemberIds.value,
        emailTemplate: inviteTemplate.value,
      },
    });

    inviteResults.value = result;
    await refresh();
    selectedMemberIds.value = [];

    toast.add({
      title: `Sent ${result.sent} invite${result.sent !== 1 ? "s" : ""}`,
      description: result.failed ? `${result.failed} failed` : undefined,
      color: result.failed ? "orange" : "green",
    });
  } catch (err) {
    console.error("Failed to send invites:", err);
    toast.add({
      title: "Failed to send invites",
      description: err.data?.statusMessage || err.message,
      color: "red",
    });
  } finally {
    sendingInvites.value = false;
  }
};

// --- Existing actions ---
const sendSlackInvite = (member) => {
  alert(`Slack invite functionality would send invite to ${member.email}`);
  console.log("Send Slack invite to:", member.email);
};

const editMember = (member) => {
  alert(`Edit functionality would open editor for ${member.name}`);
  console.log("Edit member:", member._id);
};
</script>
