import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { Button } from "@/shared/common/ui/button";
import { RotateCcw, FileText, Eye, Printer } from "lucide-react";
import { toast } from "sonner";
import { previewRecord } from "@/record-management/services/api/userRecordService";
import { createLetterSchema } from "@/record-management/components/userRecords/common/formSchema";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import useSettings from "../components/hooks/useSettings";
import PrintDialog from "../components/PrintDialog";

interface PreviewPageState {
  formData: any;
  files: File[];
  headers: any[];
  footers: any[];
  positionsData: any[];
  employeesData: any[];
}

interface RecordPreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  state?: PreviewPageState;
  unitId: string;
  embedded?: boolean;
}

const serializeReceiverGroup = (group: any) => ({
  prefix: group.prefix ?? "",
  suffix: group.suffix ?? "",
  receivers:
    group.receivers?.map((receiver: any) => ({
      ...receiver,
      name:
        receiver.type === "non_smart"
          ? typeof receiver.name === "string"
            ? receiver.name
            : receiver.name?.en || receiver.name?.am || ""
          : receiver.name,
    })) ?? [],
});

const RecordPreviewPage: React.FC<RecordPreviewModalProps> = ({
  isOpen,
  onClose,
  state,
  unitId,
  embedded = false,
}) => {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const [isLoading, setIsLoading] = useState(false);
  const [pdfData, setPdfData] = useState<ArrayBuffer | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [pdfUrl, setPdfUrl] = useState<string | null>(null);
  const [isPrintDialogOpen, setIsPrintDialogOpen] = useState(false);
  const {
    listAllDepartmentResponse,
    currentEmployeesResponse,
    allDepartmentUnits,
  } = useSettings();
  // Pull the unit's internal CC prefix/suffix from the unit configuration.
  // These are the BE-configured defaults that should auto-apply to the
  // trailing internal-CC group in the preview's ccList.

  useEffect(() => {
    if (!state) {
      navigate(-1);
      return;
    }
    generatePreview();
  }, []);

  useEffect(() => {
    if (pdfData) {
      const blob = new Blob([pdfData], { type: "application/pdf" });
      const url = URL.createObjectURL(blob);
      setPdfUrl(url);

      return () => {
        URL.revokeObjectURL(url);
      };
    }
  }, [pdfData]);

  const generatePreview = async () => {
    if (!state) return;

    try {
      setIsLoading(true);
      setError(null);
      setPdfData(null);

      const { formData } = state;
      const selectedLanguage =
        formData.preferredLanguage === "en" ? "en" : "am";
      const getLocalizedValue = (
        value?: string | { am?: string; en?: string } | null,
        fallback = "",
      ) => {
        if (!value) return fallback;
        if (typeof value === "string") return value || fallback;
        if (selectedLanguage === "en") {
          return value.en || value.am || fallback;
        }
        return value.am || value.en || fallback;
      };

      const getDisplayValue = (item: any) => {
        if (!item) return "";
        if (typeof item === "string") return item;
        if (typeof item.name === "string") return item.name;
        return (
          getLocalizedValue(item.name as { am?: string; en?: string }) ||
          item.label ||
          item.id ||
          ""
        );
      };

      const dedupeStrings = (items: Array<string | null | undefined>) =>
        Array.from(new Set(items.filter(Boolean) as string[]));

      const receiversList =
        formData.ReceiversList || formData.ReceiverList || [];
      const ccList = formData.ccList || [];

      // ============ FIX 1: Extract forYourReferenceList ============
      const forYourReferenceList = formData.forYourReferenceList || [];

      const groupedNonSmartReceivers: string[] =
        formData.groupedItems?.flatMap((group: any) => group.values || []) ||
        [];
      const groupedNonSmartCCReceivers: string[] =
        formData.groupedCCItems?.flatMap((group: any) => group.values || []) ||
        [];
      const groupedTreeReceivers: any[] =
        formData.groupedTreeItems?.flatMap(
          (group: any) => group.values || [],
        ) || [];
      const groupedCCTreeReceivers: any[] =
        formData.groupedCCTreeItems?.flatMap(
          (group: any) => group.values || [],
        ) || [];

      // ============ FIX 2: Extract FYR units and non-smart receivers ============
      const fyrListUnits =
        forYourReferenceList
          ?.flatMap((group: any) => group.receivers || [])
          ?.filter(
            (receiver: any) => receiver.type === "unit" && receiver.unitId,
          ) || [];
      const fyrListNonSmart =
        forYourReferenceList
          ?.flatMap((group: any) => group.receivers || [])
          ?.filter(
            (receiver: any) => receiver.type === "non_smart" && receiver.name,
          )
          ?.map((receiver: any) =>
            typeof receiver.name === "string"
              ? receiver.name
              : getLocalizedValue(receiver.name),
          ) || [];

      const receiversListUnits =
        receiversList
          ?.flatMap((group: any) => group.receivers || [])
          ?.filter(
            (receiver: any) => receiver.type === "unit" && receiver.unitId,
          ) || [];
      const receiversListNonSmart =
        receiversList
          ?.flatMap((group: any) => group.receivers || [])
          ?.filter(
            (receiver: any) => receiver.type === "non_smart" && receiver.name,
          )
          ?.map((receiver: any) =>
            typeof receiver.name === "string"
              ? receiver.name
              : getLocalizedValue(receiver.name),
          ) || [];
      const ccListUnits =
        ccList
          ?.flatMap((group: any) => group.receivers || [])
          ?.filter(
            (receiver: any) => receiver.type === "unit" && receiver.unitId,
          ) || [];
      const ccListNonSmart =
        ccList
          ?.flatMap((group: any) => group.receivers || [])
          ?.filter(
            (receiver: any) => receiver.type === "non_smart" && receiver.name,
          )
          ?.map((receiver: any) =>
            typeof receiver.name === "string"
              ? receiver.name
              : getLocalizedValue(receiver.name),
          ) || [];

      // Build internal CC units
      const internalCCUnits =
        (formData.internalCC ?? [])
          .map((id: string) =>
            allDepartmentUnits?.find((u: any) => u.id === id),
          )
          .filter((u: any) => u != null) ?? [];
      const externalCCUnits = formData.externalCC ?? [];

      const ccEmployeesResolved =
        (formData.ccEmployees ?? [])
          .map((employeePositionId: string) =>
            currentEmployeesResponse?.items?.find(
              (e: any) => e.employeePositions?.[0]?.id === employeePositionId,
            ),
          )
          .filter((e: any) => e != null) ?? [];
      const forYourReferenceUnits =
        (formData.forYourReference ?? [])
          .map((id: string) =>
            allDepartmentUnits?.find((u: any) => u.id === id),
          )
          .filter((u: any) => u != null) ?? [];

      // ============ FIX 3: Build ccTyped array including FYR ============
      const ccTyped = [
        ...internalCCUnits.map((c: any) => ({
          unitId: c.unitId,
          positionId: c.id,
          type: "internal" as const,
        })),
        ...externalCCUnits.map((c: any) => ({
          unitId: c.id,
          type: "external" as const,
        })),
        ...ccEmployeesResolved.map((c: any) => ({
          positionId: c.employeePositions?.[0]?.position?.id,
          employeePositionId: c.employeePositions?.[0]?.id,
          type: "internal" as const,
        })),
        ...forYourReferenceUnits.map((c: any) => ({
          unitId: c.unitId,
          positionId: c.id,
          type: "internal" as const,
          isForYourReference: true,
        })),
      ];

      const forYourReferenceNames =
        formData.forYourReference?.map((positionId: string) => {
          const position = listAllDepartmentResponse?.find(
            (pos: any) => pos.id === positionId || pos.key === positionId,
          );
          return getLocalizedValue(position?.name, positionId);
        }) ?? [];

      // ============ FIX 4: Build internal CC receivers including FYR from forYourReferenceList ============
      const internalCCReceiversForList: Array<{
        unitId?: string;
        positionId?: string;
        employeePositionId?: string;
        name: string;
        type: "internal";
        isForYourReference?: boolean;
      }> = [
        ...internalCCUnits.map(
          (c: {
            id?: string;
            unitId?: string;
            name?: { am?: string; en?: string };
          }) => ({
            unitId: c.unitId,
            positionId: c.id,
            name: getLocalizedValue(c.name, c.id || ""),
            type: "internal" as const,
          }),
        ),
        ...ccEmployeesResolved.map(
          (c: {
            user?: { name?: { am?: string; en?: string } };
            employeePositions?: Array<{
              id?: string;
              position?: {
                id?: string;
                name?: { am?: string; en?: string };
              };
            }>;
          }) => ({
            positionId: c.employeePositions?.[0]?.position?.id,
            employeePositionId: c.employeePositions?.[0]?.id,
            name:
              getLocalizedValue(c.user?.name) ||
              getLocalizedValue(c.employeePositions?.[0]?.position?.name) ||
              "",
            type: "internal" as const,
          }),
        ),
        ...forYourReferenceUnits.map(
          (c: {
            id?: string;
            unitId?: string;
            name?: { am?: string; en?: string };
          }) => ({
            unitId: c.unitId,
            positionId: c.id,
            name: getLocalizedValue(c.name, c.id || ""),
            type: "internal" as const,
            isForYourReference: true,
          }),
        ),
        // ============ FIX 5: Also include FYR from forYourReferenceList groups ============
        ...fyrListUnits.map((c: any) => ({
          unitId: c.unitId,
          name: getLocalizedValue(c.name, c.unitId || ""),
          type: "internal" as const,
          isForYourReference: true,
        })),
      ];

      type MirroredGroup = {
        prefix: string;
        suffix: string;
        receivers: unknown[];
      };

      // ============ FIX 6: Mirror ccList including forYourReferenceList as separate groups ============
      const baseCcListMirrored: MirroredGroup[] = (formData.ccList ?? []).map(
        (group: {
          prefix?: string;
          suffix?: string;
          receivers?: unknown[];
        }) => ({
          prefix: group.prefix ?? "",
          suffix: group.suffix ?? "",
          receivers:
            group?.receivers?.map((r: any) => {
              if (r.type === "non_smart") {
                return { ...r };
              }
              return {
                ...r,
                name: getLocalizedValue(r.name),
              };
            }) ?? [],
        }),
      );

      // ============ FIX 7: Add forYourReferenceList as mirrored groups ============
      const fyrListMirrored: MirroredGroup[] = forYourReferenceList.map(
        (group: { prefix?: string; suffix?: string; receivers?: any[] }) => ({
          prefix: group.prefix ?? "",
          suffix: group.suffix ?? "",
          receivers:
            group?.receivers?.map((r: any) => {
              if (r.type === "non_smart") {
                return {
                  ...r,
                  name:
                    typeof r.name === "string"
                      ? r.name
                      : getLocalizedValue(r.name),
                  isForYourReference: true,
                };
              }
              return {
                ...r,
                name: getLocalizedValue(r.name),
                isForYourReference: true,
              };
            }) ?? [],
        }),
      );
      const internalCcGroupPrefix = "";
      const internalCcGroupSuffix = "";

      // ============ FIX 8: Combine all CC groups (existing CC list + FYR list + internal CC) ============
      const ccListMirrored: MirroredGroup[] = [
        ...baseCcListMirrored,
        ...fyrListMirrored, // Add FYR groups
        ...(internalCCReceiversForList.length > 0
          ? [
              {
                prefix: internalCcGroupPrefix,
                suffix: internalCcGroupSuffix,
                receivers: internalCCReceiversForList,
              },
            ]
          : []),
      ];

      // Coerce null values to undefined
      const NULLABLE_STRING_FIELDS = [
        "prefix",
        "suffix",
        "ccPrefix",
        "ccSuffix",
        "recordTemplateId",
        "inReplyToIncomingInstanceId",
        "personalRemark",
        "positionPrefixId",
        "letterName",
        "subject",
        "body",
        "sincerelyText",
        "headerId",
        "footerId",
        "initiatedAs",
      ] as const;
      const sanitizedFormData: Record<string, unknown> = { ...formData };
      for (const key of NULLABLE_STRING_FIELDS) {
        if (sanitizedFormData[key] === null) {
          sanitizedFormData[key] = "";
        }
      }

      type ReceiverLike = {
        unitId?: string | null;
        name?: string | { am?: string; en?: string } | null;
        type?: string;
        [k: string]: unknown;
      };
      type GroupLike = {
        prefix?: string | null;
        suffix?: string | null;
        receivers?: ReceiverLike[] | null;
        [k: string]: unknown;
      };
      const sanitizeReceiver = (r: ReceiverLike) => {
        return {
          ...r,
          unitId: r.unitId ?? undefined,
          name:
            (typeof r.name === "string"
              ? r.name
              : getLocalizedValue(
                  r.name as { am?: string; en?: string } | null,
                )) || undefined,
          type:
            r.type === "unit" || r.type === "non_smart"
              ? r.type
              : r.unitId
                ? "unit"
                : "non_smart",
        };
      };
      const sanitizeGroups = (groups: unknown): GroupLike[] => {
        if (!Array.isArray(groups)) return [];
        return groups.map((g: GroupLike) => ({
          ...g,
          prefix: g?.prefix ?? "",
          suffix: g?.suffix ?? "",
          receivers: Array.isArray(g?.receivers)
            ? g.receivers.map(sanitizeReceiver)
            : [],
        }));
      };
      sanitizedFormData.ccList = sanitizeGroups(ccListMirrored);
      sanitizedFormData.ReceiversList = sanitizeGroups(
        sanitizedFormData.ReceiversList,
      );
      sanitizedFormData.ReceiverList = sanitizeGroups(
        sanitizedFormData.ReceiverList,
      );

      // Validate form data
      try {
        createLetterSchema.parse(sanitizedFormData);
      } catch (validationError: unknown) {
        const zErr = validationError as {
          errors?: Array<{ message?: string; path?: Array<string | number> }>;
        };
        const firstIssue = zErr.errors?.[0];
        const path = firstIssue?.path?.join(".") || "(unknown field)";
        const errorMessage = firstIssue?.message
          ? `${path}: ${firstIssue.message}`
          : t("preview.validationError");
        console.error("[RecordPreview] schema validation failed", {
          path,
          message: firstIssue?.message,
          allErrors: zErr.errors,
        });
        setError(errorMessage);
        toast.error(errorMessage);
        setIsLoading(false);
        return;
      }

      // ============ FIX 9: Build payload including forYourReferenceList ============
      const payload = {
        unitId: unitId,
        collaborators:
          formData.collaborators?.map((employeeId: string) => {
            const employee = currentEmployeesResponse?.items.find(
              (emp: any) => emp.employeePositions?.[0]?.id === employeeId,
            );
            return {
              name: getLocalizedValue(employee?.user?.name, employeeId),
            };
          }) || [],
        referenceNumber: formData.referenceNumber || undefined,
        preferredLanguage: formData.preferredLanguage || "am",
        receiverList: receiversList.map(serializeReceiverGroup),
        ccList: ccListMirrored,
        // ============ FIX 10: Include forYourReferenceList in payload ============
        forYourReferenceList: forYourReferenceList.map(serializeReceiverGroup),

        content: {
          isWithDelegateSignature: formData.isWithTeamSignature || false,
          body: formData.body || "",
          date: "",
          internalCC: [
            ...(formData.internalCC?.map((positionId: string) => {
              const position = listAllDepartmentResponse?.find(
                (pos: any) => pos.id === positionId || pos.key === positionId,
              );
              const positionName = getLocalizedValue(
                position?.name,
                positionId,
              );
              return positionName;
            }) || []),
            ...(formData.ccEmployees?.map((employeePositionId: string) => {
              const employee = currentEmployeesResponse?.items.find(
                (emp: any) =>
                  emp.employeePositions?.[0]?.id === employeePositionId,
              );
              const employeeName = getLocalizedValue(
                employee?.user?.name,
                employeePositionId,
              );
              return employeeName;
            }) || []),
            ...forYourReferenceNames,
            // ============ FIX 11: Include FYR from forYourReferenceList in internalCC ============
            ...fyrListNonSmart,
            ...fyrListUnits.map((c: any) =>
              getLocalizedValue(c.name, c.unitId),
            ),
          ],
          cc: ccTyped,
          ccList: ccListMirrored,
          nonSmartOfficeReceiverCCs: formData.nonSmartOfficeReceiverCCs ?? [],
          // ============ FIX 12: Include FYR non-smart receivers ============
          nonSmartOfficeReceiverFYRs: fyrListNonSmart,
          externalCC: dedupeStrings([
            ...(ccListUnits?.map(
              (item: { name?: string; unitId?: string }) =>
                getDisplayValue(item.name) || item.unitId || "Unknown Unit",
            ) || []),
            ...(formData.externalCC?.map((item: unknown) =>
              getDisplayValue(item),
            ) || []),
            ...(groupedCCTreeReceivers?.map((item: unknown) =>
              getDisplayValue(item),
            ) || []),
            ...(formData.nonSmartOfficeReceiverCCs || []),
            ...ccListNonSmart,
            ...groupedNonSmartCCReceivers,
          ]),

          prefixCC:
            formData.ccPrefix ||
            formData.ccList?.[0]?.prefix ||
            formData.groupedCCTreeItems?.[0]?.prefix ||
            formData.groupedCCItems?.[0]?.prefix ||
            "",
          suffixCC:
            formData.ccSuffix ||
            formData.ccList?.[0]?.suffix ||
            formData.groupedCCTreeItems?.[0]?.suffix ||
            formData.groupedCCItems?.[0]?.suffix ||
            "",
          from:
            formData.collaborators?.map((employeeId: string) => {
              const employee = currentEmployeesResponse?.items.find(
                (emp: any) => emp.employeePositions?.[0]?.id === employeeId,
              );
              return getLocalizedValue(employee?.user?.name, employeeId);
            }) || [],
          subject: formData.subject || "",
          sincerelyText: formData.sincerelyText || t("msg.sincerely"),
          to:
            formData.recordType === "external"
              ? dedupeStrings([
                  ...(receiversListUnits?.map((item: any) => {
                    return (
                      getLocalizedValue(item.name) ||
                      item.unitId ||
                      "Unknown Unit"
                    );
                  }) || []),
                  ...(formData.receivingUnitIds?.map((item: any) => {
                    if (typeof item === "string") {
                      return item;
                    }
                    const unitName =
                      getLocalizedValue(item.name) ||
                      item.name ||
                      item.label ||
                      item.id ||
                      "Unknown Unit";
                    return unitName;
                  }) || []),
                  ...(groupedTreeReceivers?.map((item: any) => {
                    if (typeof item === "string") {
                      return item;
                    }
                    return (
                      getLocalizedValue(item.name) ||
                      item.name ||
                      item.label ||
                      item.id ||
                      "Unknown Unit"
                    );
                  }) || []),
                  ...(formData.nonSmartOfficeReceivers || []),
                  ...receiversListNonSmart,
                  ...groupedNonSmartReceivers,
                ])
              : [
                  ...(formData.toPositions?.map((positionId: string) => {
                    const position = listAllDepartmentResponse?.find(
                      (pos: any) =>
                        pos.id === positionId || pos.key === positionId,
                    );
                    const positionName = getLocalizedValue(
                      position?.name,
                      positionId,
                    );
                    return positionName;
                  }) || []),
                  ...(formData.toEmployees?.map((employeeId: string) => {
                    const employee = currentEmployeesResponse?.items.find(
                      (emp: any) =>
                        emp.employeePositions?.[0]?.id === employeeId,
                    );
                    const employeeName = getLocalizedValue(
                      employee?.user?.name,
                      employeeId,
                    );
                    return employeeName;
                  }) || []),
                ],
          prefix:
            formData.prefix ||
            formData.ReceiversList?.[0]?.prefix ||
            formData.ReceiverList?.[0]?.prefix ||
            formData.groupedTreeItems?.[0]?.prefix ||
            formData.groupedItems?.[0]?.prefix ||
            "",
          suffix:
            formData.suffix ||
            formData.ReceiversList?.[0]?.suffix ||
            formData.ReceiverList?.[0]?.suffix ||
            formData.groupedTreeItems?.[0]?.suffix ||
            formData.groupedItems?.[0]?.suffix ||
            "",
          signatures: [],
          stamps: [],
          attachments: [],
        },
        header: formData.headerId
          ? (() => {
              const selectedHeader = state.headers?.find(
                (h: any) => h.id === formData.headerId,
              );
              return selectedHeader
                ? {
                    size: selectedHeader.fileInfo?.size || 28842,
                    bucket: "headers/",
                    fileName:
                      selectedHeader.fileInfo?.fileName ||
                      `headers/${formData.headerId}`,
                    contentType:
                      selectedHeader.fileInfo?.contentType || "image/jpeg",
                    originalname:
                      selectedHeader.fileInfo?.originalname || "header.jpg",
                  }
                : null;
            })()
          : null,
        footer: formData.footerId
          ? (() => {
              const selectedFooter = state.footers?.find(
                (f: any) => f.id === formData.footerId,
              );
              return selectedFooter
                ? {
                    size: selectedFooter.fileInfo?.size || 24634,
                    bucket: "footers/",
                    fileName:
                      selectedFooter.fileInfo?.fileName ||
                      `footers/${formData.footerId}`,
                    contentType:
                      selectedFooter.fileInfo?.contentType || "image/jpeg",
                    originalname:
                      selectedFooter.fileInfo?.originalname || "footer.jpg",
                  }
                : null;
            })()
          : null,
        recordType: formData.recordType || "internal",
        stamps: [],
      };

      const response = await previewRecord(payload);
      setPdfData(response);
    } catch (err: unknown) {
      const errorMessage = t("preview.error");
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  if (!state) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <p className="text-muted-foreground">{t("preview.noData")}</p>
          <Button onClick={() => navigate(-1)} className="mt-4">
            {t("common.back")}
          </Button>
        </div>
      </div>
    );
  }

  const previewContent = (
    <>
      {/* Enhanced Header */}
      <DialogHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 sm:p-6 border-b border-slate-200 bg-gradient-to-r from-primary-600 to-primary-700 text-white">
        <div className="flex items-center gap-3 mb-3 sm:mb-0">
          <div className="p-2 rounded-lg bg-white/10 backdrop-blur-sm">
            <FileText className="w-5 h-5 sm:w-6 sm:h-6" />
          </div>
          <div className="min-w-0 flex-1">
            {embedded ? (
              <h2 className="text-lg sm:text-xl font-semibold">
                {t("preview.title")}
              </h2>
            ) : (
              <DialogTitle className="text-lg sm:text-xl font-semibold">
                {t("preview.title")}
              </DialogTitle>
            )}
            <p className="text-primary-100 text-xs sm:text-sm mt-1 truncate">
              {state?.formData?.subject || "Document Preview"}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2 w-full sm:w-auto justify-end">
          <Button
            variant="ghost"
            size="sm"
            onClick={generatePreview}
            disabled={isLoading}
            className="text-white hover:bg-white/10 border border-white/20 text-xs sm:text-sm px-2 sm:px-3"
          >
            <RotateCcw
              className={`w-3 h-3 sm:w-4 sm:h-4 mr-1 sm:mr-2 ${
                isLoading ? "animate-spin" : ""
              }`}
            />
            <span className="hidden sm:inline">Refresh</span>
          </Button>
        </div>
      </DialogHeader>
      {/* Enhanced Content Area */}
      <div className="flex-1 overflow-hidden bg-slate-100 relative">
        {error && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="bg-white rounded-xl shadow-lg p-8 max-w-md mx-4 border border-red-200">
              <div className="text-center">
                <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <RotateCcw className="w-8 h-8 text-red-600" />
                </div>
                <h3 className="text-lg font-semibold text-slate-800 mb-2">
                  {t("preview.failed")}
                </h3>
                <p className="text-sm text-slate-600 mb-6">{error}</p>
                <Button
                  onClick={generatePreview}
                  className="bg-primary-600 hover:bg-primary-700 text-white"
                >
                  <RotateCcw className="w-4 h-4 mr-2" />
                  {t("preview.retry")}
                </Button>
              </div>
            </div>
          </div>
        )}

        {pdfUrl && !isLoading && !error && (
          <div className="w-full h-full p-4">
            <div className="w-full h-full bg-white rounded-lg shadow-lg border border-slate-200 overflow-hidden">
              <iframe
                src={pdfUrl}
                className="w-full h-full"
                title={t("preview.title")}
                style={{ border: "none" }}
              />
            </div>
          </div>
        )}

        {isLoading && (
          <div className="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center z-10">
            <div className="bg-white rounded-xl shadow-lg p-8 flex flex-col items-center gap-4 border border-slate-200">
              <div className="relative">
                <div className="w-16 h-16 border-4 border-primary-200 border-t-primary-600 rounded-full animate-spin"></div>
                <Eye className="w-6 h-6 text-primary-600 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2" />
              </div>
              <div className="text-center">
                <p className="text-lg font-semibold text-slate-800">
                  {t("preview.generating")}
                </p>
                <p className="text-sm text-slate-600 mt-1">
                  Please wait while we prepare your document...
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
      {/* Enhanced Footer */}
      <div className="border-t border-slate-200 bg-white px-4 sm:px-6 py-3 sm:py-4">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-3 sm:gap-0">
          <div className="flex items-center gap-2 text-xs sm:text-sm text-slate-600">
            <div
              className={`w-2 h-2 rounded-full ${
                isLoading
                  ? "bg-yellow-500 animate-pulse"
                  : error
                    ? "bg-red-500"
                    : pdfUrl
                      ? "bg-primary-500"
                      : "bg-slate-400"
              }`}
            ></div>
            <span>
              {isLoading
                ? "Generating preview..."
                : error
                  ? "Preview failed"
                  : pdfUrl
                    ? "Preview ready"
                    : "Preparing preview..."}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={() => setIsPrintDialogOpen(true)}
              disabled={!pdfUrl || isLoading}
              className="border-slate-300 hover:bg-slate-50 text-xs sm:text-sm px-3 sm:px-4"
            >
              <Printer className="w-4 h-4 mr-2" />
              {t("print.print") || "Print"}
            </Button>
            <Button
              variant="outline"
              onClick={onClose}
              className="border-slate-300 hover:bg-slate-50 text-xs sm:text-sm px-3 sm:px-4"
            >
              Close Preview
            </Button>
          </div>
        </div>
      </div>
      <PrintDialog
        isOpen={isPrintDialogOpen}
        onClose={() => setIsPrintDialogOpen(false)}
        pdfUrl={pdfUrl || ""}
        attachments={[]}
      />
    </>
  );

  if (embedded) {
    return (
      <div className="h-full w-full flex flex-col bg-gradient-to-br from-slate-50 to-white overflow-hidden">
        {previewContent}
      </div>
    );
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-[96vw] w-[96vw] h-[96vh] sm:max-w-[92vw] sm:w-[92vw] sm:h-[92vh] flex flex-col p-0 bg-gradient-to-br from-slate-50 to-white shadow-2xl border-0 rounded-xl overflow-hidden">
        {previewContent}
      </DialogContent>
    </Dialog>
  );
};

export default RecordPreviewPage;
