'use client';

import { useState, useEffect } from 'react';
import { SearchBar } from '@/components/SearchBar';
import { ArticleCard } from '@/components/ArticleCard';
import { UploadModal } from '@/components/UploadModal';
import UploadQueue from '@/components/UploadQueue';
import { searchArticles, Article } from '@/lib/api';
import { Newspaper, Upload, Sparkles, AlertCircle } from 'lucide-react';

export default function Home() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedJobId, setSelectedJobId] = useState<number | null>(null);

  // Fetch initial generic results on load
  useEffect(() => {
    handleSearch('', false);
  }, []);

  const handleSearch = async (query: string, semantic: boolean, jobId: number | null = selectedJobId) => {
    setIsLoading(true);
    setHasSearched(true);
    setError(null);
    try {
      const results = await searchArticles(query, semantic, jobId || undefined);
      setArticles(results || []);
    } catch (err) {
      console.error(err);
      setError('Failed to fetch articles. Please ensure the backend is running.');
      setArticles([]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleJobSelect = (jobId: number | null) => {
    setSelectedJobId(jobId);
    handleSearch('', false, jobId);
  };

  return (
    <div className="min-h-screen bg-[#030712] text-zinc-50 font-sans selection:bg-indigo-500/30">
      
      {/* Navbar */}
      <nav className="fixed top-0 left-0 right-0 z-40 glass border-b border-white/5">
        <div className="max-w-7xl mx-auto px-6 h-16 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="bg-indigo-500/10 p-2 rounded-lg border border-indigo-500/20">
              <Newspaper className="text-indigo-400" size={24} />
            </div>
            <span className="font-bold tracking-tight text-xl bg-clip-text text-transparent bg-gradient-to-r from-zinc-100 to-zinc-400">
              NeuralNews
            </span>
          </div>
          <button 
            onClick={() => setIsUploadModalOpen(true)}
            className="flex items-center gap-2 bg-white/5 hover:bg-white/10 border border-white/10 px-4 py-2 rounded-lg text-sm font-medium transition-all"
          >
            <Upload size={16} />
            Ingest PDF
          </button>
        </div>
      </nav>

      {/* Hero Section */}
      <main className="pt-32 pb-20 px-6 max-w-7xl mx-auto">
        <div className="flex flex-col items-center text-center mb-16 space-y-6">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 text-sm font-medium">
            <Sparkles size={16} />
            Powered by OCR & Layout Parsing
          </div>
          <h1 className="text-5xl md:text-7xl font-extrabold tracking-tight">
            Intelligent <span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-400 to-cyan-400">Newspaper</span> <br className="hidden md:block"/> Extraction
          </h1>
          <p className="max-w-2xl text-lg text-zinc-400">
            Search through semantically embedded newspaper articles, categorized by layout and translated via AI. 
          </p>
        </div>

        {/* Main Content Layout with Sidebar */}
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Main Feed */}
          <div className="flex-1">
            {/* Search Bar */}
            <div className="mb-8">
              <SearchBar onSearch={(q, s) => handleSearch(q, s, selectedJobId)} isLoading={isLoading} />
            </div>

            {/* Results */}
            {error ? (
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <AlertCircle className="text-red-400 mb-4" size={48} />
            <h2 className="text-xl font-medium text-red-100 mb-2">Connection Error</h2>
            <p className="text-red-400/80">{error}</p>
          </div>
        ) : isLoading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 animate-pulse">
            {[1, 2, 3, 4].map(i => (
              <div key={i} className="h-64 rounded-2xl bg-zinc-900 border border-zinc-800"></div>
            ))}
          </div>
        ) : articles.length > 0 ? (
          <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
            {articles.map(article => (
              <ArticleCard key={article.id} article={article} />
            ))}
          </div>
          ) : hasSearched ? (
            <div className="text-center py-20">
              <h3 className="text-2xl font-semibold text-zinc-300">No articles found</h3>
              <p className="text-zinc-500 mt-2">Try adjusting your search query or uploading a new newspaper.</p>
            </div>
          ) : null}
          </div>

          {/* Sidebar */}
          <div className="w-full lg:w-80 flex-shrink-0 h-[calc(100vh-200px)] sticky top-24">
            <UploadQueue 
              onSelectJob={handleJobSelect} 
              selectedJobId={selectedJobId} 
            />
          </div>
        </div>
      </main>

      <UploadModal 
        isOpen={isUploadModalOpen} 
        onClose={() => setIsUploadModalOpen(false)} 
      />
    </div>
  );
}
