import { CollaborationDto } from "@/record-management/services/api/collaborationService";
import { getMyRecordCollaboratorComments } from "@/record-management/services/api/recordCollaboratorCommentsService";
import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import { t } from "i18next";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import ApproveCollaborationRecord from "./approveCollaborationRecord";
import RejectCollaborationRecord from "./rejectCollaborationRecord";
import CommentCollaborationRecord from "./commentCollaborationRecord";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import {
  Banknote,
  Edit3,
  MessageSquare,
  MoreVertical,
  RotateCcw,
  SquareCheckBig,
} from "lucide-react";
import { useMyCollaborations } from "../hooks/useMyCollaborations";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";

const CollaborationActionsComponent = ({
  rowData,
  refreshTable,
  canRecordBeEditedByCollaborators,
  showViewDetailButton = true,
  fromTable = true,
}: {
  rowData: CollaborationDto;
  refreshTable: () => void;
  canRecordBeEditedByCollaborators?: boolean;
  showViewDetailButton?: boolean;
  fromTable?: boolean;
}) => {
  const navigate = useNavigate();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showApprove, setShowApprove] = useState<boolean>(false);
  const [showReject, setShowReject] = useState<boolean>(false);
  const [showComment, setShowComment] = useState<boolean>(false);
  const queryClient = useQueryClient();
  const { userDetails } = useAuthUser();
  const { signCollaboration, signStatus } = useMyCollaborations();
  const unitId = userDetails?.employee?.[0]?.unitId ?? "";
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: canRecordBeEditedByCollaborators === undefined && Boolean(unitId),
  });
  const currentUserId = userDetails?.id;
  const contentId = rowData?.record?.content?.[0]?.id;
  const canEditFromConfig =
    canRecordBeEditedByCollaborators ??
    unitConfigData?.data?.items?.[0]?.canRecordBeEditedByCollaborators ??
    false;

  const handleViewDetails = () => {
    navigate(
      `/record-management/collaborations/viewRecord/${rowData?.record?.id}`,
      {
        state: {
          collaboration: rowData,
          actionRowData: rowData,
        },
      },
    );
  };
  const handleApproveClick = () => {
    setShowApprove(true);
  };
  const handleRejectClick = () => {
    setShowReject(true);
  };
  const handleEditClick = () => {
    setDropdownOpen(false);
    if (rowData?.record?.id) {
      navigate(
        `/record-management/userRecords/editUserRecord/${rowData.record.id}?from=collaborations`,
      );
    }
  };
  const handleCommentClick = () => {
    setShowComment(true);
  };
  const handleAdjustClick = async () => {
    setDropdownOpen(false);

    if (!rowData?.id || !contentId) {
      toast.error(
        t(
          "collaboration.adjustCommentMissing",
          "No comment found to use for adjustment.",
        ),
      );
      return;
    }

    try {
      const myComments = await getMyRecordCollaboratorComments(rowData.id);
      const currentComment = myComments.find(
        (comment) => comment.recordContentId === contentId,
      );

      if (!currentComment?.comment?.trim()) {
        toast.error(
          t(
            "collaboration.adjustCommentMissing",
            "No comment found to use for adjustment.",
          ),
        );
        return;
      }

      await signCollaboration({
        payload: {
          collabId: rowData.id,
          signStatus: "team_rejected",
          comment: currentComment.comment,
        },
      });

      toast.success(
        t("collaboration.adjustSubmitted", "Adjustment sent successfully."),
      );
      refreshTable();
      queryClient.invalidateQueries({
        queryKey: ["my-collaborations"],
      });
      queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
    } catch (error: any) {
      toast.error(
        error?.message ||
          t(
            "collaboration.adjustFailed",
            "Failed to send the adjustment request.",
          ),
      );
    }
  };
  const isSignable = rowData.signStatus === "draft";
  // "team_rejected" = collaborator commented (send-back). "rejected" = hard reject.
  // In either state Edit is restricted to the record's creator.
  const isRejectedOrCommented =
    rowData.signStatus === "rejected" || rowData.signStatus === "team_rejected";
  const isCreator =
    Boolean(currentUserId) && currentUserId === rowData?.record?.userId;
  // Once the collaborator has signed or hard-rejected, no further Edit /
  // Comment should be possible from their side.
  const isUserActionFinalized =
    rowData.signStatus === "signed" || rowData.signStatus === "rejected";
  const isEditable =
    !isUserActionFinalized && (!isRejectedOrCommented || isCreator);
  const canEdit = isEditable && canEditFromConfig;
  const canAdjust = canEdit && false;
  const canComment = !isUserActionFinalized;
  // Hide the three-dot entirely when there's nothing to put in the menu —
  // otherwise the dropdown opens to just the "Actions" header with no items.
  const hasAnyAction = isSignable || canEdit || canComment;
  return (
    <>
      {fromTable ? (
        <div className="flex">
          {showViewDetailButton && (
            <Button variant={"viewDetail"} onClick={() => handleViewDetails()}>
              {t("userRecord.View Detail")}
            </Button>
          )}

          {hasAnyAction && (
            <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                  <MoreVertical className="h-4 w-4" />
                  <span className="sr-only">
                    {t("userIncoming.Open actions menu")}
                  </span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="end"
                onInteractOutside={(e) => {
                  const target = e.target as HTMLElement;
                  if (!target.closest('[role="dialog"]')) {
                    setDropdownOpen(false);
                  }
                }}
              >
                <DropdownMenuLabel>{t("userRecord.Actions")}</DropdownMenuLabel>
                {isSignable && (
                  <DropdownMenuItem
                    onSelect={handleApproveClick}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent"
                  >
                    <SquareCheckBig className="mr-2 h-4 w-4" />
                    {t("userRecord.Approve")}
                  </DropdownMenuItem>
                )}
                {isSignable && (
                  <DropdownMenuItem
                    onSelect={handleRejectClick}
                    className="cursor-pointer hover:!text-red-600 !bg-transparent !transition-colors duration-200"
                  >
                    <Banknote className="mr-2 h-4 w-4 text-red-600 group-hover:text-white transition-colors duration-200" />
                    {t("statusBar.Reject")}
                  </DropdownMenuItem>
                )}
                {canEdit && (
                  <DropdownMenuItem
                    onSelect={handleEditClick}
                    className="cursor-pointer !bg-transparent"
                  >
                    <Edit3 className="mr-2 h-4 w-4" />
                    {t("collaboration.edit", "Edit")}
                  </DropdownMenuItem>
                )}
                {canAdjust && (
                  <DropdownMenuItem
                    onSelect={() => void handleAdjustClick()}
                    disabled={signStatus.isLoading}
                    className="cursor-pointer !bg-transparent"
                  >
                    <RotateCcw className="mr-2 h-4 w-4" />
                    {t("collaboration.adjust", "Adjust")}
                  </DropdownMenuItem>
                )}
                {canComment && (
                  <DropdownMenuItem
                    onSelect={handleCommentClick}
                    className="cursor-pointer !bg-transparent"
                  >
                    <MessageSquare className="mr-2 h-4 w-4" />
                    {t("collaboration.comment", "Comment")}
                  </DropdownMenuItem>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      ) : hasAnyAction ? (
        <div className="flex flex-wrap gap-2">
          {isSignable && (
            <Button
              variant={getActionButtonVariant("Approve")}
              onClick={handleApproveClick}
            >
              <SquareCheckBig className="h-4 w-4" />
              <span>
                {t("userRecord.Approve")}
              </span>
            </Button>
          )}

          {isSignable && (
            <Button
              variant={getActionButtonVariant("Reject")}
              onClick={handleRejectClick}
            >
              <Banknote className="h-4 w-4" />
              <span>
                {t("statusBar.Reject")}
              </span>
            </Button>
          )}

          {canEdit && (
            <Button
              variant={getActionButtonVariant("Edit")}
              onClick={handleEditClick}
            >
              <Edit3 className="h-4 w-4" />
              <span>
                {t("collaboration.edit", "Edit")}
              </span>
            </Button>
          )}

          {canAdjust && (
            <Button
              variant={getActionButtonVariant("Adjustment")}
              onClick={() => void handleAdjustClick()}
              disabled={signStatus.isLoading}
            >
              <RotateCcw className="h-4 w-4" />
              <span>
                {t("collaboration.adjust", "Adjust")}
              </span>
            </Button>
          )}

          {canComment && (
            <Button
              variant={getActionButtonVariant("Comment")}
              onClick={handleCommentClick}
            >
              <MessageSquare className="h-4 w-4" />
              <span>
                {t("collaboration.comment", "Comment")}
              </span>
            </Button>
          )}
        </div>
      ) : null}

      {showApprove && isSignable && (
        <ApproveCollaborationRecord
          collaborationId={rowData?.id as string}
          onSuccess={() => {
            setShowApprove(false);
            refreshTable();
            queryClient.invalidateQueries({
              queryKey: ["my-collaborations"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
            navigate("/record-management/collaborations");
          }}
          onClose={() => {
            setShowApprove(false);
            refreshTable();
            queryClient.invalidateQueries({
              queryKey: ["my-collaborations"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
        />
      )}
      {showReject && isSignable && (
        <RejectCollaborationRecord
          collaborationId={rowData?.id as string}
          onSuccess={() => {
            setShowReject(false);
            refreshTable();
            queryClient.invalidateQueries({
              queryKey: ["my-collaborations"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
            navigate("/record-management/collaborations");
          }}
          onClose={() => {
            setShowReject(false);
            refreshTable();
            queryClient.invalidateQueries({
              queryKey: ["my-collaborations"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
        />
      )}
      {showComment && (
        <CommentCollaborationRecord
          collaborationId={rowData?.id as string}
          recordId={rowData?.record?.id as string}
          contentId={rowData?.record?.content?.[0]?.id as string}
          onClose={() => {
            setShowComment(false);
            refreshTable();
            queryClient.invalidateQueries({
              queryKey: ["my-collaborations"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          recordStatus={rowData?.record?.statusKey}
        />
      )}
    </>
  );
};

export default CollaborationActionsComponent;
