"use client";

import Link from "next/link";
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { Icons } from "@/components/icons";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ContentReviewActionDialog } from "@/features/content-approval/components/content-review-action-dialog";
import {
  canDeleteContent,
  canEditContent,
  canTransitionContent,
} from "@/features/content-approval/lib/workflow";
import {
  deleteAnnouncementMutation,
  pinAnnouncementMutation,
  unpinAnnouncementMutation,
  updateAnnouncementStateMutation,
} from "../api/mutations";
import type { Announcement } from "../api/types";
import {
  canManageAnnouncementPin,
  isAnnouncementPinEligible,
} from "../lib/pin";

export function AnnouncementActionMenu({
  announcement,
  currentUserId,
  permissions,
}: {
  announcement: Announcement;
  currentUserId: string;
  permissions: readonly string[];
}) {
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [reviewAction, setReviewAction] = useState<
    "approve" | "return" | "reject" | null
  >(null);
  const isOwner = announcement.created_by === currentUserId;

  const canEdit = canEditContent({
    module: "announcement",
    permissions,
    status: announcement.status,
    isOwner,
  });
  const canDelete = canDeleteContent({
    module: "announcement",
    permissions,
    status: announcement.status,
    isOwner,
  });
  const canSubmit = canTransitionContent({
    module: "announcement",
    action: "submit",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canApprove = canTransitionContent({
    module: "announcement",
    action: "approve",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canReturn = canTransitionContent({
    module: "announcement",
    action: "return",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canReject = canTransitionContent({
    module: "announcement",
    action: "reject",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canPublish = canTransitionContent({
    module: "announcement",
    action: "publish",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canArchive = canTransitionContent({
    module: "announcement",
    action: "archive",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canPinManage = canManageAnnouncementPin(permissions);
  const canPin =
    canPinManage &&
    !announcement.is_pin &&
    isAnnouncementPinEligible(announcement);
  const canUnpin = canPinManage && announcement.is_pin;

  const stateMutation = useMutation({
    ...updateAnnouncementStateMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถอัปเดตสถานะประกาศได้");
    },
  });

  const deleteMutation = useMutation({
    ...deleteAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถยกเลิกเผยแพร่ได้");
    },
  });

  const pinMutation = useMutation({
    ...pinAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถปักหมุดประกาศได้");
    },
  });

  const unpinMutation = useMutation({
    ...unpinAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถยกเลิกการปักหมุดได้");
    },
  });

  const isBusy =
    stateMutation.isPending ||
    deleteMutation.isPending ||
    pinMutation.isPending ||
    unpinMutation.isPending;

  return (
    <>
      <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>ยืนยันการยกเลิกเผยแพร่</AlertDialogTitle>
            <AlertDialogDescription>
              ระบบจะยกเลิกเผยแพร่ฉบับร่างและไฟล์แนบที่เกี่ยวข้องอย่างถาวร
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isBusy}>ยกเลิก</AlertDialogCancel>
            <AlertDialogAction
              disabled={isBusy}
              onClick={() => {
                deleteMutation.mutate(announcement.id);
                setDeleteOpen(false);
              }}
            >
              {deleteMutation.isPending ? "กำลังลบ..." : "ยกเลิกเผยแพร่"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <ContentReviewActionDialog
        open={reviewAction !== null}
        onOpenChange={(open) => {
          if (!open) {
            setReviewAction(null);
          }
        }}
        action={reviewAction}
        module="announcement"
        contentTitle={announcement.title}
        isSubmitting={stateMutation.isPending}
        onConfirm={(values) => {
          stateMutation.mutate({ id: announcement.id, values });
          setReviewAction(null);
        }}
      />

      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-9 w-9 shrink-0"
            aria-label={`เมนูจัดการประกาศ ${announcement.title}`}
          >
            <Icons.ellipsis className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent
          align="end"
          sideOffset={8}
          className="w-56 max-w-[calc(100vw-1rem)]"
        >
          <DropdownMenuLabel>จัดการประกาศ</DropdownMenuLabel>
          <DropdownMenuItem asChild>
            <Link href={`/dashboard/announcements/${announcement.id}`}>
              <Icons.info className="mr-2 h-4 w-4" />
              ดูรายละเอียด
            </Link>
          </DropdownMenuItem>

          {canEdit ? (
            <DropdownMenuItem asChild>
              <Link href={`/dashboard/announcements/${announcement.id}`}>
                <Icons.edit className="mr-2 h-4 w-4" />
                แก้ไข
              </Link>
            </DropdownMenuItem>
          ) : null}

          {canSubmit ||
          canApprove ||
          canReturn ||
          canReject ||
          canPublish ||
          canArchive ||
          canPin ||
          canUnpin ? (
            <DropdownMenuSeparator />
          ) : null}

          {canSubmit ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() =>
                stateMutation.mutate({
                  id: announcement.id,
                  values: { action: "submit" },
                })
              }
            >
              <Icons.send className="mr-2 h-4 w-4" />
              ส่งตรวจสอบ
            </DropdownMenuItem>
          ) : null}
          {canApprove ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() => setReviewAction("approve")}
            >
              <Icons.check className="mr-2 h-4 w-4" />
              อนุมัติ
            </DropdownMenuItem>
          ) : null}
          {canReturn ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() => setReviewAction("return")}
            >
              <Icons.arrowRight className="mr-2 h-4 w-4" />
              ส่งกลับแก้ไข
            </DropdownMenuItem>
          ) : null}
          {canReject ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() => setReviewAction("reject")}
            >
              <Icons.close className="mr-2 h-4 w-4" />
              ไม่อนุมัติ
            </DropdownMenuItem>
          ) : null}
          {canPublish ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() =>
                stateMutation.mutate({
                  id: announcement.id,
                  values: { action: "publish" },
                })
              }
            >
              <Icons.share className="mr-2 h-4 w-4" />
              เผยแพร่
            </DropdownMenuItem>
          ) : null}
          {canPin ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() => pinMutation.mutate(announcement.id)}
            >
              <Icons.exclusive className="mr-2 h-4 w-4" />
              ปักหมุดประกาศ
            </DropdownMenuItem>
          ) : null}
          {canUnpin ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() => unpinMutation.mutate(announcement.id)}
            >
              <Icons.slash className="mr-2 h-4 w-4" />
              ยกเลิกการปักหมุด
            </DropdownMenuItem>
          ) : null}
          {canArchive ? (
            <DropdownMenuItem
              disabled={isBusy}
              onClick={() =>
                stateMutation.mutate({
                  id: announcement.id,
                  values: { action: "archive" },
                })
              }
            >
              <Icons.workspace className="mr-2 h-4 w-4" />
              ยกเลิกเผยแพร่
            </DropdownMenuItem>
          ) : null}

          {canDelete ? (
            <>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                disabled={isBusy}
                className="text-destructive focus:text-destructive"
                onClick={() => setDeleteOpen(true)}
              >
                <Icons.trash className="mr-2 h-4 w-4" />
                ยกเลิกเผยแพร่
              </DropdownMenuItem>
            </>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
