import React, { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  fetchRecordById,
  regeneratePdf,
} from "@/record-management/services/api/userRecordService";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import FileList from "@/record-management/common/fileListComponent";
import {
  ChevronLeft,
  RefreshCw,
  Maximize,
  Minimize,
  Download,
  X,
  MoveLeft,
} from "lucide-react";
import { attachmentResponse } from "../hooks/useCreateExternalLetterRecord";
import { Button } from "@/shared/common/ui/button";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

interface ViewExternalRecordProps {
  itemId: string;
  onBack: () => void;
}
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-base font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-3">
      {title}
    </label>
    {children}
  </div>
);
const ViewExternalRecord: React.FC<ViewExternalRecordProps> = ({
  itemId,
  onBack,
}) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [isLoadingPdf, setIsLoadingPdf] = useState(true);

  const { handleError } = useErrorHandler(t);

  const { data: attachment, isLoading, error } = attachmentResponse(itemId);
  const { data: record, error: recordFetchError } = useQuery({
    queryKey: ["record", itemId],
    queryFn: () => fetchRecordById(itemId!),
    enabled: !!itemId,
  });

  // Surface main-record fetch failures via the centralized error handler.
  // attachment failure stays silent — the existing inline UI already covers it.
  const prevRecordErrorRef = useRef<unknown>(null);
  useEffect(() => {
    if (recordFetchError && recordFetchError !== prevRecordErrorRef.current) {
      prevRecordErrorRef.current = recordFetchError;
      handleError(recordFetchError);
    }
  }, [recordFetchError, handleError]);
  const attachmentUrl = useMemo(() => {
    if (!attachment) return null;

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

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

    // Handle direct URL case
    if (typeof attachment === "string") {
      return attachment.startsWith("http") ? attachment : null;
    }

    return null;
  }, [attachment]);

  useEffect(() => {
    return () => {
      // Clean up blob URLs
      if (attachmentUrl && attachmentUrl.startsWith("blob:")) {
        URL.revokeObjectURL(attachmentUrl);
      }
    };
  }, [attachmentUrl]);

  const { mutate: regeneratePdfMutation, isPending: isRegenerating } =
    useMutation({
      mutationFn: async () => {
        if (!itemId) throw new Error("Record ID is missing");
        await regeneratePdf(itemId);
      },
      onSuccess: () => {
        toast.success(t("msg.pdfRegenerated"));
        queryClient.invalidateQueries({
          queryKey: ["attachmentResponse", itemId],
        });
      },
      onError: (error) => {
        handleError(error);
      },
    });

  const handleDownload = () => {
    if (!attachmentUrl) return;

    const link = document.createElement("a");
    link.href = attachmentUrl;
    link.download = `document-${itemId}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const openFullScreen = () => {
    setIsFullScreen(true);
  };

  const closeFullScreen = () => {
    setIsFullScreen(false);
  };

  const handleIframeLoad = () => {
    setIsLoadingPdf(false);
  };

  // Handle escape key to exit fullscreen
  useEffect(() => {
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape" && isFullScreen) {
        closeFullScreen();
      }
    };

    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isFullScreen]);

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">{t("loading")}...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="bg-red-100 rounded-full p-3 w-12 h-12 flex items-center justify-center mx-auto mb-4">
            <X className="h-6 w-6 text-red-600" />
          </div>
          <h3 className="text-lg font-medium text-red-800 mb-2">
            {t("error.failedToLoadPdf")}
          </h3>
          <p className="text-red-600 mb-4">{error.message}</p>
          <div className="flex">
            <Button
              onClick={onBack}
              size="sm" // or use className for custom sizing
              className="bg-gray-600 text-sm px-1 py-1 w-[100px] hover:bg-gray-700"
            >
              <MoveLeft className="w-4 h-4" />
              {t("common.back")}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      {/* Normal View */}
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center mb-6">
            <div className="flex">
              <Button
                onClick={onBack}
                size="sm" // or use className for custom sizing
                className="bg-gray-600 text-sm px-1 py-1 w-[100px] hover:bg-gray-700"
              >
                <MoveLeft className="w-4 h-4" />
                {t("common.back")}
              </Button>
            </div>

            <div className="flex gap-3">
              <button
                onClick={() => regeneratePdfMutation()}
                disabled={isRegenerating || !attachmentUrl}
                className="flex items-center px-4 py-2 bg-white border border-gray-300 rounded-lg shadow-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
              >
                <RefreshCw
                  className={`h-4 w-4 mr-2 ${
                    isRegenerating ? "animate-spin" : ""
                  }`}
                />
                {t("viewDetail.regeneratePdf")}
              </button>

              <button
                onClick={handleDownload}
                disabled={!attachmentUrl}
                className="flex items-center px-4 py-2 bg-white border border-gray-300 rounded-lg shadow-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
              >
                <Download className="h-4 w-4 mr-2" />
                {t("userRecord.Download")}
              </button>

              <button
                onClick={openFullScreen}
                disabled={!attachmentUrl}
                className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg shadow-sm hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
              >
                <Maximize className="h-4 w-4 mr-2" />
                {t("viewDetail.fullScreen")}
              </button>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
            {attachmentUrl ? (
              <div className="relative">
                {isLoadingPdf && (
                  <div className="absolute inset-0 flex items-center justify-center bg-gray-50">
                    <div className="text-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
                      <p className="text-gray-600 dark:text-gray-400 flex items-center gap-2">
                        <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>
                    </div>
                  </div>
                )}
                <iframe
                  src={attachmentUrl}
                  title="PDF Preview"
                  width="100%"
                  height="800px"
                  style={{ border: "none" }}
                  onLoad={handleIframeLoad}
                  className={
                    isLoadingPdf
                      ? "opacity-0"
                      : "opacity-100 transition-opacity duration-300"
                  }
                />
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center h-96 bg-gray-50">
                <div className="bg-gray-100 rounded-full p-4 w-16 h-16 flex items-center justify-center mb-4">
                  <X className="h-8 w-8 text-gray-400" />
                </div>
                <h3 className="text-lg font-medium text-gray-900 mb-2">
                  {t("noPdfAvailable")}
                </h3>
                <p className="text-gray-500 text-center max-w-md">
                  {t("noPdfAvailableDescription") ||
                    "The PDF document is not available. You can try regenerating it using the button above."}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
      {/* Full Screen Overlay */}
      {isFullScreen && attachmentUrl && (
        <div className="fixed inset-0 bg-black z-50 flex flex-col">
          {/* Header */}
          <div className="bg-gray-900 text-white px-6 py-4 flex justify-between items-center">
            <div className="flex items-center">
              <span className="font-medium">Document Preview</span>
            </div>
            <div className="flex items-center gap-3">
              <button
                onClick={handleDownload}
                className="flex items-center px-3 py-2 bg-gray-700 rounded-lg hover:bg-gray-600 transition-colors duration-200"
                title="Download"
              >
                <Download className="h-4 w-4" />
              </button>
              <button
                onClick={closeFullScreen}
                className="flex items-center px-3 py-2 bg-gray-700 rounded-lg hover:bg-gray-600 transition-colors duration-200"
                title="Exit Fullscreen"
              >
                <Minimize className="h-4 w-4" />
              </button>
            </div>
          </div>

          {/* PDF Container */}
          <div className="flex-1 bg-gray-800">
            <iframe
              src={attachmentUrl}
              title="PDF Preview - Full Screen"
              width="100%"
              height="100%"
              style={{ border: "none" }}
            />
          </div>

          {/* Footer */}
          <div className="bg-gray-900 text-white px-6 py-3 text-sm text-center">
            <p>Press ESC to exit fullscreen mode</p>
          </div>
        </div>
      )}
      <div className="mt-3">
        <Box title={t("viewDetail.attachments")}>
          <FileList
            attachments={record?.content[0]?.recordAttachments ?? []}
            showDelete={false}
          />
        </Box>
      </div>
    </>
  );
};

export default ViewExternalRecord;
