import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { UserPlus, Edit, Trash } from "lucide-react";
import { useNavigate } from "react-router-dom";

import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import { AssignRecordDto } from "@/record-management/dto/userRecords/usersDto";
import AssigneIncomingRecord from "./AssigneIncomingRecords";
import DeleteRecord from "./deleteRecord";

interface IncomingRecordDetailActionsProps {
  rowData: RecordDto;
  refetchTable?: () => void;
  shouldAddEditAction?: boolean;
}

const IncomingRecordDetailActions = ({
  rowData,
  refetchTable,
  shouldAddEditAction = false,
}: IncomingRecordDetailActionsProps) => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [showAssign, setShowAssign] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // Mirror the table flow: rows from the Draft / External-NonSmart tables
  // (CorrespondenceDto) always go through AssigneIncomingRecord, which uses
  // record.id as the record id and falls back to start-assignment when
  // recordBoxes is empty. The detail view only has the bare RecordDto, so we
  // wrap it into the minimum shape the modal needs and reuse whatever
  // recordBoxes the API happened to return.
  const existingRecordBoxes =
    (rowData as unknown as { recordBoxes?: any[] })?.recordBoxes ?? [];
  const assignPayload = {
    id: rowData?.id,
    record: rowData,
    recordBoxes: existingRecordBoxes,
    recordBoxId: null,
    createdAt: rowData?.createdAt ?? "",
    status: rowData?.statusKey ?? "",
    content: rowData?.content as any,
  } as unknown as AssignRecordDto;

  const nonStatus =
    rowData &&
    "nonSmartOfficeRecordStatus" in rowData &&
    rowData.nonSmartOfficeRecordStatus === "not_assigned";

  const handleSuccess = () => {
    toast.success(t("msg.successassign"));
    queryClient.invalidateQueries({ queryKey: ["record-incoming"] });
    queryClient.invalidateQueries({ queryKey: ["external-record-incoming"] });
    queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });
    queryClient.invalidateQueries({ queryKey: ["record"] });
    refetchTable?.();
    setShowAssign(false);
    navigate("/record-management/recordOfficer/incoming");
  };

  const handleEdit = () => {
    if (rowData.id) {
      navigate(`/record-management/editIncoming/${rowData.id}`);
    }
  };

  const handleDelete = () => {
    setShowDeleteDialog(true);
  };

  return (
    <>
      <div className="flex flex-wrap items-center gap-2">
        <Button
          variant={getActionButtonVariant("Assign")}
          onClick={() => setShowAssign(true)}
        >
          <UserPlus className="h-4 w-4" />
          <span>{t("userIncoming.Assign")}</span>
        </Button>

        {shouldAddEditAction && nonStatus && (
          <>
            <Button
              variant={getActionButtonVariant("Edit")}
              onClick={handleEdit}
            >
              <Edit className="h-4 w-4" />
              <span>{t("userRecord.Edit")}</span>
            </Button>

            <Button
              variant={getActionButtonVariant("Delete")}
              onClick={handleDelete}
            >
              <Trash className="h-4 w-4" />
              <span>{t("userRecord.Delete")}</span>
            </Button>
          </>
        )}
      </div>

      {showAssign && (
        <AssigneIncomingRecord
          record={assignPayload}
          isOpen={true}
          onClose={() => setShowAssign(false)}
          onSuccess={handleSuccess}
        />
      )}

      {showDeleteDialog && (
        <DeleteRecord
          recordId={rowData?.id || "0"}
          onSuccess={() => {
            setShowDeleteDialog(false);
            queryClient.invalidateQueries({
              queryKey: ["external-record-incoming"],
            });
            queryClient.invalidateQueries({ queryKey: ["dashbordReportRO"] });
            refetchTable?.();
            navigate("/record-management/recordOfficer/incoming");
          }}
          onClose={() => {
            setShowDeleteDialog(false);
          }}
        />
      )}
    </>
  );
};

export default IncomingRecordDetailActions;
