import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Spinner } from "@/shared/common/ui/sppiner";
import { X, Printer, RotateCcw } from "lucide-react";
import { toast } from "sonner";

interface PreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  pdfData: ArrayBuffer | null;
  isLoading: boolean;
  error: string | null;
  onRetry: () => void;
}

export const PreviewModal: React.FC<PreviewModalProps> = ({
  isOpen,
  onClose,
  pdfData,
  isLoading,
  error,
  onRetry,
}) => {
  const { t } = useTranslation();
  const [pdfUrl, setPdfUrl] = useState<string | null>(null);

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

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

  const handlePrint = () => {
    if (pdfUrl) {
      const printWindow = window.open(pdfUrl, "_blank");
      if (printWindow) {
        printWindow.onload = () => {
          printWindow.print();
        };
      } else {
        toast.error("Unable to open print window");
      }
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl w-full h-[90vh] flex flex-col">
        <DialogHeader className="flex flex-row items-center justify-between">
          <DialogTitle>{t("preview.title")}</DialogTitle>
          <div className="flex items-center gap-2">
            {pdfUrl && (
              <Button
                variant="outline"
                size="sm"
                onClick={handlePrint}
                className="flex items-center gap-2"
              >
                <Printer className="h-4 w-4" />
                {t("preview.print")}
              </Button>
            )}
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              className="h-8 w-8 p-0"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
        </DialogHeader>

        <div className="flex-1 flex items-center justify-center">
          {isLoading && (
            <div className="flex flex-col items-center gap-4">
              <Spinner size="large" />
              <p className="text-sm text-muted-foreground">
                {t("preview.generating")}
              </p>
            </div>
          )}

          {error && (
            <div className="flex flex-col items-center gap-4 text-center">
              <div className="text-destructive">
                <p className="font-medium">{t("preview.failed")}</p>
                <p className="text-sm text-muted-foreground mt-1">
                  {error.includes("network") || error.includes("Network")
                    ? t("preview.networkError")
                    : error}
                </p>
              </div>
              <Button
                onClick={onRetry}
                variant="outline"
                className="flex items-center gap-2"
              >
                <RotateCcw className="h-4 w-4" />
                {t("preview.retry")}
              </Button>
            </div>
          )}

          {pdfUrl && !isLoading && !error && (
            <iframe
              src={pdfUrl}
              className="w-full h-full border rounded"
              title={t("preview.title")}
            />
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
};
