import React from 'react';
import { CurrentView, ResearchPaper } from '../types';
import { SECTION_IDS, RESEARCH_PAPER_DETAIL_CONTENT } from '../constants'; // Removed mockResearchPapers
import Button from './Button';
import { ArrowUturnLeftIcon, ChevronRightIcon } from './icons';
import ItemDetailNavigation from './ItemDetailNavigation';
import ResearchCard from './ResearchCard';
import GalleryComponent from './GalleryComponent'; // Import GalleryComponent

interface ResearchPaperDetailProps {
  itemId: string;
  allResearchPapers: ResearchPaper[]; 
  setCurrentView: (view: CurrentView) => void;
  setSelectedItemId: (id: string | null) => void;
}

const ResearchPaperDetail: React.FC<ResearchPaperDetailProps> = ({ itemId, allResearchPapers, setCurrentView, setSelectedItemId }) => {
  const paper = allResearchPapers.find(p => p.id === itemId);

  const handleBackClick = () => {
    setCurrentView('researchAll');
    setSelectedItemId(null);
  };

  const handleNavigateItem = (newItemId: string) => {
    setSelectedItemId(newItemId);
  };
  
  const handleShowAllKeepReading = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    setCurrentView('researchAll');
    setSelectedItemId(null);
  };

  if (!paper) {
    return (
      <section id={SECTION_IDS.researchPaperDetailPage} className="py-16 md:py-24 min-h-screen flex items-center justify-center">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <h1 className="text-2xl font-semibold text-slate-700">{RESEARCH_PAPER_DETAIL_CONTENT.notFoundTitle}</h1>
          <Button onClick={handleBackClick} leftIcon={<ArrowUturnLeftIcon />} className="mt-8">
            {RESEARCH_PAPER_DETAIL_CONTENT.backButtonText}
          </Button>
        </div>
      </section>
    );
  }

  const currentIndex = allResearchPapers.findIndex(p => p.id === itemId);
  const previousPaper = currentIndex > 0 ? allResearchPapers[currentIndex - 1] : undefined;
  const nextPaper = currentIndex < allResearchPapers.length - 1 ? allResearchPapers[currentIndex + 1] : undefined;
  
  const relatedPapers = allResearchPapers
    .filter(p => p.id !== itemId)
    .slice(0, 3);

  return (
    <section 
      id={SECTION_IDS.researchPaperDetailPage} 
      className="py-16 md:py-24 bg-white min-h-screen"
    >
      <div className="container mx-auto px-4 sm:px-6 lg:px-8">
        <Button
          variant="outline"
          size="sm"
          onClick={handleBackClick}
          leftIcon={<ArrowUturnLeftIcon />}
          className="mb-6"
        >
          {RESEARCH_PAPER_DETAIL_CONTENT.backButtonText}
        </Button>

        {paper.imageUrl && (
          <div className="mb-8 rounded-lg overflow-hidden">
            <img src={paper.imageUrl} alt={paper.title} className="w-full h-auto object-cover max-h-[60vh]" />
          </div>
        )}
        
        <div className="max-w-3xl mx-auto">
            <header className="mb-8 md:mb-12">
              <h1 className="font-quicksand text-3xl sm:text-4xl md:text-5xl font-bold text-slate-800 mb-3">
                {paper.title}
              </h1>
              <div className="font-inter text-sm text-slate-500">
                <span className="font-semibold text-slate-600">{paper.category}</span>
                <span className="mx-1.5">•</span>
                <span>{paper.date}</span>
                {paper.authors && paper.authors.length > 0 && (
                  <>
                    <span className="mx-1.5">•</span>
                    <span>Авторы: {paper.authors.join(', ')}</span>
                  </>
                )}
              </div>
            </header>
            
            <article className="prose prose-lg max-w-none font-inter text-slate-700">
              {paper.abstract && (
                <div className="p-4 bg-slate-50 rounded-md mb-6">
                  <h2 className="text-xl font-semibold font-quicksand text-slate-700">{RESEARCH_PAPER_DETAIL_CONTENT.abstractTitle}</h2>
                  <p>{paper.abstract}</p>
                </div>
              )}
              {typeof paper.fullContent === 'string' ? (
                <div dangerouslySetInnerHTML={{ __html: paper.fullContent }} />
              ) : (
                paper.fullContent
              )}
            </article>

            {paper.gallery && paper.gallery.length > 0 && (
              <GalleryComponent items={paper.gallery} title={RESEARCH_PAPER_DETAIL_CONTENT.galleryTitle} />
            )}

            <ItemDetailNavigation
              previousItem={previousPaper ? { id: previousPaper.id, title: previousPaper.title } : undefined}
              nextItem={nextPaper ? { id: nextPaper.id, title: nextPaper.title } : undefined}
              onNavigate={handleNavigateItem}
              previousItemButtonLabel={RESEARCH_PAPER_DETAIL_CONTENT.previousItemButtonLabel || `Предыдущее ${RESEARCH_PAPER_DETAIL_CONTENT.itemTypeSingular}`}
              nextItemButtonLabel={RESEARCH_PAPER_DETAIL_CONTENT.nextItemButtonLabel || `Следующее ${RESEARCH_PAPER_DETAIL_CONTENT.itemTypeSingular}`}
              noPreviousItemText={RESEARCH_PAPER_DETAIL_CONTENT.noPreviousItemText || `Это первое ${RESEARCH_PAPER_DETAIL_CONTENT.itemTypeSingular}`}
              noNextItemText={RESEARCH_PAPER_DETAIL_CONTENT.noNextItemText || `Это последнее ${RESEARCH_PAPER_DETAIL_CONTENT.itemTypeSingular}`}
              themeColorClass="slate"
            />
        </div>

        {relatedPapers.length > 0 && (
          <div className="mt-12 md:mt-16">
            <div className="flex justify-between items-baseline mb-8">
              <h2 className="font-quicksand text-3xl font-bold text-slate-800">
                {RESEARCH_PAPER_DETAIL_CONTENT.keepReadingTitle || "Дальнейшие исследования"}
              </h2>
               <a 
                href={`#${SECTION_IDS.researchAllPage}`}
                onClick={handleShowAllKeepReading}
                className="group inline-flex items-center text-base font-medium text-slate-700 hover:text-black transition-colors whitespace-nowrap"
                aria-label={`Посмотреть все ${RESEARCH_PAPER_DETAIL_CONTENT.itemTypePlural}`}
              >
                 {RESEARCH_PAPER_DETAIL_CONTENT.viewAllButtonText || `Все ${RESEARCH_PAPER_DETAIL_CONTENT.itemTypePlural}`}
                <ChevronRightIcon className="ml-1 w-5 h-5 transform group-hover:translate-x-1 transition-transform duration-200" />
              </a>
            </div>
             <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
              {relatedPapers.map(relatedPaper => (
                <ResearchCard 
                  key={relatedPaper.id} 
                  paper={relatedPaper} 
                  setCurrentView={setCurrentView} 
                  setSelectedItemId={setSelectedItemId} 
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
};

export default ResearchPaperDetail;