"use client"

import React, { useMemo } from "react"
import { Card, CardContent } from "../ui/card"
import { Button } from "../ui/button"
import { MoonUISkeletonPro as Skeleton } from "../ui/skeleton"
import { cn } from "../../lib/utils"
import { Lock, Sparkles, RefreshCw, Github, Download, FileJson, FileSpreadsheet } from "lucide-react"
import { useSubscription } from "../../hooks/use-subscription"
import { useGitHubData, useGitHubNotifications } from "./hooks"
import { exportData, exportAsCSV } from "./github-api"
import {
  MinimalVariant,
  CompactVariant,
  CardVariant,
  DetailedVariant,
} from "./variants"
import type { GitHubStarsProps } from "./types"
import { motion, AnimatePresence } from "framer-motion"
import confetti from "canvas-confetti"

const GitHubStarsInternal: React.FC<GitHubStarsProps> = ({
  username = "",
  repository,
  repositories,
  token,
  useMockData = false,
  variant = "card",
  layout = "grid",
  showDescription = true,
  showTopics = true,
  showStats = true,
  showOwner = true,
  showLanguage = true,
  showActivity = false,
  showTrending = false,
  showMilestones = false,
  showComparison = false,
  showHistory = false,
  sortBy = "stars",
  maxItems = 6,
  autoRefresh = false,
  refreshInterval = 300000,
  enableNotifications = false,
  enableExport = true,
  enableAnalytics = false,
  cacheEnabled = true,
  cacheDuration = 300000,
  animation = "fade",
  animationDuration = 0.3,
  staggerDelay = 0.05,
  milestones = [10, 50, 100, 500, 1000, 5000, 10000],
  celebrateAt = [100, 1000, 10000],
  onRepositoryClick,
  onStarClick,
  onMilestoneReached,
  onDataUpdate,
  onError,
  className,
  theme = "auto",
  size = "md",
  customColors,
}) => {
  // Docs mode tespiti
  // Check if component has valid props to render
  const hasValidProps = useMockData || username || (repositories && repositories.length > 0)
  
  // If useMockData is false and no valid data props, don't render
  if (!useMockData && !hasValidProps) {
    return null
  }

  const isDocsMode = typeof window !== "undefined" && 
    (window.location.pathname.includes("/docs/") || 
     window.location.pathname.includes("/components/"))
  
  // Override some features in docs mode
  const effectiveAutoRefresh = isDocsMode ? false : autoRefresh
  const effectiveNotifications = isDocsMode ? false : enableNotifications
  const effectiveRefreshInterval = isDocsMode ? 3600000 : refreshInterval // 1 hour in docs mode
  const { notify } = useGitHubNotifications(effectiveNotifications)

  // onMilestoneReached callback'ini memoize et
  const handleMilestoneReached = React.useCallback((milestone: any) => {
    // Handle milestone reached
    if (celebrateAt?.includes(milestone.count)) {
      // Trigger celebration animation
      confetti({
        particleCount: 100,
        spread: 70,
        origin: { y: 0.6 },
      })
      
      // Show notification
      notify(`🎉 Milestone Reached!`, {
        body: `${milestone.count} stars achieved!`,
        tag: `milestone-${milestone.count}`,
      })
    }
    
    onMilestoneReached?.(milestone)
  }, [celebrateAt, notify, onMilestoneReached])

  const {
    repos,
    stats,
    loading,
    error,
    rateLimitInfo,
    lastUpdated,
    refresh,
  } = useGitHubData({
    username,
    repository,
    repositories,
    token,
    autoRefresh: effectiveAutoRefresh,
    refreshInterval: effectiveRefreshInterval,
    sortBy,
    maxItems,
    onError,
    onDataUpdate,
    onMilestoneReached: handleMilestoneReached,
    milestones,
    docsMode: isDocsMode, // Docs mode flag'ini gönder
    mockDataFallback: true, // Use mock data in docs mode
    forceMockData: useMockData, // Force mock data if true
  })

  const handleExport = React.useCallback((format: "json" | "csv") => {
    if (!enableExport) return

    const timestamp = new Date().toISOString().split("T")[0]
    
    if (format === "json") {
      exportData(
        { repositories: repos, statistics: stats, exportDate: new Date() },
        `github-stars-${username}-${timestamp}.json`
      )
    } else {
      exportAsCSV(repos, `github-stars-${username}-${timestamp}.csv`)
    }
  }, [enableExport, repos, stats, username])

  // handleDetailedExport fonksiyonunu memoize et
  const handleDetailedExport = React.useCallback((e: React.MouseEvent) => {
    if (!enableExport) return
    
    // Show export dropdown
    const dropdown = document.createElement("div")
    dropdown.className = "absolute z-50 mt-2 w-48 rounded-md shadow-lg bg-popover border"
    dropdown.innerHTML = `
      <div class="py-1">
        <button class="w-full text-left px-4 py-2 text-sm hover:bg-accent" data-format="json">
          Export as JSON
        </button>
        <button class="w-full text-left px-4 py-2 text-sm hover:bg-accent" data-format="csv">
          Export as CSV
        </button>
      </div>
    `
    
    dropdown.addEventListener("click", (e) => {
      const target = e.target as HTMLElement
      const format = target.getAttribute("data-format")
      if (format === "json" || format === "csv") {
        handleExport(format)
        dropdown.remove()
      }
    })
    
    document.body.appendChild(dropdown)
    
    // Position dropdown
    const rect = (e.target as HTMLElement).getBoundingClientRect()
    dropdown.style.top = `${rect.bottom + window.scrollY}px`
    dropdown.style.left = `${rect.left + window.scrollX}px`
    
    // Remove on outside click
    setTimeout(() => {
      document.addEventListener("click", () => dropdown.remove(), { once: true })
    }, 0)
  }, [enableExport, handleExport])

  // Loading state
  if (loading) {
    return (
      <Card className={cn("w-full", className)}>
        <CardContent className="p-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <Skeleton className="h-6 w-48" />
              <Skeleton className="h-8 w-20" />
            </div>
            <div className={cn(
              layout === "grid" 
                ? "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"
                : "space-y-4"
            )}>
              {Array.from({ length: maxItems || 6 }).map((_, index) => (
                <Card key={index}>
                  <CardContent className="p-4">
                    <div className="space-y-3">
                      <Skeleton className="h-5 w-3/4" />
                      <Skeleton className="h-4 w-full" />
                      <Skeleton className="h-4 w-2/3" />
                      <div className="flex gap-2">
                        <Skeleton className="h-6 w-16" />
                        <Skeleton className="h-6 w-16" />
                        <Skeleton className="h-6 w-16" />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  // Error state
  if (error) {
    return (
      <Card className={cn("w-full", className)}>
        <CardContent className="p-6 text-center">
          <div className="space-y-4">
            <div className="text-destructive">
              <Github className="h-12 w-12 mx-auto mb-2" />
              <h3 className="font-semibold">Failed to load repositories</h3>
              <p className="text-sm text-muted-foreground">{error}</p>
              {rateLimitInfo && rateLimitInfo.remaining === 0 && (
                <p className="text-xs text-muted-foreground mt-2">
                  Rate limit will reset at {new Date(rateLimitInfo.reset).toLocaleTimeString()}
                </p>
              )}
            </div>
            <Button onClick={refresh} variant="outline">
              <RefreshCw className="h-4 w-4 mr-2" />
              Try Again
            </Button>
          </div>
        </CardContent>
      </Card>
    )
  }

  // Render based on variant
  const renderVariant = () => {
    const baseProps = {
      repos,
      stats,
      loading,
      className,
      onRepositoryClick,
    }

    switch (variant) {
      case "minimal":
        return <MinimalVariant {...baseProps} />
      case "compact":
        return <CompactVariant {...baseProps} />
      case "detailed":
        return (
          <DetailedVariant 
            {...baseProps} 
            onExport={() => handleDetailedExport({} as React.MouseEvent)}
          />
        )
      case "card":
      default:
        return <CardVariant {...baseProps} />
    }
  }

  // Apply animation wrapper
  const animationVariants = {
    bounce: {
      initial: { scale: 0.9, opacity: 0 },
      animate: { scale: 1, opacity: 1 },
      transition: { type: "spring", stiffness: 300, damping: 20 },
    },
    pulse: {
      initial: { scale: 0.95, opacity: 0 },
      animate: { scale: 1, opacity: 1 },
      transition: { duration: animationDuration },
    },
    fade: {
      initial: { opacity: 0 },
      animate: { opacity: 1 },
      transition: { duration: animationDuration },
    },
    scale: {
      initial: { scale: 0, opacity: 0 },
      animate: { scale: 1, opacity: 1 },
      transition: { duration: animationDuration },
    },
    slide: {
      initial: { x: -20, opacity: 0 },
      animate: { x: 0, opacity: 1 },
      transition: { duration: animationDuration },
    },
    none: {
      initial: {},
      animate: {},
      transition: {},
    },
  }

  const selectedAnimation = animationVariants[animation]

  return (
    <motion.div
      {...selectedAnimation}
      className={cn("w-full", className)}
    >
      {renderVariant()}
      
      {/* Rate limit warning - Don't show in docs mode */}
      {!isDocsMode && rateLimitInfo && rateLimitInfo.remaining < 10 && (
        <div className="mt-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-md text-sm">
          <p className="text-yellow-800 dark:text-yellow-200">
            ⚠️ Low API rate limit: {rateLimitInfo.remaining} requests remaining.
            {token ? "" : " Consider adding a GitHub token for higher limits."}
          </p>
        </div>
      )}
      
      {/* Docs mode indicator - only show in development mode */}
      {isDocsMode && process.env.NODE_ENV === "development" && (
        <div className="mt-2 text-xs text-muted-foreground text-center">
          📚 Docs Mode: API requests optimized
        </div>
      )}
    </motion.div>
  )
}

export const GitHubStars: React.FC<GitHubStarsProps> = ({ className, ...props }) => {
  // Check if we're in docs mode or have pro access
  const { hasProAccess, isLoading } = useSubscription()
  
  // If not in docs mode and no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-fit", className)}>
        <CardContent className="py-6 text-center">
          <div className="space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-xs mb-4">
                GitHub Stars is available exclusively to MoonUI Pro subscribers.
              </p>
              <a href="/pricing">
                <Button size="sm">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Upgrade to Pro
                </Button>
              </a>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <GitHubStarsInternal className={className} {...props} />
}

export type { GitHubRepository, GitHubStarsProps } from "./types"
export { LANGUAGE_COLORS } from "./github-api"