import { useState, useMemo, useRef } from "react";
import { motion, useInView } from "framer-motion";
import { Search, Download, FileText, Calendar, Filter } from "lucide-react";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "./ui/dialog";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";

interface ResearchPaper {
  id: string;
  title: string;
  authors: string;
  date: string;
  category: string;
  abstract: string;
  downloadUrl: string;
}

const researchPapers: ResearchPaper[] = [
  {
    id: "1",
    title: "Advanced Cryogenic Preservation Techniques for Leafy Vegetables",
    authors: "Dr. Sarah Johnson, Dr. Michael Chen",
    date: "2024-01-15",
    category: "Vegetables",
    abstract: "This study explores novel cryogenic preservation methods that extend the shelf life of leafy vegetables by up to 400% while maintaining nutritional integrity. Our findings demonstrate significant improvements in chlorophyll retention and texture preservation.",
    downloadUrl: "#",
  },
  {
    id: "2",
    title: "Controlled Atmosphere Storage: Optimizing Fruit Hibernation",
    authors: "Dr. Emily Rodriguez, Dr. James Park",
    date: "2023-11-20",
    category: "Fruits",
    abstract: "An in-depth analysis of controlled atmosphere storage parameters for various fruit types. This research identifies optimal oxygen, carbon dioxide, and humidity levels for maximum preservation efficacy.",
    downloadUrl: "#",
  },
  {
    id: "3",
    title: "Enzymatic Activity Suppression in Root Vegetables During Storage",
    authors: "Dr. Robert Williams, Dr. Lisa Anderson",
    date: "2023-09-10",
    category: "Vegetables",
    abstract: "Investigation into natural enzymatic inhibitors that prevent degradation in root vegetables during extended storage periods. Results show promise for organic preservation methods.",
    downloadUrl: "#",
  },
  {
    id: "4",
    title: "Temperature Gradient Management in Berry Preservation",
    authors: "Dr. Amanda Foster, Dr. Kevin Liu",
    date: "2023-07-05",
    category: "Fruits",
    abstract: "This paper examines the impact of precise temperature gradient control on berry preservation, revealing optimal cooling rates and storage temperatures for different berry varieties.",
    downloadUrl: "#",
  },
  {
    id: "5",
    title: "Microbiome Stabilization in Organic Produce Storage",
    authors: "Dr. Patricia Martinez, Dr. David Thompson",
    date: "2023-05-18",
    category: "General",
    abstract: "Comprehensive study on maintaining beneficial microbiomes while suppressing pathogenic organisms during produce storage, with implications for organic farming practices.",
    downloadUrl: "#",
  },
  {
    id: "6",
    title: "Humidity Control Systems for Tropical Fruit Preservation",
    authors: "Dr. Carlos Mendez, Dr. Jennifer Wong",
    date: "2023-03-22",
    category: "Fruits",
    abstract: "Analysis of  advanced humidity control technologies and their effectiveness in preserving tropical fruits during long-distance transportation and storage.",
    downloadUrl: "#",
  },
];

export default function ResearchSection() {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [selectedPaper, setSelectedPaper] = useState<ResearchPaper | null>(null);
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });

  const filteredPapers = useMemo(() => {
    return researchPapers.filter((paper) => {
      const matchesSearch =
        paper.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        paper.authors.toLowerCase().includes(searchQuery.toLowerCase()) ||
        paper.abstract.toLowerCase().includes(searchQuery.toLowerCase());
      
      const matchesCategory =
        selectedCategory === "all" || paper.category === selectedCategory;

      return matchesSearch && matchesCategory;
    });
  }, [searchQuery, selectedCategory]);

  const categories = ["all", ...Array.from(new Set(researchPapers.map((p) => p.category)))];

  return (
    <section id="research" className="py-20 bg-white">
      <div className="container mx-auto px-4 sm:px-6 lg:px-8">
        <motion.div
          ref={ref}
          initial={{ opacity: 0, y: 50 }}
          animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 50 }}
          transition={{ duration: 0.6 }}
          className="text-center mb-12"
        >
          <h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
            Research & Publications
          </h2>
          <p className="text-xl text-gray-600 max-w-3xl mx-auto">
            Explore our comprehensive library of peer-reviewed research papers
          </p>
        </motion.div>

        {/* Search and Filter */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
          transition={{ duration: 0.6, delay: 0.2 }}
          className="mb-8 flex flex-col sm:flex-row gap-4"
        >
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <Input
              type="text"
              placeholder="Search papers by title, author, or keywords..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 h-12 text-base"
            />
          </div>
          <Select value={selectedCategory} onValueChange={setSelectedCategory}>
            <SelectTrigger className="w-full sm:w-[200px] h-12">
              <Filter className="w-4 h-4 mr-2" />
              <SelectValue placeholder="Category" />
            </SelectTrigger>
            <SelectContent>
              {categories.map((category) => (
                <SelectItem key={category} value={category}>
                  {category === "all" ? "All Categories" : category}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </motion.div>

        {/* Results Count */}
        <motion.p
          initial={{ opacity: 0 }}
          animate={isInView ? { opacity: 1 } : { opacity: 0 }}
          transition={{ duration: 0.6, delay: 0.3 }}
          className="text-gray-600 mb-6"
        >
          Showing {filteredPapers.length} of {researchPapers.length} papers
        </motion.p>

        {/* Papers Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredPapers.map((paper, index) => (
            <motion.div
              key={paper.id}
              initial={{ opacity: 0, y: 20 }}
              animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
              transition={{ duration: 0.5, delay: index * 0.1 }}
              className="bg-white border border-gray-200 rounded-xl p-6 hover:shadow-lg transition-shadow cursor-pointer"
              onClick={() => setSelectedPaper(paper)}
            >
              <div className="flex items-start justify-between mb-3">
                <FileText className="w-8 h-8 text-green-600 flex-shrink-0" />
                <Badge variant="secondary" className="text-xs">
                  {paper.category}
                </Badge>
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2 line-clamp-2">
                {paper.title}
              </h3>
              <p className="text-sm text-gray-600 mb-3">{paper.authors}</p>
              <div className="flex items-center text-sm text-gray-500 mb-3">
                <Calendar className="w-4 h-4 mr-1" />
                {new Date(paper.date).toLocaleDateString("en-US", {
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </div>
              <p className="text-sm text-gray-600 line-clamp-3 mb-4">
                {paper.abstract}
              </p>
              <Button
                variant="outline"
                size="sm"
                className="w-full"
                onClick={(e) => {
                  e.stopPropagation();
                  setSelectedPaper(paper);
                }}
              >
                View Details
              </Button>
            </motion.div>
          ))}
        </div>

        {filteredPapers.length === 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="text-center py-12"
          >
            <p className="text-gray-500 text-lg">
              No papers found matching your search criteria.
            </p>
          </motion.div>
        )}

        {/* Paper Preview Modal */}
        <Dialog open={!!selectedPaper} onOpenChange={() => setSelectedPaper(null)}>
          <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
            {selectedPaper && (
              <>
                <DialogHeader>
                  <DialogTitle className="text-2xl font-bold pr-8">
                    {selectedPaper.title}
                  </DialogTitle>
                  <DialogDescription className="text-base">
                    {selectedPaper.authors}
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 mt-4">
                  <div className="flex items-center gap-4">
                    <Badge>{selectedPaper.category}</Badge>
                    <div className="flex items-center text-sm text-gray-500">
                      <Calendar className="w-4 h-4 mr-1" />
                      {new Date(selectedPaper.date).toLocaleDateString("en-US", {
                        year: "numeric",
                        month: "long",
                        day: "numeric",
                      })}
                    </div>
                  </div>
                  <div>
                    <h4 className="font-semibold text-lg mb-2">Abstract</h4>
                    <p className="text-gray-700 leading-relaxed">
                      {selectedPaper.abstract}
                    </p>
                  </div>
                  <Button
                    className="w-full bg-green-600 hover:bg-green-700"
                    onClick={() => {
                      // Simulate download
                      alert("Download functionality would be implemented here");
                    }}
                  >
                    <Download className="w-4 h-4 mr-2" />
                    Download Full Paper
                  </Button>
                </div>
              </>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </section>
  );
}
