"use client";

import React from "react";
import { X } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Document, Page, pdfjs } from "react-pdf";
import "react-pdf/dist/Page/AnnotationLayer.css";
import "react-pdf/dist/Page/TextLayer.css";

// Set up pdf.js worker
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

interface PreviewResumeModalProps {
  isOpen: boolean;
  onClose: () => void;
  resumeName: string;
  resumeUrl: string;
}

export default function PreviewResumeModal({
  isOpen,
  onClose,
  resumeName,
  resumeUrl,
}: PreviewResumeModalProps) {
  const [numPages, setNumPages] = React.useState<number | null>(null);

  function onDocumentLoadSuccess({ numPages }: { numPages: number }) {
    setNumPages(numPages);
  }

  const isPdf = resumeName.toLowerCase().endsWith(".pdf");
  const isLocalhost = resumeUrl.includes("localhost") || resumeUrl.includes("127.0.0.1");

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent 
        className="sm:max-w-5xl w-[85vw] h-[85vh] flex flex-col p-0 overflow-hidden bg-white border-none rounded-2xl shadow-xl"
        showCloseButton={false}
      >
        <DialogHeader className="px-10 pt-8 pb-4 shrink-0 flex flex-row items-start justify-between bg-white relative">
          <div className="flex flex-col gap-1">
            <DialogTitle className="text-2xl font-bold text-gray-900 leading-tight">
              Preview Resume
            </DialogTitle>
            <p className="text-[14px] text-gray-600">{resumeName}</p>
          </div>
          <button
            onClick={onClose}
            className="absolute top-8 right-8 p-1 rounded-sm opacity-70 hover:opacity-100 transition-opacity outline-none"
          >
            <X className="w-6 h-6 text-gray-500 font-light" strokeWidth={1.5} />
          </button>
        </DialogHeader>

        <div className="flex-1 w-full h-full px-10 pb-10 pt-2 overflow-hidden bg-white">
          <div className="w-full h-full bg-white border border-gray-200 overflow-hidden flex flex-col items-center justify-center">
            {isPdf ? (
              <div className="w-full h-full overflow-y-auto bg-white flex flex-col items-center py-8">
                <Document
                  file={resumeUrl}
                  onLoadSuccess={onDocumentLoadSuccess}
                  loading={
                    <div className="flex flex-col items-center justify-center text-gray-500 py-10">
                      <p>Loading document...</p>
                    </div>
                  }
                  error={
                    <div className="flex flex-col items-center justify-center text-gray-500 space-y-4 py-10">
                      <p>Failed to load PDF file.</p>
                      <a
                        href={resumeUrl}
                        download={resumeName}
                        className="px-6 py-2 bg-[#ff6b00] text-white rounded-xl text-sm font-semibold hover:bg-orange-600 transition-colors"
                      >
                        Download File
                      </a>
                    </div>
                  }
                >
                  {Array.from(new Array(numPages || 0), (el, index) => (
                    <div key={`page_${index + 1}`} className="mb-8 shadow-sm border border-gray-200 bg-white max-w-full flex justify-center">
                      <Page 
                        pageNumber={index + 1} 
                        renderTextLayer={false}
                        renderAnnotationLayer={false}
                        width={800}
                        className="max-w-full [&_.react-pdf__Page__canvas]:!max-w-full [&_.react-pdf__Page__canvas]:!h-auto"
                      />
                    </div>
                  ))}
                </Document>
              </div>
            ) : !isLocalhost ? (
              <iframe
                src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
                  resumeUrl
                )}`}
                width="100%"
                height="100%"
                frameBorder="0"
                title="Document Preview"
                className="w-full h-full"
              />
            ) : (
              <div className="flex flex-col items-center justify-center h-full space-y-6 max-w-sm text-center p-8">
                <div className="w-20 h-20 bg-blue-50 rounded-2xl flex items-center justify-center">
                  <span className="text-blue-500 font-bold text-2xl">DOC</span>
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">Local Preview Unavailable</h3>
                  <p className="text-gray-500 text-sm leading-relaxed">
                    Word documents cannot be previewed on <strong>localhost</strong> because the Microsoft Cloud Viewer cannot access your local network. 
                    <br/><br/>
                    Once deployed to production, this will automatically render the document perfectly!
                  </p>
                </div>
                <a
                  href={resumeUrl}
                  download={resumeName}
                  className="px-8 py-3 bg-[#ff6b00] text-white rounded-xl text-sm font-semibold hover:bg-orange-600 transition-colors shadow-sm mt-4"
                >
                  Download for now
                </a>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
