'use client'
import React, { useState, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { Search, BookOpen, ExternalLink, Users, Filter, X } 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 PublicationsSection: React.FC = () => {
  const [publications, setPublications] = useState<Publication[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedYear, setSelectedYear] = useState<number | 'all'>('all');
  const [selectedCategory, setSelectedCategory] = useState<string>('All');

  useEffect(() => {
    const fetchPublications = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
        const response = await fetch(`${apiUrl}/publications/active`);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch publications: ${response.statusText}`);
        }
        
        const data: Publication[] = await response.json();
        setPublications(data);
      } catch (err) {
        console.error('Error fetching publications:', err);
        setError(err instanceof Error ? err.message : 'Failed to load publications');
      } finally {
        setLoading(false);
      }
    };

    fetchPublications();
  }, []);

  // Get unique years and categories from fetched data
  const years = useMemo(() => {
    const yearSet = new Set(publications.map(pub => pub.year));
    return Array.from(yearSet).sort((a, b) => b - a);
  }, [publications]);

  const categories = useMemo(() => {
    const categorySet = new Set(publications.map(pub => pub.category || 'Uncategorized').filter(Boolean));
    return ['All', ...Array.from(categorySet).sort()];
  }, [publications]);

  // Filter publications
  const filteredPublications = useMemo(() => {
    return publications.filter(pub => {
      const matchesSearch = 
        pub.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        pub.authors.toLowerCase().includes(searchTerm.toLowerCase()) ||
        pub.journal.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesYear = selectedYear === 'all' || pub.year === selectedYear;
      const matchesCategory = selectedCategory === 'All' || pub.category === selectedCategory;

      return matchesSearch && matchesYear && matchesCategory;
    });
  }, [publications, searchTerm, selectedYear, selectedCategory]);

  const clearFilters = () => {
    setSearchTerm('');
    setSelectedYear('all');
    setSelectedCategory('All');
  };

  const hasActiveFilters = searchTerm || selectedYear !== 'all' || selectedCategory !== 'All';

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

  if (loading) {
    return (
      <section className="py-12">
        <div className="max-w-7xl mx-auto px-4">
          <h2 className="text-3xl font-semibold mb-4 text-center" style={{ color: '#012068' }}>
            Publications
          </h2>
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          </div>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="py-12">
        <div className="max-w-7xl mx-auto px-4">
          <h2 className="text-3xl font-semibold mb-4 text-center" style={{ color: '#012068' }}>
            Publications
          </h2>
          <div className="text-center py-12">
            <div className="text-red-600 mb-4">
              <p className="text-lg font-semibold">Failed to load publications</p>
              <p className="text-sm mt-2">{error}</p>
            </div>
            <button
              onClick={() => window.location.reload()}
              className="px-6 py-3 rounded-lg transition-opacity hover:opacity-90 text-sm font-medium"
              style={{ backgroundColor: '#012068', color: 'white' }}
            >
              Try Again
            </button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="py-12">
      <div className="max-w-7xl mx-auto px-4">
        <h2 className="text-3xl font-semibold mb-4 text-center" style={{ color: '#012068' }}>
          Publications
        </h2>
        <p className="text-center text-gray-600 mb-8">
          Research and scholarly work from the Trauma Surgery Department
        </p>

        {publications.length === 0 ? (
          <div className="text-center py-12">
            <BookOpen className="w-16 h-16 mx-auto mb-4 text-gray-400" />
            <h3 className="text-xl font-semibold mb-2" style={{ color: '#012068' }}>
              No publications available
            </h3>
            <p className="text-gray-600">
              Publications will appear here once they are added by the admin.
            </p>
          </div>
        ) : (
          <>
            {/* Search and Filter */}
            <div className="mb-8">
              {/* Filter Options - Categories on left, Year and Search on right */}
              <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-4">
                {/* Left side: Category Filter */}
                <div className="flex flex-wrap gap-2">
                  {categories.map((category) => (
                    <button
                      key={category}
                      onClick={() => setSelectedCategory(category)}
                      className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors duration-200 ${
                        selectedCategory === category ? 'text-white' : 'border-2'
                      }`}
                      style={{
                        backgroundColor: selectedCategory === category ? '#012068' : 'transparent',
                        borderColor: '#012068',
                        color: selectedCategory === category ? 'white' : '#012068'
                      }}
                    >
                      {category}
                    </button>
                  ))}
                </div>

                {/* Right side: Year Filter and Search */}
                <div className="flex items-center gap-2">
                  {/* Year Filter */}
                  <select
                    value={selectedYear}
                    onChange={(e) => setSelectedYear(e.target.value === 'all' ? 'all' : parseInt(e.target.value))}
                    className="px-4 py-2 border-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    style={{ borderColor: '#012068' }}
                  >
                    <option value="all">All Years</option>
                    {years.map(year => (
                      <option key={year} value={year}>{year}</option>
                    ))}
                  </select>

                  {/* Search */}
                  <div className="relative">
                    <input
                      type="text"
                      placeholder="Search publications..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="border-2 rounded-lg px-4 py-2 pl-4 pr-10 text-sm focus:outline-none w-64"
                      style={{ borderColor: '#012068', color: '#333' }}
                    />
                    <button 
                      className="absolute inset-y-0 right-0 flex items-center px-3 rounded-lg"
                      style={{ backgroundColor: '#012068' }}
                    >
                      <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>

              {/* Results Count and Clear Filters */}
              <div className="mt-4 flex justify-between items-center">
                <div className="text-sm text-gray-600">
                  Showing {filteredPublications.length} of {publications.length} publications
                </div>
                {hasActiveFilters && (
                  <button
                    onClick={clearFilters}
                    className="flex items-center px-4 py-2 rounded-lg transition-opacity hover:opacity-90 text-sm font-medium"
                    style={{ backgroundColor: '#e64838', color: 'white' }}
                  >
                    <X className="w-4 h-4 mr-2" />
                    Clear Filters
                  </button>
                )}
              </div>
            </div>

            {/* Publications List */}
            {filteredPublications.length === 0 ? (
              <div className="text-center py-12">
                <BookOpen className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                <h3 className="text-xl font-semibold mb-2" style={{ color: '#012068' }}>
                  No publications found
                </h3>
                <p className="text-gray-600 mb-4">
                  Try adjusting your search or filter criteria
                </p>
                {hasActiveFilters && (
                  <button
                    onClick={clearFilters}
                    className="px-4 py-2 rounded-lg transition-opacity hover:opacity-90 text-sm font-medium"
                    style={{ backgroundColor: '#012068', color: 'white' }}
                  >
                    Clear Filters
                  </button>
                )}
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {filteredPublications.map((pub) => (
                  <Link
                    key={pub.id}
                    href={`/publications-detail/${pub.id}`}
                    className="block rounded-lg p-6 hover:shadow-lg transition-all duration-300 cursor-pointer group"
                    style={{ backgroundColor: '#f4f4f4' }}
                  >
                    {/* Publication Header */}
                    <div className="flex items-center space-x-3 mb-3">
                      <div
                        className="px-3 py-1 rounded-full text-xs font-semibold"
                        style={{ backgroundColor: '#e64838', color: 'white' }}
                      >
                        {pub.year}
                      </div>
                      {pub.category && (
                        <div
                          className="px-3 py-1 rounded-full text-xs font-medium"
                          style={{ backgroundColor: 'white', color: '#012068' }}
                        >
                          {pub.category}
                        </div>
                      )}
                    </div>

                    {/* Title */}
                    <h3 className="text-lg font-semibold mb-3 leading-tight group-hover:opacity-70 transition-opacity" style={{ color: '#012068' }}>
                      {pub.title}
                    </h3>

                    {/* Authors */}
                    <div className="flex items-start mb-3">
                      <Users className="w-4 h-4 mr-2 mt-1 flex-shrink-0" style={{ color: '#e64838' }} />
                      <p className="text-sm text-gray-700 line-clamp-2">
                        {getAuthorsArray(pub.authors).join(', ')}
                      </p>
                    </div>

                    {/* Journal */}
                    <div className="flex items-center mb-4">
                      <BookOpen className="w-4 h-4 mr-2 flex-shrink-0" style={{ color: '#012068' }} />
                      <p className="text-sm font-medium text-gray-700">
                        {pub.journal}
                      </p>
                    </div>

                    {/* View Details Button */}
                    <div className="flex items-center text-sm font-medium group-hover:opacity-70 transition-opacity" style={{ color: '#012068' }}>
                      View Details
                      <ExternalLink className="w-4 h-4 ml-2" />
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </section>
  );
};

export default PublicationsSection;