"use client";

import type React from "react";

import { useEffect, useMemo, useRef, useState } from "react";
import {
  ChevronDown,
  ChevronLeft,
  ExternalLink,
  Maximize,
  Minimize,
  RefreshCw,
  View,
  Printer,
  X,
} from "lucide-react";
import {
  useNavigate,
  useLocation,
  useSearchParams,
  useParams,
} from "react-router-dom";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import FileList from "@/record-management/common/fileListComponent";
import ParentContainer from "@/record-management/components/recordOfficer/recordDetails/ParentAssignementContainer";
import RecordRemarksView from "@/record-management/components/recordOfficer/recordDetails/RecordRemarksView";
import PrintDialog from "@/record-management/components/PrintDialog";
import type { AttachmentFile } from "@/record-management/utils/printService";
import type {
  CollaboratorDto,
  RecordDto,
} from "../dto/userRecords/userRecordsDto";
import type { ReceiverEmployeeDto } from "../dto/approval/approvalRecordsDto";
import type { ReceiverPositionDto } from "../dto/userRecords/userRecordsDto";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { regeneratePdf } from "../services/api/userRecordService";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";
import { useAuthUser } from "../hooks/useAuthUser";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { useUserDetail } from "../components/hooks/useUserDetail";
import type { MeDto } from "@/shared/dto/user/meDto";
import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import { CommentCard } from "@/record-management/common/WorkflowCommentHistory";
import { renderStatus } from "../utils/renderDetails";
import { InternalIncomingRecordActions } from "../components/userIncoming/internalIncomingRecords/internalIncomingRecordsActions";
import { ExternalIncomingRecordActions } from "../components/userIncoming/externalIncomingRecords/externalIncomingRecordsColumns";
import { CCIncomingRecordActions } from "../components/userIncoming/ccIncomingRecords/ccIncomingRecordsColumns";
import UserRecordsActions from "../components/userRecords/userRecordsActions";
import ApproveRecordsActions from "../components/Approval/ApproveRecords/approveRecordsActions";
import CollaborationActionsComponent from "../components/collaborations/collaborationActions";
import { DelegationRecordActions } from "../components/delegation/delegationColumnAction";
import PendingRecordDetailActions from "../components/pendingRecords/pendingRecordDetailActions";
import IncomingRecordDetailActions from "../components/recordOfficer/incomingRecords/incomingRecordDetailActions";
import { IncomingRecordActions } from "../components/recordOfficer/incomingRecords/incomingRecordActions";
import { Card, CardContent } from "@/shared/common/ui/card";
import { Send } from "lucide-react";
import RemarkList from "@/record-management/common/RemarkList";
import MyApprovalRecordsActions from "../components/Approval/ApproveRecords/myApprovalRecordsActions";
import MyApprovaRecordsActions from "../components/Approval/ApproveRecords/myApprovalRecordsActions";
import { InternalIncomingRecordActionsV2 } from "../components/userIncoming/internalIncomingRecords/internalIncomingRecordsActionsV2";
import { ExternalIncomingRecordActionsV2 } from "../components/userIncoming/externalIncomingRecords/externalIncomingRecordsColumnsV2";
import { ReplySection } from "@/record-management/common/ReplySection";

type Props = {
  record: RecordDto;
  attachmentUrl?: string;
  backurl: string;
  type:
    | "incoming"
    | "outgoing"
    | "internal"
    | "cc"
    | "pending"
    | "externalincoming"
    | "userRecord"
    | "collaboration"
    | "approval"
    | "delegation";
  isDraft?: boolean;
  isSecured?: boolean;
  isLoadingAttachment?: boolean;
  errorAttachment?: any;
  attachmentMessage?: any;
  actions?: string;
  // Optional row payload for action components that need a shape the plain
  // record fetch can't supply (e.g. the approval-task instance id).
  actionRowData?: any;
};

const formatDate = (d?: string | null) =>
  d
    ? new Date(d).toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      })
    : "—";

const Box = ({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) => (
  <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-4 hover:border-primary-200 dark:hover:border-primary-600 transition-colors">
    <label className="block text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-3">
      {title}
    </label>
    {children}
  </div>
);

const Info = ({
  title,
  value,
  localizedName,
  isRecordType = false,
  infoKey,
  isReplied = false,
  replyid,
  navigate,
  letterType,
}: {
  title: string;
  value?: string | null | undefined;
  localizedName?: string;
  isRecordType?: boolean;
  infoKey?: string;
  isReplied?: boolean;
  replyid?: any;
  navigate?: any;
  letterType?: string;
}) => {
  const location = useLocation();
  const currentUrl = location.pathname + location.search;
  return (
    <Box title={title}>
      {infoKey === "status" ? (
        <div className="flex items-center gap-2">
          {renderStatus(value || "", value || "")}
        </div>
      ) : (
        <p className="text-sm text-gray-900 dark:text-gray-200 font-medium break-words">
          {isRecordType
            ? t(`nav.${value}`)
            : localizedName || value || (isReplied ? "" : "__")}
        </p>
      )}

      {isReplied &&
        Array.isArray(replyid) &&
        replyid.map((item, index) => (
          <div className="flex mt-1">
            <button
              key={item.id || index}
              onClick={() =>
                OnReplyClick(
                  currentUrl,
                  item.id || "",
                  navigate,
                  letterType || "",
                )
              }
              className="
      flex items-center gap-1.5
      px-3 py-1.5
      text-xs font-semibold text-white
      bg-primary-500
      border border-primary-600
      rounded-l-lg
      shadow-sm
      hover:bg-primary-600
      active:bg-primary-700
      transition-all duration-200
      focus:outline-none focus:ring-2 focus:ring-primary-400 focus:ring-offset-1
    ">
              <View className="w-4 h-4" />
              {t("common.viewReply")} {replyid.length > 1 && `#${index + 1}`}
            </button>

            <button
              key={`${item.id || index}-2`}
              onClick={() =>
                OnReplyClickNewtab(currentUrl, item.id || "", letterType || "")
              }
              className="
    flex items-center gap-1.5
    px-3 py-1.5
    text-xs font-semibold text-white
    bg-primary-500
    border border-primary-600
    border-l-0
    rounded-r-lg
    shadow-sm
    hover:bg-primary-600
    active:bg-primary-700
    transition-all duration-200
    focus:outline-none focus:ring-2 focus:ring-primary-400 focus:ring-offset-1
  ">
              <ExternalLink className="w-4 h-4" />
            </button>
          </div>
        ))}
    </Box>
  );
};

const ChipList = ({
  title,
  items,
  lang,
  localizedName,
}: {
  title: string;
  lang?: string | null;
  localizedName: (name: any) => string | undefined;
  items: (
    | string
    | {
        employeePosition?: { employee?: { name: { am: string; en?: string } } };
        position?: { name?: { am?: string; en?: string } };
        name?: { am?: string; en?: string } | string;
        unit?: { name?: { am?: string; en?: string } };
      }
  )[];
}) => (
  <Box title={title}>
    {items.length ? (
      <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
        {items.map((it, i) => {
          let label: string;
          if (typeof it === "string") {
            label = String(it);
          } else if (typeof it === "object" && it !== null) {
            label =
              (typeof it.name === "string"
                ? it.name
                : localizedName(it.name)) ||
              localizedName(it.position?.name) ||
              localizedName(it?.employeePosition?.employee?.name) ||
              localizedName(it?.unit?.name) ||
              "_";
          } else {
            label = "N/A";
          }
          return (
            <div
              key={i}
              className="text-sm text-gray-700 dark:text-gray-200 bg-primary-50 dark:bg-primary-900/30 border border-primary-100 dark:border-primary-800 rounded-lg px-3 py-2 break-words">
              {label}
            </div>
          );
        })}
      </div>
    ) : (
      <span className="text-sm text-gray-400 dark:text-gray-500 italic">
        None
      </span>
    )}
  </Box>
);

const ReceivingUnitChipList = ({
  title,
  items,
  lang,
  localizedName,
}: {
  title: string;
  lang?: string | null;
  localizedName: (name: any) => string | undefined;
  items: any[];
}) => (
  <Box title={title}>
    {items.length ? (
      <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
        {items.map((it, i) => {
          let label: string;

          if (typeof it === "string") {
            label = String(it);
          } else if (typeof it === "object" && it !== null) {
            label = localizedName(it.unit.name) || "-";
          } else {
            label = "N/A";
          }

          return (
            <div
              key={i}
              className="text-sm text-gray-700 dark:text-gray-200 bg-primary-50 dark:bg-primary-900/30 border border-primary-100 dark:border-primary-800 rounded-lg px-3 py-2 break-words">
              {label}
            </div>
          );
        })}
      </div>
    ) : (
      <span className="text-sm text-gray-400 dark:text-gray-500 italic">
        __
      </span>
    )}
  </Box>
);

const ReceiverEmployeeChipList = ({
  title,
  items,
  lang,
  localizedName,
}: {
  title: string;
  items: ReceiverEmployeeDto[];
  localizedName: (name: any) => string | undefined;
  lang: string | null;
}) => (
  <Box title={title}>
    {items.length ? (
      <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
        {items.map((it, i) => {
          const name = it?.employeePosition?.employee?.name;
          return (
            <div
              key={i}
              className="text-sm text-gray-700 dark:text-gray-200 bg-primary-50 dark:bg-primary-900/30 border border-primary-100 dark:border-primary-800 rounded-lg px-3 py-2 break-words">
              {localizedName(name) || "N/A"}
            </div>
          );
        })}
      </div>
    ) : (
      <span className="text-sm text-gray-400 dark:text-gray-500 italic">
        None
      </span>
    )}
  </Box>
);

const ReceiverPositionChipList = ({
  title,
  items,
  lang,
  localizedName,
}: {
  title: string;
  lang?: string | null;
  items: ReceiverPositionDto[];
  localizedName: (name: any) => string | undefined;
}) => (
  <Box title={title}>
    {items.length ? (
      <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
        {items.map((it, i) => {
          const name = it?.position?.name;
          return (
            <div
              key={i}
              className="text-sm text-gray-700 dark:text-gray-200 bg-primary-50 dark:bg-primary-900/30 border border-primary-100 dark:border-primary-800 rounded-lg px-3 py-2 break-words">
              {localizedName(name) || "-"}
            </div>
          );
        })}
      </div>
    ) : (
      <span className="text-sm text-gray-400 dark:text-gray-500 italic">
        None
      </span>
    )}
  </Box>
);

const CollaborationChipList = ({
  title,
  items,
  lang,
  localizedName,
}: {
  title: string;
  items: CollaboratorDto[];
  lang: string | null;
  localizedName: (name: any) => string | undefined;
}) => (
  <Box title={title}>
    {items.length ? (
      <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
        {items.map((it, i) => {
          const name = it?.employeePosition?.employee.name;
          return (
            <div
              key={i}
              className="text-sm text-gray-700 dark:text-gray-200 bg-primary-50 dark:bg-primary-900/30 border border-primary-100 dark:border-primary-800 rounded-lg px-3 py-2 break-words">
              {localizedName(name) || "N/A"}
            </div>
          );
        })}
      </div>
    ) : (
      <span className="text-sm text-gray-400 dark:text-gray-500 italic">
        None
      </span>
    )}
  </Box>
);
const OnReplyClick = (
  backurl: any,
  id: string,
  navigate: any,
  letterType: string,
) => {
  if (letterType === "outgoing") {
    navigate(`/record-management/userRecords/viewRecord/${id}`, {
      state: { backurl: backurl, type: "userRecord" },
    });
  } else if (letterType === "internal" || letterType === "internal_memo") {
    navigate(`/record-management/viewIncoming/internal/${id}`, {
      state: { backurl: backurl, type: letterType },
    });
  } else {
    navigate(`/record-management/viewIncoming/incoming/${id}`, {
      state: { backurl: backurl, type: letterType },
    });
  }
};
const OnReplyClickNewtab = (backurl: any, id: string, letterType: string) => {
  let url = "";

  if (letterType === "outgoing") {
    url = `/record-management/userRecords/viewRecord/${id}`;
  } else if (letterType === "internal" || letterType === "internal_memo") {
    url = `/record-management/viewIncoming/internal/${id}`;
  } else {
    url = `/record-management/viewIncoming/incoming/${id}`;
  }

  // Append state as query parameters since window.open doesn't support state
  const params = new URLSearchParams();
  if (backurl) params.set("backurl", backurl);
  if (letterType) params.set("type", letterType);

  const finalUrl = params.toString() ? `${url}?${params.toString()}` : url;

  window.open(finalUrl, "_blank");
};

type NonSmartReceiverLike = {
  name?: string;
  value?: string;
  isCc?: boolean;
  isCC?: boolean;
  isForYourReference?: boolean;
};

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
};

export default function RecordDetailCard({
  record,
  attachmentUrl,
  backurl,
  type,
  isDraft,
  isLoadingAttachment,
  errorAttachment,
  isSecured,
  actions,
  actionRowData,
}: Props) {
  const navigate = useNavigate();
  const { id: routeId, type: incomingDetailType } = useParams<{
    id?: string;
    type?: string;
  }>();
  const [isOpen, setIsOpen] = useState(true);
  const [isPrintDialogOpen, setIsPrintDialogOpen] = useState(false);
  const [isAddReplyModalOpen, setIsAddReplyModalOpen] = useState(false);
  const [isFullScreenOpen, setIsFullScreenOpen] = useState(false);
  const fullscreenContainerRef = useRef<HTMLDivElement>(null);
  const { t, i18n } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const lang = i18n.language;
  const queryClient = useQueryClient();
  const content = record.content[0];
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const { receivingUnits } = record;
  const localizedName = useLocalizedName();
  const unitId = userDetails?.employee?.[0]?.unitId ?? "";
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const canRecordBeEditedOnWorkflow =
    unitConfigData?.data?.items?.[0]?.canRecordBeEditedOnWorkflow ?? false;
  const canRecordBeEditedByCollaborators =
    unitConfigData?.data?.items?.[0]?.canRecordBeEditedByCollaborators ?? false;
  const { receiverPositions, receiverEmployees, ccs } = content;
  const { internalCC, externalCC, forYourReferenceInternal, forYourReferenceExternal } = useMemo(() => {
    const result: {
      internalCC: any[];
      externalCC: any[];
      forYourReferenceInternal: any[];
      forYourReferenceExternal: any[];
    } = {
      internalCC: [],
      externalCC: [],
      forYourReferenceInternal: [],
      forYourReferenceExternal: [],
    };

    (ccs || []).forEach((cc: any) => {
      const { type, isForYourReference } = cc;
      if (type === "internal") {
        if (isForYourReference) {
          result.forYourReferenceInternal.push(cc);
        } else {
          result.internalCC.push(cc);
        }
      } else if (type === "external") {
        if (isForYourReference) {
          result.forYourReferenceExternal.push(cc);
        } else {
          result.externalCC.push(cc);
        }
      }
    });

    return result;
  }, [ccs]);
  const legacyNonSmartReceivers = useMemo<NonSmartReceiverLike[]>(
    () =>
      (content.nonSmartReceivers as NonSmartReceiverLike[] | undefined) || [],
    [content.nonSmartReceivers],
  );

  const normalizeNonSmartName = (item: NonSmartReceiverLike | string) => {
    if (typeof item === "string") return item;
    return item?.name || item?.value || "";
  };

  const legacyNonSmartCC = useMemo(
    () =>
      legacyNonSmartReceivers
        .filter((item) => Boolean(item?.isCc ?? item?.isCC))
        .map((item) => normalizeNonSmartName(item))
        .filter(Boolean),
    [legacyNonSmartReceivers],
  );

  const legacyNonSmartFYR = useMemo(
    () =>
      legacyNonSmartReceivers
        .filter((item) => item?.isForYourReference === true)
        .map((item) => normalizeNonSmartName(item))
        .filter(Boolean) as string[],
    [legacyNonSmartReceivers],
  );

  const legacyNonSmartTo = useMemo(
    () =>
      legacyNonSmartReceivers
        .filter((item) => !Boolean(item?.isCc ?? item?.isCC))
        .map((item) => normalizeNonSmartName(item))
        .filter(Boolean),
    [legacyNonSmartReceivers],
  );

  const nonSmartOfficeReceivers = useMemo(
    () =>
      Array.from(
        new Set([
          ...(content.nonSmartOfficeReceivers || []),
          ...legacyNonSmartTo,
        ]),
      ),
    [content.nonSmartOfficeReceivers, legacyNonSmartTo],
  );

  const nonSmartOfficeCC = useMemo(
    () =>
      Array.from(
        new Set([
          ...(content.nonSmartOfficeReceiverCCs || []),
          ...legacyNonSmartCC,
        ]),
      ),
    [content.nonSmartOfficeReceiverCCs, legacyNonSmartCC],
  );

  const combinedReceivers = [
    ...(receivingUnits || []),
    ...nonSmartOfficeReceivers,
  ];

  const combinedCC = [...(externalCC || []), ...nonSmartOfficeCC];
  const combinedCCInternal = [...(internalCC || [])];

  const incomingInstanceActionRow = useMemo(() => {
    const fromIncomingInstances = Array.isArray(record?.incomingInstances)
      ? record.incomingInstances[0]
      : record?.incomingInstances;

    if (fromIncomingInstances) return fromIncomingInstances;
    if (record?.incomingInstance) return record.incomingInstance;

    // Fallback for detail routes that are opened by incoming-instance id.
    if (
      routeId &&
      ["incoming", "internal", "externalincoming"].includes(type)
    ) {
      return {
        id: routeId,
        recordId: record.id,
        status: record.statusKey,
        record,
      };
    }

    return undefined;
  }, [record, routeId, type]);
  const fallbackIncomingInstance =
    actionRowData?.lastIncomingInstance ||
    actionRowData?.incomingInstances ||
    incomingInstanceActionRow;
  const detailCommentSource =
    typeof actionRowData?.comment === "string" && actionRowData.comment.trim()
      ? actionRowData
      : fallbackIncomingInstance;
  const detailComment =
    typeof detailCommentSource?.comment === "string"
      ? detailCommentSource.comment.trim()
      : "";
  const detailCommentCreatedAt = detailCommentSource?.createdAt || "";
  const actionAssignerName = actionRowData?.delegateAssigner?.employee?.name;
  const actionAssignerDelegateeName =
    actionRowData?.delegateAssignee?.employee?.name;
  const actionEmployeeName = actionRowData?.employeePosition?.employee?.name;
  const fallbackAssignerName =
    fallbackIncomingInstance?.assigner?.employee?.name;
  const fallbackAssignerDelegatorName =
    fallbackIncomingInstance?.assigner?.delegator?.employee?.name;
  const fallbackEmployeeName = fallbackIncomingInstance?.employee?.name;

  const resolveDetailCommentAssignerName = () => {
    const nameSources = [
      {
        type: "actionAssigner",
        name: actionAssignerName,
        delegateeName: actionAssignerDelegateeName,
      },
      {
        type: "actionEmployee",
        name: actionEmployeeName,
        delegateeName: undefined,
      },
      {
        type: "fallbackAssigner",
        name: fallbackAssignerName,
        delegateeName: fallbackAssignerDelegatorName,
      },
      {
        type: "fallbackEmployee",
        name: fallbackEmployeeName,
        delegateeName: undefined,
      },
    ] as const;

    for (const source of nameSources) {
      const resolvedName = localizedName(source.name);
      const rawName = source.name?.en || source.name?.am;

      const resolvedDelegateeName = localizedName(source.delegateeName);
      if (!resolvedName && !rawName) {
        continue;
      }

      switch (source.type) {
        case "actionAssigner":
          return resolvedDelegateeName
            ? `${resolvedDelegateeName} (${t("viewDetail.for")} ${
                resolvedName || rawName
              })`
            : resolvedName || rawName;
        case "actionEmployee":
          return resolvedName || rawName;
        case "fallbackAssigner":
          return resolvedDelegateeName
            ? `${resolvedDelegateeName} (${t("viewDetail.for")} ${
                resolvedName || rawName
              })`
            : resolvedName || rawName;
        case "fallbackEmployee":
          return resolvedName || rawName;
        default:
          break;
      }
    }

    return t("common.unknownUser", "Unknown user");
  };

  const detailCommentAssignerName = resolveDetailCommentAssignerName();
  const mappedIncomingInstances =
    fallbackIncomingInstance && fallbackIncomingInstance.length > 0
      ? fallbackIncomingInstance
          ?.map((i: any) => {
            const actionAssignerDelegateeName = localizedName(
              i?.delegateAssignee?.employee?.name,
            );
            const resolvedName = localizedName(i?.assigner?.employee?.name);

            const assignerName = actionAssignerDelegateeName
              ? `${actionAssignerDelegateeName} (${t("viewDetail.for")} ${resolvedName})`
              : resolvedName;

            return {
              amharicCreatedAt: i.amharicCreatedAt,
              comment: i.comment,
              assignerName: assignerName,
              createdAt: i.createdAt,
            };
          })
          // Deduplicate: keep first occurrence of assignerName + createdAt/amharicCreatedAt
          .filter((item: any, index: any, self: any[]) => {
            const key = `${item.assignerName}|${item.createdAt || item.amharicCreatedAt}`;
            const firstIndex = self.findIndex(
              (x) =>
                `${x.assignerName}|${x.createdAt || x.amharicCreatedAt}` ===
                key,
            );
            return item?.comment && index === firstIndex;
          })
      : undefined;
  const openFull = () => {
    if (!attachmentUrl) return;
    setIsFullScreenOpen(true);
    // requestFullscreen must be called synchronously inside a user-gesture handler
    requestAnimationFrame(() => {
      fullscreenContainerRef.current?.requestFullscreen?.().catch(() => {});
    });
  };

  const closeFullScreen = () => {
    setIsFullScreenOpen(false);
    if (document.fullscreenElement) {
      document.exitFullscreen?.().catch(() => {});
    }
  };

  useEffect(() => {
    const onFullscreenChange = () => {
      if (!document.fullscreenElement) {
        setIsFullScreenOpen(false);
      }
    };
    document.addEventListener("fullscreenchange", onFullscreenChange);
    return () => document.removeEventListener("fullscreenchange", onFullscreenChange);
  }, []);
  const { mutate: regeneratePdfMutation, isPending: isRegenerating } =
    useMutation({
      mutationFn: async () => {
        if (!record.id) throw new Error("Record ID is missing");
        await regeneratePdf(record.id);
      },
      onSuccess: () => {
        toast.success(t("msg.pdfRegenerated"));
        queryClient.invalidateQueries();
      },
      onError: (error) => {
        handleError(error);
      },
    });

  const refreshDetailData = () => {
    const queryIds = [routeId, record.id].filter(Boolean) as string[];

    queryIds.forEach((id) => {
      queryClient.invalidateQueries({ queryKey: ["record-instance", id] });
      queryClient.invalidateQueries({ queryKey: ["record", id] });
      queryClient.invalidateQueries({ queryKey: ["record-pdf", id] });
    });

    queryClient.invalidateQueries({ queryKey: ["incoming-instances"] });
    queryClient.invalidateQueries({ queryKey: ["external-incoming"] });
    queryClient.invalidateQueries({ queryKey: ["incoming-cc"] });
    queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
  };
  const metaBoxes = [
    <Info
      key="recType"
      title={t("convert.recordType")}
      value={record.recordTypeKey}
      isRecordType={true}
    />,
    record.recordTypeKey !== "external" && (
      <ReceiverPositionChipList
        key="recvDept"
        title={t("viewDetail.receivingDepartments")}
        items={receiverPositions}
        lang={lang}
        localizedName={localizedName}
      />
    ),
    record.recordTypeKey === "external" && (
      <ReceivingUnitChipList
        key="recvOrgs"
        title={t("viewDetail.receivingOrganizations")}
        items={combinedReceivers}
        lang={lang}
        localizedName={localizedName}
      />
    ),
    record.recordTypeKey !== "external" && (
      <ReceiverEmployeeChipList
        key="recvEmp"
        title={t("viewDetail.receivingUserEmployees")}
        items={receiverEmployees}
        lang={lang}
        localizedName={localizedName}
      />
    ),

    record.recordTypeKey === "non_smart_user" && (
      <>
        <Info
          key="sendBur"
          title={t("viewDetail.sendingBureau")}
          value={record.metadata.organizationName.am}
          localizedName={localizedName(record.metadata.organizationName)}
        />
        <Info
          key="letterNo"
          title={t("viewDetail.letterNumber")}
          value={record.letterNumber}
        />
        <Info
          key="deliveredBy"
          title={t("viewDetail.deliveredBy")}
          value={
            record.metadata?.deliveredBy?.en || record.metadata?.deliveredBy?.am
          }
        />
      </>
    ),
    record.recordTypeKey !== "non_smart_user" && (
      <>
        <Info
          key="sendDept"
          title={t("viewDetail.sendingDepartment")}
          value={record.initiator?.position?.name?.am}
          localizedName={localizedName(record.initiator?.position?.name)}
        />
        <Info
          key="sendEmp"
          title={t("viewDetail.sendingEmployee")}
          value={
            record.delegateInitiator?.employee?.name?.am ||
            record.initiator?.employee?.name?.am
          }
          localizedName={
            record.delegateInitiator
              ? `${localizedName(record.delegateInitiator?.employee?.name)} (${t("viewDetail.for")} ${localizedName(
                  record.initiator?.employee?.name,
                )})`
              : localizedName(record.initiator?.employee?.name)
          }
        />
      </>
    ),
    (record.statusKey === "Dispatched" ||
      ["incoming", "internal", "cc", "outgoing"].includes(type)) && (
      <Info
        key="refNo"
        title={t("viewDetail.referenceNumber")}
        value={record.referenceNumber}
      />
    ),
    ["incoming", "internal", "cc", "outgoing", "pending"].includes(type) && (
      <Info
        key="sentDate"
        title={t("viewDetail.sentDate")}
        value={
          lang === "en"
            ? formatDate(record.dispatchedDate)
            : record.amharicDispatchedDate
        }
      />
    ),
    record.initiationType === "team" && (
      <CollaborationChipList
        key="collaborators"
        title={t("viewDetail.collaborators")}
        items={record.collaborators}
        lang={lang}
        localizedName={localizedName}
      />
    ),
    <Info
      key="subject"
      title={t("viewDetail.subject")}
      value={content.subject}
    />,
    <Info
      key="letterName"
      title={t("viewDetail.fileName")}
      value={record.letterName ?? "____"}
    />,
    <ChipList
      key="externalCC"
      title={t("viewDetail.externalCcOrganizations")}
      items={combinedCC}
      lang={lang}
      localizedName={localizedName}
    />,
    <ChipList
      key="internalCC"
      title={t("viewDetail.internalCcDepartments")}
      items={combinedCCInternal}
      lang={lang}
      localizedName={localizedName}
    />,
    (forYourReferenceExternal.length > 0 || legacyNonSmartFYR.length > 0) && (
      <ChipList
        key="forYourReferenceExternal"
        title={t("addRecord.forYourReferenceExternal")}
        items={[...forYourReferenceExternal, ...legacyNonSmartFYR]}
        lang={lang}
        localizedName={localizedName}
      />
    ),
    forYourReferenceInternal.length > 0 && (
      <ChipList
        key="forYourReferenceInternal"
        title={t("addRecord.forYourReferenceInternal")}
        items={forYourReferenceInternal}
        lang={lang}
        localizedName={localizedName}
      />
    ),
    <Info
      key="status"
      title={t("userIncoming.Status")}
      value={incomingInstanceActionRow?.status || record.statusKey}
      infoKey="status"
    />,

    incomingInstanceActionRow?.status === "replied" && (
      <Info
        key="seestatus"
        title={t("userIncoming.ViewReplyLetterDetails")}
        value={""}
        infoKey="seestatus"
        isReplied={incomingInstanceActionRow?.status === "replied"}
        replyid={incomingInstanceActionRow?.replyRecords || []}
        navigate={navigate}
        letterType="outgoing"
      />
    ),
    Boolean(record?.inReplyToIncomingInstanceId) && (
      <Info
        key="seestatus"
        title={t("userIncoming.ViewReplyLetterDetails")}
        value={""}
        infoKey="seestatus"
        isReplied={Boolean(record?.inReplyToIncomingInstanceId)}
        replyid={[{ id: record?.inReplyToIncomingInstanceId }]}
        navigate={navigate}
        letterType={record.recordTypeKey}
      />
    ),
    <Info
      key="isReply"
      title={t("userIncoming.isReplyLetter")}
      value={record?.inReplyToIncomingInstanceId ? "yes" : "no"}
      infoKey="status"
    />,
  ].filter(Boolean);
  const isRecordOfficer = permissionKeys.includes("can:dispatchRecords");

  const refreshReplies = () => {
    const queryIds = [routeId, record.id].filter(Boolean) as string[];
    queryIds.forEach((id) => {
      queryClient.invalidateQueries({ queryKey: ["record-instance", id] });
      queryClient.invalidateQueries({ queryKey: ["record", id] });
    });
  };
  const [searchParamsUrl, setSearchParamsUrl] = useSearchParams();
  const initialView = searchParamsUrl.get("view") || "self";
  const isSelf = initialView === "self";

  const renderActions = () => {
    switch (actions) {
      // case "OutgoingRecordActions":
      //   return (
      //     <OutgoingRecordActions
      //       rowData={{ ...incomingInstanceActionRow, record: record }}
      //       pageIndex={Number(searchParamsUrl.get("page") || 1)}
      //     />
      //   );
      case "MyApprovaRecordsActions":
        return (
          <MyApprovaRecordsActions
            rowData={actionRowData as any}
            fromTable={false}
          />
        );
      case "InternalIncomingRecordActions":
        return (
          <InternalIncomingRecordActionsV2
            rowData={{
              ...incomingInstanceActionRow,
              record: record,
              ...actionRowData,
            }}
            refetchTable={refreshDetailData}
            fromTable={false}
            isSelf={isSelf}
          />
        );
      case "ExternalIncomingRecordActions":
        return (
          <ExternalIncomingRecordActionsV2
            rowData={{
              ...incomingInstanceActionRow,
              record: record,
              ...actionRowData,
            }}
            refetchTable={refreshDetailData}
            fromTable={false}
            isSelf={isSelf}
          />
        );
      case "CCIncomingRecordActions":
        return (
          <CCIncomingRecordActions
            rowData={record as any}
            refetch={refreshDetailData}
            isTable={false}
            isSelf={isSelf}
            calledFrom="recordDetail"
          />
        );
      case "UserRecordsActions":
        return (
          <UserRecordsActions
            rowData={record}
            refetchTable={refreshDetailData}
            fromTable={false}
            isSelf={isSelf}
          />
        );
      case "ApproveRecordsActions":
        return (
          <ApproveRecordsActions
            rowData={actionRowData ?? record}
            refetchTable={refreshDetailData}
            fromTable={false}
            canRecordBeEditedOnWorkflow={canRecordBeEditedOnWorkflow}
          />
        );
      case "CollaborationActionsComponent":
        return actionRowData ? (
          <CollaborationActionsComponent
            rowData={actionRowData}
            refreshTable={refreshDetailData}
            fromTable={false}
            showViewDetailButton={false}
            canRecordBeEditedByCollaborators={canRecordBeEditedByCollaborators}
          />
        ) : null;
      case "DelegationRecordActions":
        return actionRowData ? (
          <DelegationRecordActions
            rowData={actionRowData}
            refetchTable={refreshDetailData}
            type={actionRowData.delegationType ?? "delegator"}
            fromTable={false}
          />
        ) : null;
      case "PendingRecordDetailActions":
        return (
          <PendingRecordDetailActions
            recordId={record.id}
            canROReturn={Boolean(actionRowData?.canROReturn)}
            backToTable={actionRowData?.backToTable ?? backurl}
          />
        );
      case "IncomingRecordDetailActions":
        return (
          <IncomingRecordDetailActions
            rowData={actionRowData}
            refetchTable={refreshDetailData}
            shouldAddEditAction={true}
          />
        );
      case "IncomingRecordActions":
        return (
          <IncomingRecordActions
            rowData={actionRowData ?? record}
            refetchTable={refreshDetailData}
            shouldAddEditAction={
              incomingDetailType === "draft" || record.statusKey === "Draft"
            }
            type={incomingDetailType}
            pageIndex={Number(searchParamsUrl.get("page") || 1)}
            fromTable={false}
          />
        );
      default:
        return null;
    }
  };
  const actionsContent = renderActions();
  const isFinalLookGenerated = record?.isFinalLookGenerated ?? false;

  return (
    <div className="w-full max-w-none space-y-6 dark:bg-gray-900 p-6 rounded-lg">
      <div className="flex items-center">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => navigate(backurl)}
          className="flex items-center text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200">
          <ChevronLeft className="h-4 w-4" />
          {t("common.back")}
        </Button>
      </div>
      <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
        {t("viewDetail.recordDetail")}
      </h2>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {metaBoxes}
      </div>
      {(detailComment || mappedIncomingInstances?.length > 0) &&
        ["incoming", "internal", "externalincoming", "delegation"].includes(
          type,
        ) && (
          <CommentCard
            key="incomingComment"
            createdAt={detailCommentCreatedAt}
            comment={detailComment}
            assignerName={detailCommentAssignerName}
            commentSection={mappedIncomingInstances}
            variant={type === "delegation" ? "secondary" : "info"}
          />
        )}
      {["incoming", "internal", "externalincoming"].includes(type) && (
        <RemarkList
          instanceIds={[
            fallbackIncomingInstance && fallbackIncomingInstance?.length > 0
              ? fallbackIncomingInstance[0].id
              : fallbackIncomingInstance?.id,
          ].filter(Boolean)}
        />
      )}
      {!isSecured || (isSecured && !isRecordOfficer) ? (
        <div className="w-full">
          <div
            className="flex items-center justify-between w-full cursor-pointer rounded-xl border border-gray-200 dark:border-gray-700 px-5 py-4 bg-white dark:bg-gray-800 hover:border-primary-300 dark:hover:border-primary-600 hover:bg-primary-50/30 dark:hover:bg-primary-900/20 transition-all"
            onClick={() => setIsOpen(!isOpen)}>
            <span className="font-semibold text-gray-900 dark:text-white">
              {t("viewDetail.letterPreview")}
            </span>
            <div className="flex items-center gap-2 text-sm font-medium text-primary-600 dark:text-primary-400">
              {t("viewDetail.view")}
              <ChevronDown
                className={`h-5 w-5 transition-transform ${
                  isOpen ? "rotate-180" : ""
                }`}
              />
            </div>
          </div>

          {isOpen && (
            <div className="mt-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-3 sm:p-5">
              {/* Header */}
              <div className="flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center mb-4">
                <p className="text-gray-900 dark:text-white font-semibold text-sm sm:text-base">
                  {t("viewDetail.letterPreview")}
                </p>

                {/* Action Buttons */}
                <div className="grid grid-cols-1 sm:flex gap-2 sm:gap-3 w-full sm:w-auto">
                  <button
                    className="
                        flex items-center justify-center
                        px-3 sm:px-4 py-2
                        text-sm font-medium
                        text-white
                        bg-primary-600 hover:bg-primary-700
                        dark:bg-primary-700 dark:hover:bg-primary-600
                        rounded-lg transition-all duration-200
                        disabled:opacity-50
                        w-full sm:w-auto
                        border border-primary-700 dark:border-primary-600
                      "
                    onClick={() => regeneratePdfMutation()}
                    disabled={isRegenerating || isLoadingAttachment}>
                    <RefreshCw
                      className={`h-4 w-4 mr-2 ${
                        isRegenerating ? "animate-spin" : ""
                      }`}
                    />

                    <span className="truncate">
                      {isRegenerating
                        ? t("viewDetail.regeneratingPdf")
                        : t("viewDetail.regeneratePdf")}
                    </span>
                  </button>

                  <button
                    className="
          flex items-center justify-center
          px-3 sm:px-4 py-2
          text-sm font-medium
          text-white
          bg-primary-600 hover:bg-primary-700
          dark:bg-primary-700 dark:hover:bg-primary-600
          rounded-lg transition-all duration-200
          disabled:opacity-50
          w-full sm:w-auto
          border border-primary-700 dark:border-primary-600
        "
                    onClick={() => setIsPrintDialogOpen(true)}
                    disabled={!attachmentUrl}>
                    <Printer className="h-4 w-4 mr-2 shrink-0" />
                    <span>{t("print.print") || "Print"}</span>
                  </button>

                  <button
                    className="
          flex items-center justify-center
          px-3 sm:px-4 py-2
          text-sm font-medium
          text-white
          bg-primary-600 hover:bg-primary-700
          dark:bg-primary-700 dark:hover:bg-primary-600
          rounded-lg transition-all duration-200
          disabled:opacity-50
          w-full sm:w-auto
          border border-primary-700 dark:border-primary-600
        "
                    onClick={openFull}
                    disabled={!attachmentUrl}>
                    <Maximize className="h-4 w-4 mr-2 shrink-0" />
                    <span>{t("viewDetail.fullScreen")}</span>
                  </button>
                </div>
              </div>

              {/* PDF Preview */}
              {attachmentUrl ? (
                <div className="overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700">
                  <iframe
                    src={attachmentUrl}
                    title="PDF Preview"
                    className="
          w-full
          h-[400px]
          sm:h-[600px]
          md:h-[800px]
          lg:h-[900px]
          bg-white
        "
                  />
                </div>
              ) : (
                <div
                  className="
        h-[180px] sm:h-[220px]
        flex flex-col items-center justify-center
        bg-gray-50 dark:bg-gray-900
        border-2 border-dashed
        border-gray-200 dark:border-gray-700
        rounded-lg
        text-gray-500 dark:text-gray-400
        px-4 text-center
      ">
                  {isLoadingAttachment || isRegenerating ? (
                    <p className="text-gray-600 dark:text-gray-400 flex items-center gap-2 text-sm sm:text-base">
                      <span className="animate-spin rounded-full h-4 w-4 border-t-2 border-primary-600 dark:border-primary-400"></span>

                      {t("viewDetail.loading")}
                    </p>
                  ) : (
                    <p className="text-gray-600 dark:text-gray-400 text-sm sm:text-base">
                      {t("viewDetail.noPreview")}
                    </p>
                  )}
                </div>
              )}
            </div>
          )}
        </div>
      ) : (
        <div className="w-full p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-xl text-yellow-800 dark:text-yellow-300 text-sm">
          {t("viewDetail.securedRecordMessage")}
        </div>
      )}
      <div className="space-y-4">
        {!isSecured || (isSecured && !isRecordOfficer) ? (
          <Box title={t("viewDetail.attachments")}>
            <FileList
              attachments={content.recordAttachments ?? []}
              showDelete={false}
            />
          </Box>
        ) : (
          <div className="w-full p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-xl text-yellow-800 dark:text-yellow-300 text-sm">
            {t("viewDetail.securedAttachmentMessage")}
          </div>
        )}

        {[
          "",
          "",
          "collaboration",
          "outgoing",
          "pending",
          "approval",
          "userRecord",
        ].includes(type) && (
          <RecordRemarksView recordId={record.id} error={""} />
        )}
        {record.recordTypeKey === "external" &&
          record.statusKey === "Dispatched" && (
            <ReplySection
              recordId={record.id}
              replies={record.replies ?? []}
              isRecordOfficer={isRecordOfficer}
              onRefresh={refreshReplies}
              isAddOpen={isAddReplyModalOpen}
              onCloseAdd={() => setIsAddReplyModalOpen(false)}
            />
          )}

        <Box title={t("userIncoming.Actions")}>
          <div className="flex flex-wrap gap-3">
            {actionsContent}
            {record.recordTypeKey === "external" && type === "outgoing" && (
              <Button
                variant={getActionButtonVariant("reply")}
                onClick={() => setIsAddReplyModalOpen(true)}>
                <Send className="h-4 w-4 mr-2" />
                {t("common.addReply", "Add Reply")}
              </Button>
            )}
            {!actionsContent &&
              !(record.recordTypeKey === "external" && type === "outgoing") && (
                <p className="text-sm text-gray-500 dark:text-gray-400 italic">
                  {t("userIncoming.noActionsAvailable", {
                    defaultValue: "No actions available for this record.",
                  })}
                </p>
              )}
          </div>
        </Box>

        <ParentContainer
          recordId={record.id}
          recordTitle=""
          recordType={record.recordTypeKey}
          subject={content.subject}
          createdDate={record.createdAt}
          referenceNumber={record.referenceNumber || ""}
          showStat={true}
        />
        <div className="flex justify-end pt-2">
          <button
            type="button"
            className="flex items-center bg-gray-700 hover:bg-gray-800 dark:bg-gray-600 dark:hover:bg-gray-700 text-white px-5 py-2.5 rounded-lg font-medium transition-colors"
            onClick={() => navigate(backurl)}>
            <ChevronLeft className="h-5 w-5 mr-2" />
            {t("viewDetail.back")}
          </button>
        </div>
      </div>
      <PrintDialog
        isOpen={isPrintDialogOpen}
        onClose={() => setIsPrintDialogOpen(false)}
        pdfUrl={attachmentUrl || ""}
        attachments={(() => {
          const mapped =
            content.recordAttachments?.map((att: any) => {
              // Check if there's a sealed PDF version of the attachment
              const hasSealedPdf =
                att.sealedFileInfo &&
                att.sealedFileInfo.contentType === "application/pdf";

              const mappedAttachment = {
                id: att.id || att.itemId,
                name:
                  att.fileInfo?.originalname ||
                  att.fileInfo?.fileName ||
                  att.name,
                // Use sealed PDF if available, otherwise use presigned URL
                url: hasSealedPdf
                  ? `http://minio-dev.license.aafda.gov.et/smart-office-dev/${att.sealedFileInfo.bucket}${att.sealedFileInfo.fileName}`
                  : att.presigned || att.url,
                fileType: hasSealedPdf
                  ? "application/pdf"
                  : att.fileInfo?.contentType ||
                    att.fileInfo?.type ||
                    "application/octet-stream",
                size: hasSealedPdf
                  ? att.sealedFileInfo.size
                  : att.fileInfo?.size || att.length || 0,
              };

              return mappedAttachment;
            }) || [];

          return mapped;
        })()}
      />

      {isFullScreenOpen && (
        <div
          ref={fullscreenContainerRef}
          className="fixed inset-0 z-9999 flex flex-col bg-black"
        >
          <div className="flex items-center justify-between px-4 py-2 bg-gray-900 text-white shrink-0">
            <div className="flex items-center gap-2 text-sm font-medium">
              <Minimize className="h-4 w-4" />
              {t("viewDetail.fullScreen")}
            </div>
            <button
              type="button"
              onClick={closeFullScreen}
              className="rounded p-1 hover:bg-gray-700 transition-colors"
              aria-label="Close full screen"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
          <iframe
            src={attachmentUrl}
            title="PDF Full Screen"
            className="flex-1 w-full border-0"
            allowFullScreen
          />
        </div>
      )}
    </div>
  );
}
