"use client";

import { useState } from "react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { useRepositories } from "@/di/repository-provider";
import { useT } from "@/shared/i18n/client";
import { ROUTES } from "@/shared/constants";
import { displayState } from "@/shared/lib/announcements";
import { Label } from "@/presentation/components/ui/label";
import { Textarea } from "@/presentation/components/ui/textarea";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/presentation/components/ui/alert-dialog";
import { useAnnouncementPermissions } from "@/presentation/components/announcements/use-announcement-permissions";
import type { Announcement, AnnouncementDisplayState } from "@/domain/entities/announcement";

export type AnnouncementAction =
  | "edit"
  | "preview"
  | "publish"
  | "duplicate"
  | "delete"
  | "unpublish"
  | "archive"
  | "reset"
  | "stats";

/** Actions per display state (spec §6.1); publishing actions need announcements.publish. A draft or
 * a scheduled announcement can be archived too: test drafts leave the list (QA 2026-10-22). */
const BY_STATE: Record<AnnouncementDisplayState, AnnouncementAction[]> = {
  draft: ["edit", "preview", "publish", "duplicate", "delete", "archive"],
  scheduled: ["edit", "preview", "unpublish", "archive"],
  live: ["edit", "stats", "reset", "unpublish", "archive"],
  ended: ["stats", "duplicate", "archive"],
  archived: ["stats", "duplicate"],
};

const PUBLISHING: AnnouncementAction[] = ["publish", "unpublish", "reset", "archive"];
const CONFIRMED: AnnouncementAction[] = ["delete", "unpublish", "archive", "reset"];

export function useAvailableActions() {
  const { canPublish } = useAnnouncementPermissions();
  return (a: Announcement): AnnouncementAction[] =>
    BY_STATE[displayState(a)].filter(
      (action) =>
        (canPublish || !PUBLISHING.includes(action)) &&
        // A draft that was live once keeps its statistics: unpublish then archive, never delete.
        !(action === "delete" && a.first_published_at),
    );
}

/**
 * Runs an announcement action from the list or the editor: navigation for edit / preview /
 * publish / stats, a confirmation for the destructive ones, the API call and a toast.
 */
export function useAnnouncementActions(onDone: (updated: Announcement | null, action: AnnouncementAction) => void) {
  const t = useT();
  const router = useRouter();
  const { announcementRepository } = useRepositories();
  const [pending, setPending] = useState<{ action: AnnouncementAction; announcement: Announcement } | null>(null);
  const [reason, setReason] = useState("");
  const [busy, setBusy] = useState(false);

  const execute = async (action: AnnouncementAction, a: Announcement) => {
    setBusy(true);
    try {
      let updated: Announcement | null = null;
      switch (action) {
        case "duplicate":
          updated = await announcementRepository.duplicate(a.id);
          toast.success(t.announcements.toasts.duplicated);
          router.push(`${ROUTES.announcements}/${updated.id}`);
          break;
        case "delete":
          await announcementRepository.remove(a.id);
          toast.success(t.announcements.toasts.deleted);
          break;
        case "unpublish":
          updated = await announcementRepository.unpublish(a.id);
          toast.success(t.announcements.toasts.unpublished);
          break;
        case "archive":
          updated = await announcementRepository.archive(a.id);
          toast.success(t.announcements.toasts.archived);
          break;
        case "reset":
          updated = await announcementRepository.reset(a.id, reason);
          toast.success(t.announcements.toasts.reset);
          break;
      }
      onDone(updated, action);
    } catch (err) {
      const message = (err as { response?: { data?: { message?: string } }; message?: string })?.response?.data?.message ?? (err as Error).message;
      toast.error(message);
    } finally {
      setBusy(false);
      setPending(null);
      setReason("");
    }
  };

  const run = (action: AnnouncementAction, a: Announcement) => {
    const base = `${ROUTES.announcements}/${a.id}`;
    if (action === "edit") return router.push(base);
    if (action === "stats") return router.push(`${base}?tab=stats`);
    if (action === "publish") return router.push(`${base}?publish=1`);
    if (action === "preview") return router.push(`${base}?preview=1`);
    if (CONFIRMED.includes(action)) return setPending({ action, announcement: a });
    void execute(action, a);
  };

  const c = t.announcements.confirm;
  const copy: Partial<Record<AnnouncementAction, { title: string; body: string; label: string; destructive?: boolean }>> = {
    delete: { title: c.deleteTitle, body: c.deleteBody, label: t.announcements.actions.delete, destructive: true },
    archive: { title: c.archiveTitle, body: c.archiveBody, label: t.announcements.actions.archive },
    unpublish: { title: c.unpublishTitle, body: c.unpublishBody, label: t.announcements.actions.unpublish },
    reset: {
      title: c.resetTitle,
      body: pending ? c.resetBody(pending.announcement.counts.eligible) : "",
      label: t.announcements.actions.reset,
    },
  };
  const current = pending ? copy[pending.action] : undefined;

  const dialogs = (
    <AlertDialog open={!!pending} onOpenChange={(open) => !open && !busy && setPending(null)}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{current?.title}</AlertDialogTitle>
          <AlertDialogDescription>{current?.body}</AlertDialogDescription>
        </AlertDialogHeader>
        {pending?.action === "reset" && (
          <div className="space-y-1.5">
            <Label htmlFor="reset-reason">{c.resetReason}</Label>
            <Textarea
              id="reset-reason"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder={c.resetReasonPlaceholder}
              maxLength={200}
              rows={2}
            />
          </div>
        )}
        <AlertDialogFooter>
          <AlertDialogCancel disabled={busy}>{c.cancel}</AlertDialogCancel>
          <AlertDialogAction
            disabled={busy}
            className={current?.destructive ? "bg-destructive text-white hover:bg-destructive/90" : undefined}
            onClick={(e) => {
              e.preventDefault();
              if (pending) void execute(pending.action, pending.announcement);
            }}
          >
            {current?.label}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );

  return { run, dialogs, busy };
}
