import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Edit, Eye, OctagonAlert, MoreVertical, Trash2 } from "lucide-react";
import { useState } from "react";
// import AssigneRecord from "@/components/userIncoming/internalIncomingRecords/AssigneRecord";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { DelegatePositionDto } from "@/record-management/dto/delegation/delegationDto";
import { useLocalizedName } from "@/shared/common/localizedName";
import { CommentCard } from "@/record-management/common/WorkflowCommentHistory";
import DeleteDelegation from "./deleteDelegation";
import { formatAmharicDateTime } from "@/record-management/services/dateService";
import dayjs from "dayjs";

interface IncomingRecordActionsProps {
  rowData: DelegatePositionDto;
  refetchTable?: () => void; // Optional callback to refetch table data
  type: "delegator" | "delegatee";
  fromTable?: boolean;
}

export const getDelegationActionState = (
  rowData: DelegatePositionDto,
  type: "delegator" | "delegatee",
) => {
  const isExpired = rowData.endDate
    ? dayjs(rowData.endDate).isBefore(dayjs())
    : false;
  const canEditDelegation =
    !isExpired &&
    (rowData.delegationLetter?.statusKey === "Approved" ||
      rowData.delegationLetter?.statusKey === "Adjustment" ||
      rowData.delegationLetter?.statusKey === "Draft");
  const canManageDelegation = rowData.isCurrent && type === "delegator";

  return {
    isExpired,
    canEditDelegation,
    canManageDelegation,
  };
};

export function DelegationRecordActions({
  rowData,
  refetchTable,
  type,
  fromTable = true,
}: IncomingRecordActionsProps) {
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showTerminationDialog, setShowTerminationDialog] = useState(false);
  const navigate = useNavigate();
  const { t } = useTranslation();
  const localizeName = useLocalizedName();
  const { canEditDelegation, canManageDelegation } = getDelegationActionState(
    rowData,
    type,
  );
  const terminationReason = rowData?.terminationReason ?? null;
  const hasTermination = !!terminationReason;
  const terminatedEmployeeName =
    (rowData?.terminationReason?.terminatorEmployeePosition?.employee?.name &&
      (localizeName(
        rowData.terminationReason.terminatorEmployeePosition.employee.name,
      ) ||
        rowData.terminationReason.terminatorEmployeePosition.employee.name.en ||
        rowData.terminationReason.terminatorEmployeePosition.employee.name
          .am)) ||
    t("common.unknownUser", "Unknown user");
  const handleEditClick = () => {
    setDropdownOpen(false);
    navigate(`/record-management/editDelegation/${rowData?.id}`, {
      state: { delegation: rowData },
    });
  };
  const handleViewDetails = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    setDropdownOpen(false);
    navigate(
      `/record-management/viewDelegationLetter/${rowData?.delegationLetter.id}`,
      {
        state: {
          delegation: rowData,
          delegationType: type,
        },
      },
    );
  };
  const handleDelete = () => {
    setDropdownOpen(false);
    setShowDeleteDialog(true);
  };
  return (
    <>
      {fromTable ? (
        <>
          {rowData.delegationLetter ? (
            <Button
              variant="viewDetail"
              className="min-w-[110px]"
              onClick={(e: any) => handleViewDetails(e)}
            >
              {t("delegation.viewLetter")}
            </Button>
          ) : hasTermination ? (
            <Button
              variant="viewDetail"
              className="min-w-[110px] inline-flex items-center gap-2"
              aria-label={t(
                "delegation.viewTerminationDetail",
                "View termination detail",
              )}
              title={t(
                "delegation.viewTerminationDetail",
                "View termination detail",
              )}
              onClick={(e) => {
                e.preventDefault();
                setShowTerminationDialog(true);
              }}
            >
              <Eye className="h-4 w-4" />
              {t("userRecord.View Detail")}
            </Button>
          ) : (
            <p className="flex items-center gap-2 text-sm font-medium text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-md px-3 py-2">
              <OctagonAlert className="h-4 w-4" />
              {t("delegation.noLetterAssigned")}
            </p>
          )}

          {canManageDelegation && (
            <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: any) => {
                  const target = e.target as HTMLElement;
                  if (!target.closest('[role="dialog"]')) {
                    setDropdownOpen(false);
                  }
                }}
              >
                <DropdownMenuLabel>{t("userRecord.Actions")}</DropdownMenuLabel>
                {canEditDelegation && (
                  <DropdownMenuItem
                    onSelect={handleEditClick}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200"
                  >
                    <Edit className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
                    <span> {t("userRecord.Edit")}</span>
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem
                  onSelect={handleDelete}
                  className="text-red-600 cursor-pointer hover:!text-red-800 !bg-transparent !transition-colors duration-200"
                >
                  <Trash2 className="mr-2 h-4 w-4 text-red-600 group-hover:text-white transition-colors duration-200" />
                  {t("userRecord.Delete")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </>
      ) : canManageDelegation ? (
        <div className="flex flex-wrap gap-2">
          {canEditDelegation && (
            <Button
              variant={getActionButtonVariant("Edit")}
              onClick={handleEditClick}
            >
              <Edit className="h-4 w-4" />
              <span>
                {t("userRecord.Edit")}
              </span>
            </Button>
          )}

          <Button
            variant={getActionButtonVariant("Delete")}
            onClick={handleDelete}
          >
            <Trash2 className="h-4 w-4" />
            <span>
              {t("userRecord.Delete")}
            </span>
          </Button>
        </div>
      ) : (
        <p className="text-sm text-gray-500 dark:text-gray-400 italic">
          {t("userIncoming.noActionsAvailable", {
            defaultValue: "No actions available for this record.",
          })}
        </p>
      )}

      {showDeleteDialog && (
        <DeleteDelegation
          delegateId={(rowData?.id as string) || "0"}
          onSuccess={() => {
            setShowDeleteDialog(false);
            if (refetchTable) {
              refetchTable(); // Call the refetch function if provided
            }
            navigate("/record-management/delegation");
          }}
          onClose={() => {
            setShowDeleteDialog(false);
            if (refetchTable) {
              refetchTable();
            }
          }}
        />
      )}

      {showTerminationDialog && terminationReason && (
        <Dialog
          open={showTerminationDialog}
          onOpenChange={setShowTerminationDialog}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>
                {t("delegation.terminationDetail", "Termination Detail")}
              </DialogTitle>
            </DialogHeader>
            <CommentCard
              createdAt={terminationReason.terminatedAt}
              amharicCreatedAt={formatAmharicDateTime(
                terminationReason.terminatedAt,
              )}
              comment={terminationReason.comment}
              assignerName={terminatedEmployeeName}
              variant="secondary"
            />
          </DialogContent>
        </Dialog>
      )}
    </>
  );
}
