import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchApprovalTasks } from "@/record-management/services/api/approvalService";
import {
  SearchCheck,
  Banknote,
  FilePenLine,
  EllipsisVertical,
  CheckCircle2,
  SquarePen,
} from "lucide-react";
import { useNavigate } from "react-router-dom";

import RejectRecord from "../approve/rejectRecord";
import AcceptRecord from "@/record-management/components/Approval/approve/AcceptRecord";
import AdjustRecord from "../approve/AdjustRecord";
import { useUserDetail } from "@/record-management/components/hooks/useUserDetail";
import ApproveRecordPage from "../approve/approveRecordPage";
import { useTranslation } from "react-i18next";
import { PendingApprovalDto } from "@/record-management/dto/approval/approvalRecordsDto";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { MeDto } from "@/shared/dto/user/meDto";
import { useQueryClient } from "@tanstack/react-query";
import UnderReviewRecord from "../approve/UnderReviewRecord";
import IncomingInstanceDetail from "../../userIncoming/IncomingInstanceDetail";
interface UserRecordProps {
  rowData: any;
  refetchTable?: () => void; // Optional refetch function
  pageIndex?: number;
  fromTable: boolean;
  canRecordBeEditedOnWorkflow?: boolean;
  // When provided, the Approve modal is owned by the parent (TasksTable).
  // The row delegates the click upward instead of mounting the modal in
  // its own state. This prevents row remounts from killing the modal.
  onApproveClick?: (row: any) => void;
}

const ApproveRecordsActions: React.FC<UserRecordProps> = ({
  rowData,
  refetchTable,
  pageIndex,
  fromTable,
  canRecordBeEditedOnWorkflow = false,
  onApproveClick,
}) => {
  const [showAcceptDialog, setShowAcceptDialog] = useState(false);
  const [showAdjustDialog, setAdjustDialog] = useState(false);
  const [showRejectDialog, setShowRejectDialog] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showApprove, setShowApprove] = useState<boolean>(false);
  const [showReview, setShowReview] = useState<boolean>(false);

  const { userDetails } = useAuthUser();

  const queryClient = useQueryClient();
  const { checkHaveParent, permissionKeys } = useUserDetail(
    userDetails as MeDto,
  );
  const sendInternal = permissionKeys.includes("can:sendInternalRecordToRo");
  const sendInternalMemo = permissionKeys.includes("can:dispatchInternalMemo");
  const sendExternal = permissionKeys.includes("can:sendExternalRecordToRo");

  // The detail page hands us a flat RecordDto. In that shape, `rowData.id` is
  // the record id — NOT the workflow instance id the mutations expect, which
  // is why every action returned 400 instance_not_found. Look up the matching
  // approval task by record id so the detail page acts on the same row shape
  // the table uses.

  const hasTaskShape = !!rowData?.record?.id;
  const recordIdForLookup: string | undefined = hasTaskShape
    ? rowData?.record?.id
    : rowData?.id;

  const { data: lookupResp } = useQuery({
    queryKey: ["approvalTaskByRecord", recordIdForLookup],
    queryFn: () => fetchApprovalTasks({ take: 1000 }),
    enabled: !fromTable && !hasTaskShape && !!recordIdForLookup,
    staleTime: 30_000,
  });

  const lookupTask = useMemo(() => {
    const items: any[] = (lookupResp as any)?.items ?? [];
    if (!Array.isArray(items)) return null;
    return items.find((t: any) => t?.record?.id === recordIdForLookup) ?? null;
  }, [lookupResp, recordIdForLookup]);

  // Effective row: in table mode trust the prop; in detail mode prefer the
  // task-shaped lookup result so .id is the workflow instance id.
  const effectiveRowData: any =
    fromTable || hasTaskShape ? rowData : (lookupTask ?? rowData);
  const taskResolved = fromTable || hasTaskShape || !!lookupTask;

  const onReviewStatus = effectiveRowData?.onReview ?? false;
  const effectiveRecordTypeKey =
    effectiveRowData?.record?.recordTypeKey ?? effectiveRowData?.recordTypeKey;
  const { t } = useTranslation();

  const navigate = useNavigate();
  const approveVissible = permissionKeys.includes("can:sendToRO");

  const acceptVisible = checkHaveParent !== null;
  const handleViewDetails = () => {
    setDropdownOpen(false);
    navigate(
      `/record-management/viewApproval/${rowData?.record.id}/?page=${pageIndex}`,
      {
        // The approval-task shape (with task id, status, nested .record) isn't
        // recoverable from a record id alone, so hand it to the detail page so
        // action buttons there can act on the correct workflow instance.
        state: { approvalRow: rowData },
      },
    );
  };

  const openAcceptDialog = (e: Event) => {
    e.preventDefault();
    setDropdownOpen(false);
    setShowAcceptDialog(true);
  };

  const openAdjustDialog = (e: Event) => {
    e.preventDefault();
    setDropdownOpen(false);
    setAdjustDialog(true);
  };

  const openRejectDialog = (e: Event) => {
    e.preventDefault();
    setDropdownOpen(false);
    setShowRejectDialog(true);
  };

  // Accept both Radix's `Event` (from DropdownMenuItem onSelect) and
  // React's MouseEvent (from <Button onClick>) so the same handler is
  // safe to wire to both call sites.
  const handleApproval = (e: Event | React.MouseEvent) => {
    e.preventDefault();
    setDropdownOpen(false);
    if (onApproveClick) {
      // Modal is hoisted to TasksTable — let it own the open state so the
      // modal survives any row remount.
      onApproveClick(effectiveRowData);
    } else {
      setShowApprove(true);
    }
  };
  const handleReview = (e: Event | React.MouseEvent) => {
    e.preventDefault();
    setDropdownOpen(false);
    setShowReview(true);
  };

  const handleEditClick = () => {
    setDropdownOpen(false);
    // `?from=approval` keeps the sidebar from auto-highlighting Outgoing
    // (the edit route lives under /userRecords/) and lets editUserRecord
    // resolve the fallback return URL when location.state is missing.
    navigate(
      `/record-management/userRecords/editUserRecord/${rowData?.record?.id}?from=approval`,
      {
        state: {
          returnUrl: "/record-management/approval",
          recordId: rowData?.record?.id,
        },
      },
    );
  };
  const outgoingInstance = rowData?.outgoingHistories?.[0];

  const isActiveStatus = effectiveRowData?.status === "active";
  const canEditRecord = isActiveStatus && canRecordBeEditedOnWorkflow;
  const canShowWorkflowActions =
    effectiveRowData?.status !== ("Draft" as string) ||
    rowData?.action === "send_back";
  const canApproveRecord =
    (approveVissible &&
      sendExternal &&
      effectiveRecordTypeKey === "external") ||
    (approveVissible &&
      sendInternal &&
      effectiveRecordTypeKey === "internal") ||
    (approveVissible &&
      sendInternalMemo &&
      effectiveRecordTypeKey === "internal_memo");
  const hasInlineActions =
    (canEditRecord || canShowWorkflowActions) &&
    outgoingInstance?.action !== "send_back" &&
    outgoingInstance?.action !== "send_to_ro" &&
    outgoingInstance?.action !== "approve" &&
    outgoingInstance?.action !== "reject";
  return (
    <>
      {fromTable ? (
        <div className="flex flex-wrap gap-2 items-center justify-start">
          <Button
            variant={"viewDetail"}
            onClick={handleViewDetails}
            className="min-w-[110px] text-sm sm:text-base"
          >
            {t("ApprovalPage.View Detail")}
          </Button>

          <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
                aria-haspopup="menu"
                aria-expanded={dropdownOpen}
              >
                <EllipsisVertical className="h-4 w-4" />
                <span className="sr-only">
                  {" "}
                  {t("ApprovalPage.Open actions menu")}
                </span>
              </Button>
            </DropdownMenuTrigger>

            <DropdownMenuContent
              align="end"
              className="w-[200px] sm:w-[220px]"
              onInteractOutside={(e) => {
                const target = e.target as HTMLElement;
                if (!target.closest('[role="dialog"]')) {
                  setDropdownOpen(false);
                }
              }}
            >
              <DropdownMenuLabel className="text-sm sm:text-base">
                {t("ApprovalPage.Actions")}
              </DropdownMenuLabel>

              {/* Show Edit for Draft status */}
              {canEditRecord && (
                <DropdownMenuItem
                  onSelect={handleEditClick}
                  className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                >
                  <SquarePen className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                  {t("userRecord.Edit")}
                </DropdownMenuItem>
              )}

              {/* Only show these if NOT Approved */}
              {canShowWorkflowActions && (
                <>
                  {acceptVisible && (
                    <DropdownMenuItem
                      onSelect={openAcceptDialog}
                      className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                    >
                      <SearchCheck className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                      {t("statusBar.acceptForward")}
                    </DropdownMenuItem>
                  )}
                  <DropdownMenuItem
                    onSelect={openRejectDialog}
                    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>
                  {!onReviewStatus && (
                    <DropdownMenuItem
                      onSelect={handleReview}
                      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.Under Review")}
                    </DropdownMenuItem>
                  )}

                  <DropdownMenuItem
                    onSelect={openAdjustDialog}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                  >
                    <FilePenLine className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                    {t("statusBar.Adjust")}
                  </DropdownMenuItem>
                  {canApproveRecord && (
                    <DropdownMenuItem
                      onSelect={handleApproval}
                      className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                    >
                      <CheckCircle2 className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                      {t("statusBar.Approve")}
                    </DropdownMenuItem>
                  )}
                  {(rowData?.record?.statusKey === "Dispatched" ||
                    (rowData?.record?.recordTypeKey === "internal_memo" &&
                      rowData?.record?.statusKey === "Approved")) && (
                    <IncomingInstanceDetail
                      instanceId={rowData?.record?.id as string}
                      instanceType={"outgoing"}
                      rowData={rowData}
                    />
                  )}
                </>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
          {(rowData?.record?.statusKey === "Dispatched" ||
            (rowData?.record?.recordTypeKey === "internal_memo" &&
              rowData?.record?.statusKey === "Approved")) && (
            <IncomingInstanceDetail
              instanceId={rowData?.record?.id as string}
              instanceType={"outgoing"}
              rowData={rowData}
            />
          )}
        </div>
      ) : (
        <>
          {canEditRecord && (
            <div className="flex flex-wrap gap-2">
              <Button
                variant={getActionButtonVariant("Edit")}
                onClick={handleEditClick}
              >
                <SquarePen className="h-4 w-4" />
                <span>{t("userRecord.Edit")}</span>
              </Button>
            </div>
          )}
          {hasInlineActions && (
            <div className="flex flex-wrap gap-2">
              {canShowWorkflowActions && acceptVisible && (
                <Button
                  variant={getActionButtonVariant("Accept and Forward")}
                  onClick={(e) => openAcceptDialog(e as any)}
                >
                  <SearchCheck className="h-4 w-4" />
                  <span>{t("statusBar.acceptForward")}</span>
                </Button>
              )}

              {canShowWorkflowActions && (
                <Button
                  variant={getActionButtonVariant("Reject")}
                  onClick={(e) => openRejectDialog(e as any)}
                >
                  <Banknote className="h-4 w-4" />
                  <span>{t("statusBar.Reject")}</span>
                </Button>
              )}

              {canShowWorkflowActions && !onReviewStatus && (
                <Button
                  variant={getActionButtonVariant("Under Review")}
                  onClick={handleReview}
                >
                  <Banknote className="h-4 w-4" />
                  <span>{t("statusBar.Under Review")}</span>
                </Button>
              )}

              {canShowWorkflowActions && (
                <Button
                  variant={getActionButtonVariant("Adjustment")}
                  onClick={(e) => openAdjustDialog(e as any)}
                >
                  <FilePenLine className="h-4 w-4" />
                  <span>{t("statusBar.Adjust")}</span>
                </Button>
              )}

              {canShowWorkflowActions && canApproveRecord && (
                <Button
                  variant={getActionButtonVariant("Approve")}
                  onClick={handleApproval}
                >
                  <CheckCircle2 className="h-4 w-4" />
                  <span>{t("statusBar.Approve")}</span>
                </Button>
              )}
            </div>
          )}
          {(rowData?.record?.statusKey === "Dispatched" ||
            (rowData?.record?.recordTypeKey === "internal_memo" &&
              rowData?.record?.statusKey === "Approved")) && (
            <IncomingInstanceDetail
              instanceId={rowData?.record?.id as string}
              instanceType={"outgoing"}
              rowData={rowData}
              fromTable={false}
            />
          )}
          {!hasInlineActions && (
            <p className="text-sm text-gray-500 dark:text-gray-400 italic">
              {t("userIncoming.noActionsAvailable", {
                defaultValue: "No actions available for this record.",
              })}
            </p>
          )}
        </>
      )}
      {/* Modals — all driven off effectiveRowData so the workflow instance id
          is correct in both table and detail-page modes. */}
      {showAcceptDialog && (
        <AcceptRecord
          record={effectiveRowData}
          onClose={() => {
            setShowAcceptDialog(false);
            refetchTable && refetchTable();
            queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          onSuccess={() => {
            setShowAcceptDialog(false);
            navigate(`/record-management/approval`);
          }}
        />
      )}
      {showReview && (
        <UnderReviewRecord
          recordId={effectiveRowData?.id}
          onClose={() => {
            setShowReview(false);
            refetchTable && refetchTable();
            queryClient.invalidateQueries({ queryKey: ["reviewRecord"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          onSuccess={() => {
            setShowReview(false);
            navigate(`/record-management/approval`);
          }}
        />
      )}
      {showAdjustDialog && (
        <AdjustRecord
          record={effectiveRowData as PendingApprovalDto}
          onClose={() => {
            setAdjustDialog(false);
            refetchTable && refetchTable();
            queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          onSuccess={() => {
            setAdjustDialog(false);
            navigate(`/record-management/approval`);
          }}
        />
      )}

      {showRejectDialog && (
        <RejectRecord
          record={effectiveRowData}
          onClose={() => {
            setShowRejectDialog(false);
            refetchTable && refetchTable();
            queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          onSuccess={() => {
            setShowRejectDialog(false);
            navigate(`/record-management/approval`);
          }}
        />
      )}
      {showApprove && (
        <ApproveRecordPage
          recordId={effectiveRowData?.record?.id ?? effectiveRowData?.id}
          recordTypeKey={
            effectiveRowData?.record?.recordTypeKey ??
            effectiveRowData?.recordTypeKey
          }
          isWithTeamSignature={
            effectiveRowData?.record?.isWithTeamSignature ??
            effectiveRowData?.isWithTeamSignature
          }
          onSuccess={() => {
            setShowApprove(false);
            navigate(`/record-management/approval`);
          }}
          open={showApprove}
          onClose={() => {
            setShowApprove(false);
            refetchTable && refetchTable();
            queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
            queryClient.invalidateQueries({ queryKey: ["pendingRecords"] });
            queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
          }}
          preferredLanguage={
            effectiveRowData?.record?.preferredLanguage ??
            effectiveRowData?.preferredLanguage
          }
        />
      )}
    </>
  );
};

export default ApproveRecordsActions;
