'use client';

import { useEffect, useRef, useState } from 'react';
import JobDetailsContent from './JobDetailsContent';

interface JobDetailsModalProps {
  jobId: number | string;
  jobTitle?: string;
  isOpen: boolean;
  onClose: () => void;
  /** When provided, shows an "Edit JD" button in the header that reuses the existing edit flow. */
  onEdit?: () => void;
}

export default function JobDetailsModal({ jobId, jobTitle, isOpen, onClose, onEdit }: JobDetailsModalProps) {
  const modalRef = useRef<HTMLDivElement>(null);
  const [fetchedTitle, setFetchedTitle] = useState<string>('');
  const [jobMeta, setJobMeta] = useState<{ status?: string; jd_status?: string }>({});

  const displayTitle = jobTitle || fetchedTitle;
  const isPublished = (jobMeta.jd_status || jobMeta.status || '').toLowerCase() === 'published';

  // Close on Escape key press
  useEffect(() => {
    if (!isOpen) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  // Close on clicking outside the modal content
  const handleOutsideClick = (e: React.MouseEvent) => {
    if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div
      onClick={handleOutsideClick}
      className="fixed inset-0 z-[140] flex items-center justify-center p-4 bg-slate-950/45 dark:bg-slate-950/80 backdrop-blur-sm animate-in fade-in duration-200"
    >
      <div
        ref={modalRef}
        className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 w-full max-w-5xl h-[85vh] rounded-none shadow-2xl relative flex flex-col animate-in zoom-in duration-200 text-slate-800 dark:text-slate-100"
      >
        {/* Header with Title and Close Action */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-150 dark:border-slate-800 shrink-0 gap-4">
          <h3 className="text-sm font-bold text-slate-850 dark:text-slate-200 flex items-center gap-2 min-w-0 truncate">
            <i className="fa-solid fa-file-invoice text-[#405189] dark:text-indigo-400 shrink-0" />
            <span className="shrink-0">Job Description Viewer</span>
            {displayTitle && (
              <>
                <span className="text-slate-300 dark:text-slate-700 font-normal shrink-0">-</span>
                <span className="text-[#405189] dark:text-indigo-100 font-extrabold truncate" title={displayTitle}>
                  ({displayTitle})
                </span>
              </>
            )}
          </h3>
          <div className="flex items-center gap-2 shrink-0">
            {onEdit && (
              <button
                onClick={() => { if (!isPublished) onEdit(); }}
                disabled={isPublished}
                className={`inline-flex items-center gap-1.5 px-3 py-2 rounded-none text-xs font-bold transition ${
                  isPublished
                    ? 'text-slate-400 dark:text-slate-600 bg-slate-100 dark:bg-slate-800 cursor-not-allowed'
                    : 'text-white bg-indigo-600 hover:bg-indigo-500 cursor-pointer'
                }`}
                title={isPublished ? 'This JD is published and cannot be edited' : 'Edit this Job Description'}
              >
                <i className="fa-solid fa-pen text-[11px]"></i> Edit JD
              </button>
            )}
            <button
              onClick={onClose}
              className="w-8 h-8 rounded-none flex items-center justify-center text-slate-400 hover:text-slate-700 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
              title="Close modal (Esc)"
            >
              <i className="fa-solid fa-xmark text-sm"></i>
            </button>
          </div>
        </div>

        {/* Scrollable Content wrapper */}
        <div className="flex-1 overflow-y-auto custom-scrollbar p-6">
          <JobDetailsContent
            jobId={jobId}
            isModal={true}
            onClose={onClose}
            onJobLoaded={(j) => {
              setFetchedTitle(j?.title || '');
              setJobMeta({ status: j?.status, jd_status: j?.jd_status });
            }}
          />
        </div>
      </div>
    </div>
  );
}
