"use client";

import { useEffect, useState } from "react";
import { useActionState } from "react";
import { CheckCircle2Icon, AlertCircleIcon, Loader2Icon } from "lucide-react";
import { sendTestAction, type SendTestResult } from "@/actions/groups";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { useEvents } from "@/hooks/use-events";

const initial: SendTestResult | null = null;

type Outcome =
  | { kind: "idle" }
  | { kind: "in-flight"; message: string }
  | { kind: "sent"; message: string }
  | { kind: "error"; message: string };

export function SendTestForm({ groupId }: { groupId: string }) {
  const [state, formAction, isPending] = useActionState(sendTestAction, initial);
  const [outcome, setOutcome] = useState<Outcome>({ kind: "idle" });

  // Bridge the optimistic action result into our richer Outcome state.
  // The action's `ok` only confirms the IPC NOTIFY was published — we
  // wait for the bot's `send_test.done` event below to know whether
  // WhatsApp actually accepted the message.
  useEffect(() => {
    if (!state) return;
    if (state.ok) {
      setOutcome({ kind: "in-flight", message: state.message });
    } else {
      setOutcome({ kind: "error", message: state.error });
    }
  }, [state]);

  // Subscribe to the bot's reply. Only act on events for OUR groupId so
  // a parallel send-test on another group doesn't move our state.
  useEvents({
    "send_test.done": (data) => {
      if (data.groupId !== groupId) return;
      if (data.ok) {
        setOutcome({ kind: "sent", message: "Sent ✓" });
      } else {
        setOutcome({
          kind: "error",
          message: data.error ?? "Send failed — see bot logs for details.",
        });
      }
    },
  });

  const sending = isPending || outcome.kind === "in-flight";

  return (
    <form action={formAction} className="space-y-3">
      <input type="hidden" name="groupId" value={groupId} />
      <div>
        <Label htmlFor="text" className="text-sm">
          Message
        </Label>
        <Textarea
          id="text"
          name="text"
          placeholder="What should I send to this group?"
          rows={4}
          required
          maxLength={4000}
          className="mt-1"
        />
      </div>

      {outcome.kind === "in-flight" && (
        <p
          className="flex items-center gap-1.5 text-sm text-muted-foreground"
          role="status"
          aria-live="polite"
        >
          <Loader2Icon className="size-3.5 animate-spin" aria-hidden />
          {outcome.message}
        </p>
      )}
      {outcome.kind === "sent" && (
        <p
          className="flex items-center gap-1.5 text-sm text-emerald-600 dark:text-emerald-400"
          role="status"
          aria-live="polite"
        >
          <CheckCircle2Icon className="size-3.5" aria-hidden />
          {outcome.message}
        </p>
      )}
      {outcome.kind === "error" && (
        <p
          className="flex items-center gap-1.5 text-sm text-destructive"
          role="alert"
        >
          <AlertCircleIcon className="size-3.5" aria-hidden />
          {outcome.message}
        </p>
      )}

      <div className="flex justify-end">
        <Button type="submit" disabled={sending}>
          {sending ? "Sending…" : "Send Test"}
        </Button>
      </div>
    </form>
  );
}
