'use client'
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { 
  ChevronRight, 
  BookOpen, 
  Users, 
  Calendar, 
  ExternalLink,
  FileText,
  Tag
} from 'lucide-react';

interface Publication {
  id: number;
  authors: string;
  year: number;
  title: string;
  journal: string;
  doi?: string;
  category?: string;
  abstractText?: string;
  publicationDate?: string;
  keywords?: string;
  isActive: boolean;
  displayOrder?: number;
}

const PublicationDetail: React.FC = () => {
  const params = useParams();
  const publicationId = params?.id as string;
  const [publication, setPublication] = useState<Publication | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchPublication = async () => {
      if (!publicationId) {
        setError('No publication ID provided');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);
        
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
        const response = await fetch(`${apiUrl}/publications/${publicationId}`);
        
        if (!response.ok) {
          if (response.status === 404) {
            throw new Error('Publication not found');
          }
          throw new Error(`Failed to fetch publication: ${response.statusText}`);
        }
        
        const data: Publication = await response.json();
        setPublication(data);
      } catch (err) {
        console.error('Error fetching publication:', err);
        setError(err instanceof Error ? err.message : 'Failed to load publication');
      } finally {
        setLoading(false);
      }
    };

    fetchPublication();
  }, [publicationId]);

  // Parse comma-separated strings
  const getAuthorsArray = (authors: string): string[] => {
    return authors.split(',').map(a => a.trim()).filter(a => a.length > 0);
  };

  const getKeywordsArray = (keywords: string): string[] => {
    return keywords.split(',').map(k => k.trim()).filter(k => k.length > 0);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading publication details...</p>
        </div>
      </div>
    );
  }

  if (error || !publication) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <BookOpen className="w-16 h-16 mx-auto mb-4 text-gray-400" />
          <h2 className="text-2xl font-bold mb-4" style={{ color: '#012068' }}>
            {error === 'Publication not found' ? 'Publication Not Found' : 'Error Loading Publication'}
          </h2>
          <p className="text-gray-600 mb-6">
            {error || 'The publication you\'re looking for doesn\'t exist.'}
          </p>
          <div className="flex gap-4 justify-center">
            <Link
              href="/education-training"
              className="inline-block px-6 py-3 rounded transition-opacity hover:opacity-90 text-sm font-medium"
              style={{ backgroundColor: '#012068', color: 'white' }}
            >
              Back to Publications
            </Link>
            <button
              onClick={() => window.location.reload()}
              className="px-6 py-3 rounded transition-opacity hover:opacity-90 text-sm font-medium border-2"
              style={{ borderColor: '#012068', color: '#012068' }}
            >
              Try Again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white">
      {/* Breadcrumb Section */}
      <section className="py-4" style={{ backgroundColor: '#f4f4f4' }}>
        <div className="max-w-7xl mx-auto px-4">
          <nav className="flex items-center space-x-2 text-sm">
            <Link
              href="/"
              className="hover:opacity-70 transition-opacity duration-200"
              style={{ color: '#012068' }}
            >
              Home
            </Link>
            <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
            <Link
              href="/education-training"
              className="hover:opacity-70 transition-opacity duration-200"
              style={{ color: '#012068' }}
            >
              Academic & Research
            </Link>
            <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
            <span className="font-medium" style={{ color: '#e64838' }}>
              Publication Details
            </span>
          </nav>

          {/* Publication Header */}
          <div className="mt-6">
            <div className="flex items-center space-x-3 mb-4">
              <div
                className="px-3 py-1 rounded-full text-sm font-semibold"
                style={{ backgroundColor: '#e64838', color: 'white' }}
              >
                {publication.year}
              </div>
              {publication.category && (
                <div
                  className="px-3 py-1 rounded-full text-sm font-medium"
                  style={{ backgroundColor: 'white', color: '#012068', border: '2px solid #012068' }}
                >
                  {publication.category}
                </div>
              )}
            </div>
            <h1 className="text-3xl font-bold mb-4" style={{ color: '#012068' }}>
              {publication.title}
            </h1>
          </div>
        </div>
      </section>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 py-12">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Main Content Column */}
          <div className="lg:col-span-2">
            {/* Abstract Section */}
            {publication.abstractText && (
              <div className="mb-8">
                <div className="flex items-center mb-4">
                  <FileText className="w-6 h-6 mr-3" style={{ color: '#e64838' }} />
                  <h2 className="text-2xl font-semibold" style={{ color: '#012068' }}>
                    Abstract
                  </h2>
                </div>
                <div className="rounded-lg p-6" style={{ backgroundColor: '#f9fafb' }}>
                  <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">
                    {publication.abstractText}
                  </p>
                </div>
              </div>
            )}

            {/* Authors Section */}
            <div className="mb-8">
              <div className="flex items-center mb-4">
                <Users className="w-6 h-6 mr-3" style={{ color: '#e64838' }} />
                <h2 className="text-2xl font-semibold" style={{ color: '#012068' }}>
                  Authors
                </h2>
              </div>
              <div className="rounded-lg p-6" style={{ backgroundColor: '#f9fafb' }}>
                <div className="flex flex-wrap gap-3">
                  {getAuthorsArray(publication.authors).map((author, index) => (
                    <div
                      key={index}
                      className="px-4 py-2 rounded-lg text-sm font-medium"
                      style={{ backgroundColor: 'white', color: '#012068', border: '1px solid #e5e7eb' }}
                    >
                      {author}
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Keywords Section */}
            {publication.keywords && (
              <div className="mb-8">
                <div className="flex items-center mb-4">
                  <Tag className="w-6 h-6 mr-3" style={{ color: '#e64838' }} />
                  <h2 className="text-2xl font-semibold" style={{ color: '#012068' }}>
                    Keywords
                  </h2>
                </div>
                <div className="rounded-lg p-6" style={{ backgroundColor: '#f9fafb' }}>
                  <div className="flex flex-wrap gap-2">
                    {getKeywordsArray(publication.keywords).map((keyword, index) => (
                      <span
                        key={index}
                        className="px-3 py-1 rounded-full text-sm"
                        style={{ backgroundColor: '#e64838', color: 'white' }}
                      >
                        {keyword}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Sidebar Column */}
          <div className="lg:col-span-1">
            <div className="rounded-lg p-6 sticky top-8" style={{ backgroundColor: '#f4f4f4' }}>
              <h3 className="text-xl font-semibold mb-6" style={{ color: '#012068' }}>
                Publication Information
              </h3>

              {/* Journal */}
              <div className="mb-6">
                <div className="flex items-center mb-2">
                  <BookOpen className="w-5 h-5 mr-2" style={{ color: '#e64838' }} />
                  <span className="text-sm font-semibold" style={{ color: '#012068' }}>
                    Journal
                  </span>
                </div>
                <p className="text-sm text-gray-700 ml-7">
                  {publication.journal}
                </p>
              </div>

              {/* Publication Date */}
              {publication.publicationDate && (
                <div className="mb-6">
                  <div className="flex items-center mb-2">
                    <Calendar className="w-5 h-5 mr-2" style={{ color: '#e64838' }} />
                    <span className="text-sm font-semibold" style={{ color: '#012068' }}>
                      Published
                    </span>
                  </div>
                  <p className="text-sm text-gray-700 ml-7">
                    {publication.publicationDate}
                  </p>
                </div>
              )}

              {/* DOI */}
              {publication.doi && (
                <div className="mb-6">
                  <div className="flex items-center mb-2">
                    <ExternalLink className="w-5 h-5 mr-2" style={{ color: '#e64838' }} />
                    <span className="text-sm font-semibold" style={{ color: '#012068' }}>
                      DOI
                    </span>
                  </div>
                  <a
                    href={publication.doi}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm hover:underline ml-7 break-all"
                    style={{ color: '#e64838' }}
                  >
                    {publication.doi.replace('https://doi.org/', '')}
                  </a>
                </div>
              )}

              {/* Action Buttons */}
              <div className="space-y-3 pt-6 border-t border-gray-300">
                {publication.doi && (
                  <a
                    href={publication.doi}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center justify-center w-full px-4 py-3 rounded transition-opacity hover:opacity-90 text-sm font-medium"
                    style={{ backgroundColor: '#012068', color: 'white' }}
                  >
                    <ExternalLink className="w-4 h-4 mr-2" />
                    View Full Publication
                  </a>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PublicationDetail;