import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { s as supabase } from "./client-CJCZGN4z.js";
import { A as AdminShell } from "./AdminShell-fo83oaxY.js";
import { D as DeleteButton } from "./DeleteButton-D7V3t-jE.js";
import { B as Button } from "./button-BXrfXN_b.js";
import { L as Label, I as Input } from "./label-BsuFFEVs.js";
import { S as Switch } from "./switch-DDHih_sy.js";
import { C as Card, a as CardHeader, b as CardTitle, c as CardContent } from "./card-DU714E9E.js";
import { D as Dialog, a as DialogContent, b as DialogHeader, c as DialogTitle, d as DialogFooter } from "./alert-dialog-Cbc2KPWf.js";
import { Plus, Edit, Trash2 } from "lucide-react";
import { toast } from "sonner";
import "@supabase/supabase-js";
import "@tanstack/react-router";
import "./use-auth-DoD1gvcu.js";
import "@radix-ui/react-slot";
import "class-variance-authority";
import "clsx";
import "tailwind-merge";
import "@radix-ui/react-label";
import "@radix-ui/react-switch";
import "@radix-ui/react-dialog";
import "@radix-ui/react-alert-dialog";
function PollsPage() {
  const qc = useQueryClient();
  const [editing, setEditing] = useState(null);
  const [editOptions, setEditOptions] = useState([]);
  const [removedOptionIds, setRemovedOptionIds] = useState([]);
  const list = useQuery({
    queryKey: ["admin", "polls"],
    queryFn: async () => {
      const {
        data: polls,
        error
      } = await supabase.from("polls").select("*").order("created_at", {
        ascending: false
      });
      if (error) throw error;
      const {
        data: options,
        error: optErr
      } = await supabase.from("poll_options").select("*").order("position");
      if (optErr) throw optErr;
      return (polls ?? []).map((p) => ({
        ...p,
        options: (options ?? []).filter((o) => o.poll_id === p.id)
      }));
    }
  });
  function openNew() {
    setEditing({
      question: "",
      active: true,
      closes_at: null
    });
    setEditOptions([{
      label: "",
      position: 1
    }, {
      label: "",
      position: 2
    }]);
    setRemovedOptionIds([]);
  }
  function openEdit(poll) {
    setEditing(poll);
    setEditOptions(poll.options.map((o) => ({
      id: o.id,
      label: o.label,
      position: o.position,
      votes: o.votes
    })));
    setRemovedOptionIds([]);
  }
  const save = useMutation({
    mutationFn: async () => {
      if (!editing?.question?.trim()) throw new Error("Question is required");
      const cleaned = editOptions.map((o) => ({
        ...o,
        label: o.label.trim()
      })).filter((o) => o.label);
      if (cleaned.length < 2) throw new Error("At least 2 options required");
      if (editing.id) {
        const {
          error
        } = await supabase.from("polls").update({
          question: editing.question.trim(),
          active: !!editing.active,
          closes_at: editing.closes_at || null
        }).eq("id", editing.id);
        if (error) throw error;
        for (const optId of removedOptionIds) {
          const {
            error: delErr
          } = await supabase.from("poll_options").delete().eq("id", optId);
          if (delErr) throw delErr;
        }
        for (let i = 0; i < cleaned.length; i++) {
          const opt = cleaned[i];
          const position = i + 1;
          if (opt.id) {
            const {
              error: updErr
            } = await supabase.from("poll_options").update({
              label: opt.label,
              position
            }).eq("id", opt.id);
            if (updErr) throw updErr;
          } else {
            const {
              error: insErr
            } = await supabase.from("poll_options").insert({
              poll_id: editing.id,
              label: opt.label,
              position
            });
            if (insErr) throw insErr;
          }
        }
      } else {
        const {
          data: poll,
          error
        } = await supabase.from("polls").insert({
          question: editing.question.trim(),
          active: !!editing.active,
          closes_at: editing.closes_at || null
        }).select("id").single();
        if (error) throw error;
        const {
          error: optErr
        } = await supabase.from("poll_options").insert(cleaned.map((o, i) => ({
          poll_id: poll.id,
          label: o.label,
          position: i + 1
        })));
        if (optErr) throw optErr;
      }
    },
    onSuccess: () => {
      toast.success(editing?.id ? "Poll updated" : "Poll created");
      setEditing(null);
      qc.invalidateQueries({
        queryKey: ["admin", "polls"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const toggle = useMutation({
    mutationFn: async ({
      id,
      active
    }) => {
      const {
        error
      } = await supabase.from("polls").update({
        active
      }).eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => qc.invalidateQueries({
      queryKey: ["admin", "polls"]
    })
  });
  const del = useMutation({
    mutationFn: async (id) => {
      const {
        error
      } = await supabase.from("polls").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Poll deleted");
      qc.invalidateQueries({
        queryKey: ["admin", "polls"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  function removeOption(index) {
    const opt = editOptions[index];
    if (opt?.id) setRemovedOptionIds((ids) => [...ids, opt.id]);
    setEditOptions(editOptions.filter((_, i) => i !== index));
  }
  return /* @__PURE__ */ jsxs(AdminShell, { title: "Polls & Surveys", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center mb-4", children: [
      /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
        list.data?.length ?? 0,
        " polls"
      ] }),
      /* @__PURE__ */ jsxs(Button, { onClick: openNew, children: [
        /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
        " New Poll"
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      list.data?.map((p) => {
        const total = p.options.reduce((s, o) => s + (o.votes ?? 0), 0);
        return /* @__PURE__ */ jsxs(Card, { children: [
          /* @__PURE__ */ jsxs(CardHeader, { className: "flex flex-row items-start justify-between", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx(CardTitle, { className: "font-serif text-lg", children: p.question }),
              /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: [
                total,
                " votes",
                p.closes_at && /* @__PURE__ */ jsxs(Fragment, { children: [
                  " · closes ",
                  new Date(p.closes_at).toLocaleDateString()
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Switch, { checked: p.active, onCheckedChange: (c) => toggle.mutate({
                id: p.id,
                active: c
              }) }),
              /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", onClick: () => openEdit(p), children: /* @__PURE__ */ jsx(Edit, { className: "w-4 h-4" }) }),
              /* @__PURE__ */ jsx(DeleteButton, { onDelete: () => del.mutate(p.id), title: "Delete poll?", description: "All votes and options for this poll will be removed." })
            ] })
          ] }),
          /* @__PURE__ */ jsx(CardContent, { className: "space-y-2", children: p.options.map((o) => {
            const pct = total ? Math.round((o.votes ?? 0) / total * 100) : 0;
            return /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs("div", { className: "flex justify-between text-xs mb-1", children: [
                /* @__PURE__ */ jsx("span", { children: o.label }),
                /* @__PURE__ */ jsxs("span", { children: [
                  o.votes ?? 0,
                  " (",
                  pct,
                  "%)"
                ] })
              ] }),
              /* @__PURE__ */ jsx("div", { className: "h-2 bg-muted rounded-full overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "h-full bg-brand-accent", style: {
                width: `${pct}%`
              } }) })
            ] }, o.id);
          }) })
        ] }, p.id);
      }),
      !list.data?.length && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "No polls yet." })
    ] }),
    /* @__PURE__ */ jsx(Dialog, { open: !!editing, onOpenChange: (o) => !o && setEditing(null), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-lg", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: editing?.id ? "Edit poll" : "New poll" }) }),
      editing && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Question" }),
          /* @__PURE__ */ jsx(Input, { value: editing.question ?? "", onChange: (e) => setEditing({
            ...editing,
            question: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Closes at (optional)" }),
          /* @__PURE__ */ jsx(Input, { type: "datetime-local", value: editing.closes_at ? editing.closes_at.slice(0, 16) : "", onChange: (e) => setEditing({
            ...editing,
            closes_at: e.target.value ? new Date(e.target.value).toISOString() : null
          }) })
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
          /* @__PURE__ */ jsx(Switch, { checked: !!editing.active, onCheckedChange: (c) => setEditing({
            ...editing,
            active: c
          }) }),
          "Active"
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { children: "Options" }),
          editOptions.map((o, i) => /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsx(Input, { placeholder: `Option ${i + 1}`, value: o.label, onChange: (e) => setEditOptions(editOptions.map((x, j) => j === i ? {
              ...x,
              label: e.target.value
            } : x)) }),
            editOptions.length > 2 && /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", onClick: () => removeOption(i), children: /* @__PURE__ */ jsx(Trash2, { className: "w-4 h-4" }) })
          ] }, i)),
          /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => setEditOptions([...editOptions, {
            label: "",
            position: editOptions.length + 1
          }]), children: [
            /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
            " Add option"
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setEditing(null), children: "Cancel" }),
        /* @__PURE__ */ jsx(Button, { onClick: () => save.mutate(), disabled: save.isPending || !editing?.question?.trim(), children: "Save" })
      ] })
    ] }) })
  ] });
}
export {
  PollsPage as component
};
