import React, { useEffect, useMemo, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { useLocation, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import Loader from "@/record-management/components/Loader/loader";
import RecordDetailCard from "@/record-management/common/RecordDetailCard";
import {
  fetchLetterById,
  fetchLetterPreview,
  fetchRecordById,
  fetchRecordInstanceById,
  fetchDelegationRecordById,
} from "@/record-management/services/api/userRecordService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

interface LetterViewerProps {
  backurl: string;
  type:
    | "incoming"
    | "outgoing"
    | "internal"
    | "cc"
    | "pending"
    | "externalincoming"
    | "userRecord"
    | "collaboration"
    | "approval"
    | "delegation";
  statusKey?: string;
  id?: string;
  shouldFetchInstance: boolean;
  actions?: string;
  // Optional row payload to forward to action components (e.g. the approval
  // task object for ApproveRecordsActions, which can't be reconstructed from
  // the plain record fetch).
  actionRowData?: any;
}

const LetterViewer: React.FC<LetterViewerProps> = ({
  backurl,
  type,
  id,
  shouldFetchInstance,
  actions,
  actionRowData,
}) => {
  // ✅ Keep params immutable
  const { id: paramId } = useParams<{ id: string }>();
  const location = useLocation();
  const recordId = id || paramId;
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const status = ["Draft", "Adjustment"];

  // ✅ Determine which API to use
  // const shouldFetchInstance =
  //   type === "internal" ||
  //   type === "incoming" ||
  //   type === "externalincoming";

  // ✅ Fetch main record (for non-instance types)
  const {
    data: record,
    isLoading: isLoadingRecord,
    error: errorRecord,
  } = useQuery({
    queryKey: ["record", recordId, type],
    queryFn: () =>
      type === "delegation"
        ? fetchDelegationRecordById(recordId!)
        : fetchRecordById(recordId!),
    enabled: !shouldFetchInstance && !!recordId,
  });

  // ✅ Fetch record instance (for instance-based types)
  const {
    data: recordInstance,
    isLoading: isLoadingInstance,
    error: errorInstance,
  } = useQuery({
    queryKey: ["record-instance", recordId],
    queryFn: () => fetchRecordInstanceById(recordId!),
    enabled: shouldFetchInstance && !!recordId,
  });

  // Surface main-record fetch failures via the centralized error handler.
  // Inline <p className="text-red-600"> below is preserved.
  // record-pdf failure is intentionally not toasted — it has its own inline UX.
  const recordFetchError = errorRecord || errorInstance;
  const prevRecordErrorRef = useRef<unknown>(null);
  useEffect(() => {
    if (recordFetchError && recordFetchError !== prevRecordErrorRef.current) {
      prevRecordErrorRef.current = recordFetchError;
      handleError(recordFetchError);
    }
  }, [recordFetchError, handleError]);

  // ✅ Compute effective ID (don’t mutate)
  const effectiveRecordId = recordInstance?.id ?? recordId;
  const canFetchAttachment = shouldFetchInstance
    ? !!recordInstance?.id
    : type === "userRecord"
      ? !!record
      : !!effectiveRecordId;

  // ✅ Fetch attachment
  const {
    data: attachment,
    isLoading: isLoadingAttachment,
    error: errorAttachment,
  } = useQuery({
    queryKey: ["record-pdf", effectiveRecordId],
    queryFn: async () => {
      if (!effectiveRecordId) return null;

      if (type === "userRecord" && record) {
        if (status.includes(record.statusKey ?? "")) {
          return fetchLetterPreview(effectiveRecordId);
        } else {
          return fetchLetterById(effectiveRecordId);
        }
      }

      return fetchLetterById(effectiveRecordId);
    },
    enabled: canFetchAttachment,
    retry: false, // don’t auto-retry on 400
  });

  // ✅ Compute attachment URL
  const attachmentUrl = useMemo(() => {
    if (!attachment) return null;

    if (attachment instanceof ArrayBuffer) {
      const blob = new Blob([attachment], { type: "application/pdf" });
      return URL.createObjectURL(blob);
    }

    if (typeof attachment === "object" && "presigned" in attachment) {
      return attachment.presigned;
    }

    if (typeof attachment === "string" && attachment.startsWith("http")) {
      return attachment;
    }

    return null;
  }, [attachment]);

  // ✅ Handle loading and error messages
  let attachmentMessage: string | null = null;
  if (isLoadingAttachment) {
    attachmentMessage = "Loading record...";
  } else if (errorAttachment) {
    const err: any = errorAttachment;
    const message =
      err?.response?.data?.message || err?.message || err?.exception?.message;

    if (message === "record_final_look_not_yet_generated") {
      attachmentMessage =
        "The record is still being generated. If this takes too long, try clicking the Regenerate button. If the issue persists, please contact your administrator.";
    } else {
      attachmentMessage = "Something went wrong while fetching the record.";
    }
  }

  const isLoadingAny = shouldFetchInstance
    ? isLoadingInstance
    : isLoadingRecord;

  const activeRecord = recordInstance || record;
  const currentContent = activeRecord?.content?.[0] ?? null;
  const locationActionRowData = (
    location.state as { actionRowData?: any } | null
  )?.actionRowData;
  const effectiveActionRowData = actionRowData ?? locationActionRowData;

  return (
    <div className="w-full mx-0 font-serif">
      {isLoadingAny && <Loader />}

      {(errorRecord || errorInstance) && (
        <p className="text-red-600 text-center py-4">
          {errorRecord instanceof Error
            ? errorRecord.message
            : "Failed to load record"}
        </p>
      )}

      {activeRecord && currentContent && !isLoadingAny ? (
        <RecordDetailCard
          record={activeRecord}
          attachmentUrl={attachmentUrl}
          isDraft={activeRecord.statusKey === "Draft"}
          isLoadingAttachment={isLoadingAttachment}
          backurl={backurl}
          type={type}
          isSecured={activeRecord.isSecured}
          actions={actions}
          actionRowData={effectiveActionRowData}
        />
      ) : (
        !isLoadingAny &&
        !errorRecord && (
          <p className="text-center py-8 text-gray-500">
            {recordId ? <Loader /> : "No record selected"}
          </p>
        )
      )}
    </div>
  );
};

export default LetterViewer;
