"use client";
import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogClose,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import { InvokeLLM } from "@/types/entities";
import { motion, AnimatePresence } from "framer-motion";
import { Search, Filter, Sparkles, TrendingUp, Brain, Target, Zap, ArrowRight, Lightbulb } from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { adviseForDataset, DatasetAdvisorInput } from "@/ai/flows/dataset-advisor";
import AIAdvisor from "@/components/portal/AIAdvisor";
import DatasetCard from "@/components/portal/DatasetCard";
import FilterPanel from "@/components/portal/FilterPanel";
import RecommendationCard from "@/components/portal/RecommendationCard";
import SearchBar from "@/components/portal/SearchBar";

export default function DataPortalPage() {
  // Discovery logic
  const [datasets, setDatasets] = useState<any[]>([]);
  const [filteredDatasets, setFilteredDatasets] = useState<any[]>([]);
  const [activeSource, setActiveSource] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [filters, setFilters] = useState({ category: "all", size: "all", rating: "all" });
  const [isLoading, setIsLoading] = useState(true);
  const [aiRecommendations, setAiRecommendations] = useState<any[]>([]);
  const [showFilters, setShowFilters] = useState(false);
  const [downloadStatus, setDownloadStatus] = useState<any>({});
  const [aiLoading, setAiLoading] = useState(false);
  const [cloudStatus, setCloudStatus] = useState<any>({});

  // Form-based logic
  const [source, setSource] = useState("kaggle");
  const [identifier, setIdentifier] = useState("");
  const [destDir, setDestDir] = useState("datasets/");
  const [kaggleUsername, setKaggleUsername] = useState("");
  const [kaggleKey, setKaggleKey] = useState("");
  const [split, setSplit] = useState("train");
  const [status, setStatus] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [advisorInput, setAdvisorInput] = useState("");
  const [advisorResponse, setAdvisorResponse] = useState("");

  // Advisor state
  const [advisorOpen, setAdvisorOpen] = useState(false);
  const [projectGoal, setProjectGoal] = useState("");
  const [currentData, setCurrentData] = useState("");

  // Google-level search features
  const [searchSuggestions, setSearchSuggestions] = useState<string[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [searchStats, setSearchStats] = useState({ total: 0, time: '0.00' });

  // Google-style search suggestions
  const popularSearches = [
    "drone datasets", "aerial imagery", "computer vision", "image classification",
    "natural language processing", "medical imaging", "covid detection", 
    "oscilloscope data", "signal processing", "mnist handwritten digits",
    "cifar object recognition", "fashion mnist", "speech recognition",
    "satellite imagery", "autonomous driving", "robotics datasets"
  ];

  // Real-time search with debouncing (Google-style)
  useEffect(() => {
    const delayedSearch = setTimeout(() => {
      if (searchQuery.trim()) {
        performGoogleLevelSearch(searchQuery);
        generateSearchSuggestions(searchQuery);
      } else {
        setSearchResults([]);
        setSearchSuggestions([]);
        setShowSuggestions(false);
      }
    }, 300); // 300ms debounce like Google

    return () => clearTimeout(delayedSearch);
  }, [searchQuery]);

  const generateSearchSuggestions = (query: string) => {
    if (query.length < 2) {
      setSearchSuggestions([]);
      return;
    }

    const suggestions = popularSearches
      .filter(search => search.toLowerCase().includes(query.toLowerCase()))
      .slice(0, 8);
    
    setSearchSuggestions(suggestions);
    setShowSuggestions(suggestions.length > 0);
  };

  const performGoogleLevelSearch = async (query: string) => {
    setIsSearching(true);
    setError(null);
    const startTime = performance.now();

    try {
      const response = await fetch(
        `http://localhost:8000/datasets/search?query=${encodeURIComponent(query)}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      if (!response.ok) {
        throw new Error(`Search failed: ${response.status}`);
      }

      const data = await response.json();
      const endTime = performance.now();
      const searchTime = ((endTime - startTime) / 1000).toFixed(2);

      // Google-style result handling
      setSearchResults(data.results || []);
      setSearchStats({
        total: data.total || data.results?.length || 0,
        time: parseFloat(searchTime)
      });

      // Update search history (Google-style)
      if (!searchHistory.includes(query)) {
        setSearchHistory(prev => [query, ...prev.slice(0, 9)]); // Keep last 10 searches
      }

      console.log('🔍 Google-Level Search Results:', data);
      
    } catch (error) {
      console.error('Search error:', error);
      setError('Search temporarily unavailable. Please try again.');
      setSearchResults([]);
    }

    setIsSearching(false);
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      performGoogleLevelSearch(searchQuery);
      setShowSuggestions(false);
    }
  };

  const selectSuggestion = (suggestion: string) => {
    setSearchQuery(suggestion);
    setShowSuggestions(false);
    performGoogleLevelSearch(suggestion);
  };

  useEffect(() => {
    // Don't automatically load datasets - only show when user searches
    // generateAIRecommendations();
  }, []);

  // Apply filters to search results (Google-style filtering)
  useEffect(() => {
    if (searchResults.length > 0) {
      let filtered = [...searchResults];
      
      if (activeSource !== "all") {
        filtered = filtered.filter(dataset => dataset.source === activeSource);
      }
      
      setFilteredDatasets(filtered);
    } else {
      setFilteredDatasets([]);
    }
  }, [searchResults, activeSource]);

  // Legacy function compatibility
  const loadDatasets = async () => {
    // Replaced by loadTrendingDatasets
  };

  const applyFilters = () => {
    // Now handled by the useEffect above
  };

  const handleSearch = () => {
    // Now handled by performGoogleLevelSearch
  };

  const generateAIRecommendations = async () => {
    setAiLoading(true);
    try {
      const response = await InvokeLLM({
        prompt: `Generate 3 trending dataset recommendations for machine learning projects. Focus on popular, high-quality datasets across different domains like computer vision, NLP, and structured data. For each recommendation, provide: name, brief description, and why it's trending.`,
        response_json_schema: {
          type: "object",
          properties: {
            recommendations: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  name: { type: "string" },
                  description: { type: "string" },
                  reason: { type: "string" },
                  category: { type: "string" }
                }
              }
            }
          }
        }
      });
      setAiRecommendations(response.recommendations || []);
    } catch (error) {
      console.error("Error generating AI recommendations:", error);
    }
    setAiLoading(false);
  };

  const toggleFavorite = async (datasetId: any) => {
    setDatasets(ds => ds.map(d => d.id === datasetId ? { ...d, is_favorited: !d.is_favorited } : d));
  };

  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [downloadInfo, setDownloadInfo] = useState<any>(null);
  const [pendingDownload, setPendingDownload] = useState<string>("");

  const handleDirectDownload = async (dataset: any) => {
    try {
      setIsLoading(true);
      const identifier = dataset.identifier || dataset.name.replace('🤗 ', '');
      
    if (dataset.source === 'huggingface') {
        // First, get dataset size info
        const infoResponse = await fetch(`http://localhost:9001/download-hf?dataset=${encodeURIComponent(identifier)}&info=true`);
        
        if (infoResponse.ok) {
          const info = await infoResponse.json();
          
          if (info.warning || info.estimatedSizeMB > 500) {
            // Show size warning dialog
            setDownloadInfo(info);
            setPendingDownload(identifier);
            setShowConfirmDialog(true);
            setIsLoading(false);
            return;
          }
        }
        
        // Small dataset - download directly
        window.open(`http://localhost:9001/download-hf?dataset=${encodeURIComponent(identifier)}&confirm=true`, '_blank');
        
      } else if (dataset.source === 'kaggle') {
        window.open(`http://localhost:9001/download-kaggle?dataset=${encodeURIComponent(identifier)}`, '_blank');
    } else if (dataset.source === 'github') {
        window.open(`http://localhost:9001/download-github?repo=${encodeURIComponent(identifier)}`, '_blank');
      } else {
        window.open(dataset.url, '_blank');
      }
      
    } catch (error) {
      console.error('Download error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const confirmDownload = () => {
    if (pendingDownload) {
      window.open(`http://localhost:9001/download-hf?dataset=${encodeURIComponent(pendingDownload)}&confirm=true`, '_blank');
    }
    setShowConfirmDialog(false);
    setDownloadInfo(null);
    setPendingDownload("");
  };

  const cancelDownload = () => {
    setShowConfirmDialog(false);
    setDownloadInfo(null);
    setPendingDownload("");
  };

  // --- Form-based logic (from your original page) ---
  const handleFormSearch = async () => {
    setSearchResults([
      { name: "Example Dataset 1", id: "example1" },
      { name: "Example Dataset 2", id: "example2" },
    ]);
  };
  const handleAdvisor = async () => {
    setAdvisorResponse("Try 'mnist' for digit recognition, or 'imagenet' for general vision tasks.");
  };
  const handleSelectResult = (result: any) => {
    setIdentifier(result.id || result.name);
    setSearchOpen(false);
  };
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setStatus(null);
    const payload: any = { source, identifier, dest_dir: destDir };
    if (source === "kaggle") {
      if (kaggleUsername) payload.kaggle_username = kaggleUsername;
      if (kaggleKey) payload.kaggle_key = kaggleKey;
    }
    if (source === "huggingface") {
      payload.split = split;
    }
    try {
      const res = await fetch("http://localhost:8000/datasets/download", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      setStatus(data.message || JSON.stringify(data));
    } catch (err: any) {
      setStatus("Error: " + err.message);
    } finally {
      setLoading(false);
    }
  };

  // --- UI ---
  const [error, setError] = useState<string | null>(null);

  return (
    <>
      <div className="min-h-screen bg-gradient-to-br from-background via-background/95 to-background/90 relative overflow-hidden">
        <div className="absolute inset-0 bg-grid-white/[0.02] bg-[size:50px_50px]" />
        <div className="relative z-10 flex flex-col h-screen">
          {/* Header */}
          <motion.div 
            initial={{ opacity: 0, y: -20 }} 
            animate={{ opacity: 1, y: 0 }} 
            className="flex-shrink-0 p-6 border-b border-border/50 backdrop-blur-xl bg-background/80"
          >
      <div className="max-w-7xl mx-auto">
              <div className="flex items-center justify-between">
            <div>
                  <h1 className="text-3xl font-bold bg-gradient-to-r from-[var(--neon-cyan)] to-[var(--neon-blue)] bg-clip-text text-transparent">
                    Discover Datasets
              </h1>
                  <p className="text-muted-foreground mt-1">Find the perfect data for your next AI project</p>
            </div>
            <div className="flex items-center gap-3">
                  <Button onClick={() => setShowFilters(!showFilters)} className="flex items-center gap-2 hover-lift">
                <Filter className="w-4 h-4" /> Filters
              </Button>
              <Button onClick={generateAIRecommendations} className="flex items-center gap-2 hover-lift bg-gradient-to-r from-purple-500 to-blue-500 text-white">
                <Sparkles className="w-4 h-4" /> AI Suggest
              </Button>
              <Button onClick={() => setAdvisorOpen(o => !o)} className="flex items-center gap-2 hover-lift bg-gradient-to-r from-blue-500 to-green-500 text-white">
                <Brain className="w-4 h-4" /> AI Advisor
              </Button>
                </div>
            </div>
          </div>
        </motion.div>

          {/* Main Content - Scrollable */}
          <div className="flex-1 overflow-hidden">
            <div className="h-full overflow-y-auto px-6 py-6 minimal-scrollbar">
              <div className="max-w-7xl mx-auto space-y-8">

        {/* Search and Filters */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="mb-8">
                  {/* Google-Level Search Interface */}
                  <div className="relative">
                    <form onSubmit={handleSearchSubmit} className="relative">
                      <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-5 h-5 z-10" />
                        <input
                          type="text"
                          value={searchQuery}
                          onChange={(e) => {
                            setSearchQuery(e.target.value);
                            setShowSuggestions(true);
                          }}
                          onFocus={() => setShowSuggestions(searchSuggestions.length > 0)}
                          onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
                          placeholder="Search datasets... (try 'drones', 'mnist', 'covid')"
                          className="w-full pl-10 pr-12 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 shadow-lg text-lg text-black dark:text-white"
                        />
                        <button
                          type="submit"
                          disabled={isSearching}
                          className="absolute right-2 top-1/2 transform -translate-y-1/2 px-4 py-1.5 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors font-mono text-sm disabled:opacity-50"
                        >
                          {isSearching ? (
                            <div className="flex items-center gap-1">
                              <div className="w-3 h-3 border border-current border-t-transparent rounded-full animate-spin"></div>
                              <span>Searching</span>
                            </div>
                          ) : (
                            'Search'
                          )}
                        </button>
                      </div>
                    </form>

                    {/* Google-Style Search Suggestions */}
                    {showSuggestions && searchSuggestions.length > 0 && (
                      <div className="absolute top-full left-0 right-0 mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-2xl z-50 max-h-64 overflow-y-auto minimal-scrollbar">
                        {searchSuggestions.map((suggestion, index) => (
                          <button
                            key={index}
                            onClick={() => selectSuggestion(suggestion)}
                            className="w-full text-left px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors border-b border-gray-200 dark:border-gray-600 last:border-b-0 flex items-center gap-2 text-black dark:text-white"
                          >
                            <Search className="w-4 h-4 text-muted-foreground" />
                            <span>{suggestion}</span>
                          </button>
                        ))}
                      </div>
                    )}

                    {/* Google-Style Search Stats */}
                    {searchResults.length > 0 && (
                      <div className="mt-3 text-sm text-muted-foreground">
                        About {searchStats.total.toLocaleString()} results ({searchStats.time} seconds)
                        {searchQuery && (
                          <span className="ml-2 px-2 py-1 bg-[var(--neon-cyan)]/10 text-[var(--neon-cyan)] rounded-full text-xs">
                            AI-Enhanced Search
                          </span>
                        )}
                      </div>
                    )}
                  </div>
          <div className="mt-6">
            <Tabs value={activeSource} onValueChange={setActiveSource}>
                      <TabsList className="bg-muted/30 backdrop-blur-sm">
                        <TabsTrigger value="all" className="data-[state=active]:bg-[var(--neon-cyan)] data-[state=active]:text-[var(--bg-main)]">All Sources</TabsTrigger>
                        <TabsTrigger value="kaggle" className="data-[state=active]:bg-[var(--neon-cyan)] data-[state=active]:text-[var(--bg-main)]">Kaggle</TabsTrigger>
                        <TabsTrigger value="huggingface" className="data-[state=active]:bg-[var(--neon-cyan)] data-[state=active]:text-[var(--bg-main)]">Hugging Face</TabsTrigger>
                        <TabsTrigger value="github" className="data-[state=active]:bg-[var(--neon-cyan)] data-[state=active]:text-[var(--bg-main)]">GitHub</TabsTrigger>
              </TabsList>
            </Tabs>
          </div>
        </motion.div>

                {/* Results - Scrollable Content */}
                <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}>
                  {/* Search Results or Trending Datasets */}
                  {error && (
                    <div className="text-center py-8">
                      <div className="text-red-400 mb-2">⚠️ Search Error</div>
                      <div className="text-muted-foreground">{error}</div>
                      <button 
                        onClick={() => {
                          setError(null);
                          if (searchQuery) performGoogleLevelSearch(searchQuery);
                        }}
                        className="mt-3 px-4 py-2 bg-[var(--neon-cyan)] text-[var(--bg-main)] rounded-md hover:bg-[var(--neon-blue)] transition-colors"
                      >
                        Try Again
                      </button>
              </div>
                  )}

                  {isSearching && (
                    <div className="text-center py-12">
                      <div className="inline-flex items-center gap-3 text-[var(--neon-cyan)]">
                        <div className="w-6 h-6 border-2 border-current border-t-transparent rounded-full animate-spin"></div>
                        <span className="text-lg font-mono">Searching with AI intelligence...</span>
            </div>
          </div>
                  )}

                  {!isSearching && !error && filteredDatasets.length === 0 && searchQuery && (
                    <div className="text-center py-12">
                      <div className="text-6xl mb-4">🔍</div>
                      <div className="text-xl text-muted-foreground mb-2">No datasets found</div>
                      <div className="text-sm text-muted-foreground mb-4">
                        Try different keywords or check the suggestions above
                      </div>
                      <div className="flex flex-wrap justify-center gap-2">
                        {popularSearches.slice(0, 6).map(suggestion => (
                          <button
                            key={suggestion}
                            onClick={() => selectSuggestion(suggestion)}
                            className="px-3 py-1 bg-muted hover:bg-[var(--neon-cyan)]/20 rounded-full text-sm transition-colors"
                          >
                            {suggestion}
                          </button>
                        ))}
                      </div>
                    </div>
                  )}

                  {!isSearching && !error && filteredDatasets.length > 0 && (
                    <div className="space-y-6">
                      <div className="flex items-center justify-between">
                        <h3 className="text-lg font-semibold text-foreground">
                          {searchQuery ? `Search Results for "${searchQuery}"` : 'Trending Datasets'}
                        </h3>
                        <div className="text-sm text-muted-foreground">
                          📊 Sorted by relevance
                        </div>
            </div>
                      
                      {/* Scrollable Results Container */}
                      <div className="space-y-4 pb-20">
              <AnimatePresence>
                {filteredDatasets.map((dataset, index) => (
                  <motion.div 
                              key={dataset.url || index} 
                    initial={{ opacity: 0, y: 20 }} 
                    animate={{ opacity: 1, y: 0 }} 
                    exit={{ opacity: 0, y: -20 }} 
                    transition={{ delay: index * 0.05 }}
                    className={index % 2 !== 0 ? 'blue-coated-card' : ''}
                  >
                    <DatasetCard
                      key={dataset.id || index}
                      dataset={dataset}
                      onFavorite={toggleFavorite}
                                onDownload={handleDirectDownload}
                      onDirectDownload={handleDirectDownload}
                      downloadStatus={downloadStatus[dataset.name]}
                      onLoadToCloud={handleDirectDownload}
                      cloudStatus={cloudStatus[dataset.name]}
                    />
                  </motion.div>
                ))}
              </AnimatePresence>
            </div>
                    </div>
          )}
        </motion.div>
      </div>
    </div>
          </div>
        </div>
      </div>

      {/* Size Warning Dialog */}
      {showConfirmDialog && downloadInfo && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 p-6 rounded-lg max-w-md w-full mx-4">
            <h3 className="text-lg font-bold mb-4">Dataset Download Warning</h3>
            
            <div className="space-y-3 mb-6">
              <p><strong>Dataset:</strong> {downloadInfo.dataset}</p>
              <p><strong>Files:</strong> {downloadInfo.totalFiles.toLocaleString()}</p>
              <p><strong>Estimated Size:</strong> {downloadInfo.estimatedSizeMB > 1024 
                ? `${(downloadInfo.estimatedSizeMB/1024).toFixed(1)}GB` 
                : `${downloadInfo.estimatedSizeMB}MB`}</p>
              
              {downloadInfo.warning && (
                <div className="bg-orange-100 dark:bg-orange-900/20 border border-orange-300 dark:border-orange-700 rounded p-3">
                  <p className="text-orange-800 dark:text-orange-200">{downloadInfo.warning}</p>
                </div>
              )}
              
              {downloadInfo.largeFiles?.length > 0 && (
                <div>
                  <p className="font-medium mb-2">Large files included:</p>
                  <ul className="text-sm text-gray-600 dark:text-gray-400 space-y-1">
                    {downloadInfo.largeFiles.map((file: string, index: number) => (
                      <li key={index}>• {file}</li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
            
            <div className="flex space-x-3">
              <button
                onClick={confirmDownload}
                className="flex-1 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg font-medium"
              >
                Download Anyway
              </button>
              <button
                onClick={cancelDownload}
                className="flex-1 bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg font-medium"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
} 