"use client"

import React from 'react'
import { motion } from 'framer-motion'
import { Card } from '../../ui/card'
import { cn } from '../../../lib/utils'
import { 
  TrendingUp, 
  TrendingDown, 
  Minus,
  ArrowUpRight,
  ArrowDownRight,
  MoreVertical,
  Maximize2,
  Download,
  Share2
} from 'lucide-react'
import { MetricData } from '../types'
import { Button } from '../../ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../../ui/dropdown-menu'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/tooltip'

interface MetricCardProps {
  data: MetricData
  onClick?: () => void
  onAction?: (action: string) => void
  className?: string
  showSparkline?: boolean
  showForecast?: boolean
  interactive?: boolean
  glassmorphism?: boolean
}

export function MetricCard({
  data,
  onClick,
  onAction,
  className,
  showSparkline = true,
  showForecast = false,
  interactive = true,
  glassmorphism = false
}: MetricCardProps) {
  const [isHovered, setIsHovered] = React.useState(false)

  // Renk sınıfları
  const colorClasses = {
    primary: 'text-blue-600 dark:text-blue-400',
    success: 'text-green-600 dark:text-green-400',
    warning: 'text-yellow-600 dark:text-yellow-400',
    danger: 'text-red-600 dark:text-red-400',
    info: 'text-purple-600 dark:text-purple-400'
  }

  // Değişim renkleri
  const getChangeColor = (type: 'increase' | 'decrease' | 'neutral') => {
    switch (type) {
      case 'increase':
        return 'text-green-600 dark:text-green-400'
      case 'decrease':
        return 'text-red-600 dark:text-red-400'
      default:
        return 'text-muted-foreground'
    }
  }

  // Değişim ikonu
  const getChangeIcon = (type: 'increase' | 'decrease' | 'neutral') => {
    switch (type) {
      case 'increase':
        return <ArrowUpRight className="h-4 w-4" />
      case 'decrease':
        return <ArrowDownRight className="h-4 w-4" />
      default:
        return <Minus className="h-4 w-4" />
    }
  }

  // Sparkline çizimi
  const renderSparkline = () => {
    if (!data.sparkline || data.sparkline.length < 2) return null

    const max = Math.max(...data.sparkline)
    const min = Math.min(...data.sparkline)
    const range = max - min || 1

    const points = data.sparkline
      .map((value, index) => {
        const x = (index / (data.sparkline!.length - 1)) * 100
        const y = 100 - ((value - min) / range) * 100
        return `${x},${y}`
      })
      .join(' ')

    const gradientId = `gradient-${data.id}`

    return (
      <motion.div 
        className="absolute bottom-0 left-0 right-0 h-16 overflow-hidden rounded-b-lg opacity-20"
        initial={{ opacity: 0 }}
        animate={{ opacity: isHovered ? 0.3 : 0.2 }}
        transition={{ duration: 0.2 }}
      >
        <svg
          className="w-full h-full"
          viewBox="0 0 100 100"
          preserveAspectRatio="none"
        >
          <defs>
            <linearGradient id={gradientId} x1="0%" y1="0%" x2="0%" y2="100%">
              <stop offset="0%" stopColor="currentColor" stopOpacity="0.3" />
              <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
            </linearGradient>
          </defs>
          <polyline
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            points={points}
            className={colorClasses[data.color || 'primary']}
          />
          <polygon
            fill={`url(#${gradientId})`}
            points={`0,100 ${points} 100,100`}
            className={colorClasses[data.color || 'primary']}
          />
        </svg>
      </motion.div>
    )
  }

  // İlerleme barı (hedef varsa)
  const renderProgress = () => {
    if (!data.target) return null

    const currentValue = typeof data.value === 'number' ? data.value : parseFloat(data.value as string)
    const progress = (currentValue / data.target) * 100

    return (
      <motion.div 
        className="mt-3"
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
      >
        <div className="flex justify-between text-xs text-muted-foreground mb-1">
          <span>Progress to target</span>
          <span>{progress.toFixed(1)}%</span>
        </div>
        <div className="h-1.5 bg-muted rounded-full overflow-hidden">
          <motion.div
            className={cn(
              "h-full rounded-full",
              progress >= 100 ? 'bg-green-500' : 'bg-primary'
            )}
            initial={{ width: 0 }}
            animate={{ width: `${Math.min(progress, 100)}%` }}
            transition={{ duration: 0.5, ease: "easeOut" }}
          />
        </div>
        <div className="flex justify-between text-xs text-muted-foreground mt-1">
          <span>{currentValue} {data.unit}</span>
          <span>Target: {data.target} {data.unit}</span>
        </div>
      </motion.div>
    )
  }

  // Değer formatı
  const formatValue = (value: string | number): string => {
    if (typeof value === 'number') {
      if (value >= 1000000) {
        return (value / 1000000).toFixed(1) + 'M'
      } else if (value >= 1000) {
        return (value / 1000).toFixed(1) + 'K'
      }
      return value.toLocaleString()
    }
    return value.toString()
  }

  // Card variants
  const cardVariants = {
    initial: { opacity: 0, y: 20 },
    animate: { 
      opacity: 1, 
      y: 0,
      transition: { duration: 0.3, ease: "easeOut" }
    },
    hover: interactive ? {
      y: -2,
      transition: { duration: 0.2 }
    } : {}
  }

  return (
    <motion.div
      variants={cardVariants}
      initial="initial"
      animate="animate"
      whileHover="hover"
      onHoverStart={() => setIsHovered(true)}
      onHoverEnd={() => setIsHovered(false)}
    >
      <Card 
        className={cn(
          "relative overflow-hidden cursor-pointer transition-all duration-300",
          interactive && "hover:shadow-lg hover:shadow-primary/5",
          glassmorphism && "bg-background/60 backdrop-blur-md border-white/10",
          className
        )}
        onClick={onClick}
      >
        {/* Açık arka plan efekti */}
        {glassmorphism && (
          <div className="absolute inset-0 bg-gradient-to-br from-primary/5 to-transparent" />
        )}

        {/* Üst bar */}
        <div className="flex items-center justify-between p-4 pb-2">
          <div className="flex items-center gap-3">
            <motion.div 
              className={cn(
                "p-2 rounded-lg",
                glassmorphism ? "bg-white/10 backdrop-blur" : "bg-muted"
              )}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <div className={cn("h-5 w-5", colorClasses[data.color || 'primary'])}>
                {data.icon}
              </div>
            </motion.div>
            <div>
              <h3 className="text-sm font-medium text-muted-foreground">{data.title}</h3>
            </div>
          </div>

          {/* Aksiyonlar */}
          {interactive && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  className="h-8 w-8 p-0"
                  onClick={(e) => e.stopPropagation()}
                >
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => onAction?.('fullscreen')}>
                  <Maximize2 className="mr-2 h-4 w-4" />
                  Fullscreen
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => onAction?.('export')}>
                  <Download className="mr-2 h-4 w-4" />
                  Export Data
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => onAction?.('share')}>
                  <Share2 className="mr-2 h-4 w-4" />
                  Share
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>

        {/* Ana değer */}
        <div className="px-4 pb-4">
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <motion.div 
                  className="text-3xl font-bold tracking-tight"
                  animate={{ 
                    scale: isHovered ? 1.02 : 1,
                  }}
                  transition={{ duration: 0.2 }}
                >
                  {formatValue(data.value)}
                  {data.unit && <span className="text-lg ml-1 text-muted-foreground">{data.unit}</span>}
                </motion.div>
              </TooltipTrigger>
              <TooltipContent>
                <p>Exact value: {data.value} {data.unit}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>

          {/* Değişim göstergesi */}
          {data.change && (
            <motion.div 
              className={cn(
                "flex items-center gap-1 text-sm mt-2",
                getChangeColor(data.change.type)
              )}
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.1 }}
            >
              {getChangeIcon(data.change.type)}
              <span className="font-medium">
                {data.change.type === 'neutral' ? '' : data.change.type === 'increase' ? '+' : '-'}
                {Math.abs(data.change.value)}%
              </span>
              <span className="text-muted-foreground">
                from {data.change.period}
              </span>
            </motion.div>
          )}

          {/* Tahmin */}
          {showForecast && data.forecast && (
            <motion.div 
              className="flex items-center gap-1 text-xs text-muted-foreground mt-1"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.2 }}
            >
              <TrendingUp className="h-3 w-3" />
              <span>Forecast: {formatValue(data.forecast)} {data.unit}</span>
            </motion.div>
          )}

          {/* İlerleme barı */}
          {renderProgress()}
        </div>

        {/* Sparkline */}
        {showSparkline && renderSparkline()}
      </Card>
    </motion.div>
  )
}

export default MetricCard