'use client';

import { useState, useEffect } from 'react';

interface ResumePreviewModalProps {
  url: string | null;
  name: string;
  onClose: () => void;
}

export function ResumePreviewModal({ url, name, onClose }: ResumePreviewModalProps) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Get absolute URL helper
  const getAbsoluteUrl = (rawUrl: string | null): string => {
    if (!rawUrl) return '';
    if (rawUrl.startsWith('http://') || rawUrl.startsWith('https://') || rawUrl.startsWith('blob:')) return rawUrl;
    const backendBase = (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1').replace('/api/v1', '');
    if (rawUrl.startsWith('/')) {
      return `${backendBase}${rawUrl}`;
    }
    return `${backendBase}/media/${rawUrl}`;
  };

  // Get same-origin URL for iframe to avoid X-Frame-Options block
  const getSameOriginUrl = (rawUrl: string | null): string => {
    if (!rawUrl) return '';
    if (rawUrl.startsWith('blob:')) return rawUrl;
    if (rawUrl.startsWith('http://') || rawUrl.startsWith('https://')) {
      const backendBase = (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1').replace('/api/v1', '');
      if (rawUrl.startsWith(backendBase)) {
        return rawUrl.replace(backendBase, '');
      }
      return rawUrl;
    }
    if (rawUrl.startsWith('/')) {
      return rawUrl;
    }
    return `/media/${rawUrl}`;
  };

  const absoluteUrl = getAbsoluteUrl(url);
  const sameOriginUrl = getSameOriginUrl(url);
  const rawPath = url || '';

  const isWord = /\.(docx?|rtf)(\?|$)/i.test(name) || /\.(docx?|rtf)(\?|$)/i.test(rawPath) || /\.(docx?|rtf)(\?|$)/i.test(absoluteUrl);
  const isPdf = /\.pdf(\?|$)/i.test(name) || /\.pdf(\?|$)/i.test(rawPath) || /\.pdf(\?|$)/i.test(absoluteUrl) || rawPath.startsWith('blob:') || !isWord;
  const isLocal = /localhost|127\.0\.0\.1/.test(absoluteUrl);

  useEffect(() => {
    if (!absoluteUrl) {
      setError('Resume path is invalid or empty.');
      setLoading(false);
      return;
    }

    if (absoluteUrl.startsWith('blob:')) {
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    // Verify if the resume exists and is reachable
    fetch(absoluteUrl, { method: 'HEAD' })
      .then((res) => {
        if (res.status === 404) {
          setError('Resume document could not be found on the server (404).');
        }
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  }, [absoluteUrl]);

  // Define embed URL.
  let embedUrl = '';
  if (isPdf) {
    embedUrl = absoluteUrl || sameOriginUrl;
  } else if (isWord && !isLocal) {
    embedUrl = `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(absoluteUrl)}`;
  }

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in duration-200" onClick={onClose}>
      {/* Backdrop */}
      <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm" />

      {/* Modal Content */}
      <div
        className="relative z-10 w-full max-w-4xl h-[85vh] bg-white dark:bg-slate-900 rounded-none shadow-2xl flex flex-col animate-in zoom-in-95 duration-200"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-800 shrink-0">
          <h3 className="text-sm font-semibold text-[#495057] dark:text-slate-100 truncate flex items-center gap-2">
            {isPdf && <i className="fa-solid fa-file-pdf text-red-500"></i>}
            {isWord && <i className="fa-solid fa-file-word text-blue-500"></i>}
            <span>{name}</span>
          </h3>
          <div className="flex items-center gap-3">
            {absoluteUrl && (
              <>
                <a
                  href={absoluteUrl}
                  download
                  className="text-xs font-semibold text-emerald-600 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-350 transition flex items-center gap-1"
                >
                  <i className="fa-solid fa-download" />
                  <span>Download</span>
                </a>
                <a
                  href={absoluteUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="text-xs font-semibold text-[#405189] hover:text-[#364574] dark:text-indigo-400 dark:hover:text-indigo-300 transition flex items-center gap-1"
                >
                  <i className="fa-solid fa-up-right-from-square" />
                  <span>Open in Tab</span>
                </a>
              </>
            )}
            <button
              onClick={onClose}
              className="w-7 h-7 rounded-none text-slate-400 hover:text-slate-650 hover:bg-slate-100 dark:hover:bg-slate-800 dark:hover:text-slate-200 flex items-center justify-center transition cursor-pointer"
            >
              <i className="fa-solid fa-xmark text-sm"></i>
            </button>
          </div>
        </div>

        {/* Viewer Area */}
        <div className="flex-1 min-h-0 relative bg-slate-50 dark:bg-slate-950">
          {/* Loading State */}
          {loading && !error && (
            <div className="absolute inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-white/80 dark:bg-slate-900/80">
              <i className="fa-solid fa-spinner animate-spin text-3xl text-indigo-600 dark:text-indigo-400" />
              <p className="text-xs text-slate-550 dark:text-slate-400 font-semibold tracking-wide animate-pulse">Loading resume document...</p>
            </div>
          )}

          {/* Error State */}
          {error ? (
            <div className="w-full h-full flex flex-col items-center justify-center text-center gap-3 p-6 bg-white dark:bg-slate-900">
              <div className="w-12 h-12 bg-rose-50 dark:bg-rose-950/20 rounded-none flex items-center justify-center text-rose-500 border border-rose-100 dark:border-rose-900/30">
                <i className="fa-solid fa-circle-exclamation text-xl"></i>
              </div>
              <h4 className="text-sm font-bold text-slate-800 dark:text-white">Unable to Load Preview</h4>
              <p className="text-xs text-slate-500 max-w-md">{error}</p>
              {absoluteUrl && (
                <a
                  href={absoluteUrl}
                  download
                  className="mt-2 bg-[#405189] hover:bg-[#364574] text-white text-xs font-semibold px-4 py-2 rounded-none transition flex items-center gap-1.5 cursor-pointer"
                >
                  <i className="fa-solid fa-download"></i>
                  <span>Download to View</span>
                </a>
              )}
            </div>
          ) : (
            <>
              {/* Document Rendering */}
              {isPdf && absoluteUrl && (
                <iframe
                  src={embedUrl}
                  className="w-full h-full rounded-none border-none"
                  title="Resume PDF Viewer"
                  onLoad={() => setLoading(false)}
                />
              )}

              {isWord && !isLocal && absoluteUrl && (
                <iframe
                  src={embedUrl}
                  className="w-full h-full rounded-none border-none"
                  title="Resume Word Viewer"
                  onLoad={() => setLoading(false)}
                />
              )}

              {isWord && isLocal && (
                <div className="w-full h-full flex flex-col items-center justify-center text-center gap-3 p-6 bg-white dark:bg-slate-900">
                  <div className="w-12 h-12 bg-blue-50 dark:bg-blue-950/20 rounded-none flex items-center justify-center text-blue-500 border border-blue-100 dark:border-blue-900/30 animate-bounce">
                    <i className="fa-solid fa-file-word text-xl"></i>
                  </div>
                  <h4 className="text-sm font-bold text-slate-800 dark:text-white">Word Document Preview (Local)</h4>
                  <p className="text-xs text-slate-550 dark:text-slate-400 max-w-md leading-relaxed">
                    Word document previews (.doc, .docx) require a public network address for inline viewing.
                    Please download the file directly to view it, or upload the resume as a PDF.
                  </p>
                  <a
                    href={absoluteUrl}
                    download
                    className="mt-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold px-4 py-2 rounded-none transition flex items-center gap-1.5 cursor-pointer"
                  >
                    <i className="fa-solid fa-download"></i>
                    <span>Download to View</span>
                  </a>
                </div>
              )}

              {!isPdf && !isWord && (
                <div className="w-full h-full flex flex-col items-center justify-center text-center gap-3 p-6 bg-white dark:bg-slate-900">
                  <div className="w-12 h-12 bg-amber-50 dark:bg-amber-950/20 rounded-none flex items-center justify-center text-amber-500 border border-amber-100 dark:border-amber-900/30">
                    <i className="fa-solid fa-file text-xl"></i>
                  </div>
                  <h4 className="text-sm font-bold text-slate-800 dark:text-white">Preview Not Available</h4>
                  <p className="text-xs text-slate-550 dark:text-slate-400 max-w-md leading-relaxed">
                    This file format is not supported for direct inline preview.
                    Please download the document to view its contents.
                  </p>
                  {absoluteUrl && (
                    <a
                      href={absoluteUrl}
                      download
                      className="mt-2 bg-[#405189] hover:bg-[#364574] text-white text-xs font-semibold px-4 py-2 rounded-none transition flex items-center gap-1.5 cursor-pointer"
                    >
                      <i className="fa-solid fa-download"></i>
                      <span>Download File</span>
                    </a>
                  )}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
