'use client';

import { useEffect, useMemo, useState } from 'react';

interface ResumeUploadConfirmModalProps {
  file: File;
  busy?: boolean;
  onConfirm: () => void;
  onCancel: () => void;
  onChooseAnother?: () => void;
}

const formatSize = (bytes: number): string => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
};

/**
 * Shown after a résumé file is picked but BEFORE it is sent to the server.
 * Renders a local preview (PDF inline via object URL; Word docs as a file
 * card, since browsers cannot render .doc/.docx from a local blob) and asks
 * the user to confirm the selection. Nothing is uploaded until onConfirm.
 */
export function ResumeUploadConfirmModal({
  file,
  busy = false,
  onConfirm,
  onCancel,
  onChooseAnother,
}: ResumeUploadConfirmModalProps) {
  const [pdfLoading, setPdfLoading] = useState(true);

  const isPdf = /\.pdf$/i.test(file.name) || file.type === 'application/pdf';
  const isWord = /\.docx?$/i.test(file.name);

  const objectUrl = useMemo(() => (isPdf ? URL.createObjectURL(file) : null), [file, isPdf]);
  useEffect(() => {
    return () => { if (objectUrl) URL.revokeObjectURL(objectUrl); };
  }, [objectUrl]);

  return (
    <div className="fixed inset-0 z-[110] flex items-center justify-center p-3 sm:p-4" onClick={busy ? undefined : onCancel}>
      {/* Backdrop */}
      <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm" />

      {/* Panel */}
      <div
        className="relative z-10 w-full max-w-3xl max-h-[90vh] bg-white dark:bg-slate-900 rounded-none shadow-2xl flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between gap-3 px-4 sm: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 min-w-0">
            {isPdf && <i className="fa-solid fa-file-pdf text-red-500 shrink-0"></i>}
            {isWord && <i className="fa-solid fa-file-word text-blue-500 shrink-0"></i>}
            {!isPdf && !isWord && <i className="fa-solid fa-file text-slate-400 shrink-0"></i>}
            <span className="truncate">{file.name}</span>
            <span className="text-xs text-slate-400 font-normal shrink-0 hidden sm:inline">({formatSize(file.size)})</span>
          </h3>
          <button
            type="button"
            onClick={onCancel}
            disabled={busy}
            className="w-7 h-7 rounded-none text-slate-400 hover:text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-800 dark:hover:text-slate-200 flex items-center justify-center transition cursor-pointer disabled:opacity-50 shrink-0"
          >
            <i className="fa-solid fa-xmark text-sm"></i>
          </button>
        </div>

        {/* Preview area */}
        <div className="flex-1 min-h-0 relative bg-slate-50 dark:bg-slate-950">
          {isPdf && objectUrl ? (
            <div className="h-[45vh] sm:h-[55vh] relative">
              {pdfLoading && (
                <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-500 dark:text-slate-400 font-semibold tracking-wide animate-pulse">Loading preview…</p>
                </div>
              )}
              <iframe
                src={objectUrl}
                className="w-full h-full rounded-none border-none"
                title="Selected resume preview"
                onLoad={() => setPdfLoading(false)}
              />
            </div>
          ) : (
            <div className="h-[30vh] sm:h-[35vh] flex flex-col items-center justify-center text-center gap-3 p-6">
              <div className={`w-12 h-12 rounded-none flex items-center justify-center border ${isWord ? 'bg-blue-50 dark:bg-blue-950/20 text-blue-500 border-blue-100 dark:border-blue-900/30' : 'bg-amber-50 dark:bg-amber-950/20 text-amber-500 border-amber-100 dark:border-amber-900/30'}`}>
                <i className={`fa-solid ${isWord ? 'fa-file-word' : 'fa-file'} text-xl`}></i>
              </div>
              <h4 className="text-sm font-bold text-slate-800 dark:text-white break-all px-2">{file.name}</h4>
              <p className="text-xs text-slate-500 dark:text-slate-400">{formatSize(file.size)}</p>
              <p className="text-xs text-slate-500 dark:text-slate-400 max-w-md leading-relaxed">
                {isWord
                  ? 'Word documents (.doc, .docx) cannot be previewed inline before upload — please verify the file name and size above.'
                  : 'This file type cannot be previewed inline — please verify the file name and size above.'}
              </p>
            </div>
          )}
        </div>

        {/* Confirmation footer */}
        <div className="border-t border-slate-200 dark:border-slate-800 px-4 sm:px-5 py-4 shrink-0">
          <p className="text-sm font-semibold text-slate-800 dark:text-slate-100 mb-3 text-center sm:text-left">
            Is this the correct resume you want to upload?
          </p>
          <div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-2">
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                if (onChooseAnother) {
                  onChooseAnother();
                } else {
                  onCancel();
                }
              }}
              disabled={busy}
              className="px-4 py-2.5 border border-slate-200 dark:border-slate-700 text-sm font-semibold text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-800 transition cursor-pointer disabled:opacity-50"
            >
              <i className="fa-solid fa-rotate-left mr-1.5" />
              Cancel / Choose Another
            </button>
            <button
              type="button"
              onClick={onConfirm}
              disabled={busy}
              className="px-6 py-2.5 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition cursor-pointer disabled:opacity-50"
            >
              {busy ? (
                <><i className="fa-solid fa-spinner animate-spin mr-1.5" /> Uploading…</>
              ) : (
                <><i className="fa-solid fa-check mr-1.5" /> Confirm & Upload</>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
